logo
down
shadow

Test if Django ModelForm has instance on customized model


Test if Django ModelForm has instance on customized model

Content Index :

Test if Django ModelForm has instance on customized model
Tag : python , By : alexmajy
Date : December 01 2020, 05:00 PM

it fixes the issue If your model has a primary key column, than pk property of that model will always be there and be an alias to that field.
In your case you do not want to check if your form.instance has a property named pk (that's the hasattr line). Instead you have to check if the property pk of form.instance is empty or not:
data = {'myid': '123'}
form = MyModelForm(data=data, instance=None)
form.is_valid()
if form.instance.pk: 
     print('This has a pk! It was saved before!')
else:
     print('This has no pk! It was never saved!')

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Access Django model instance in ModelForm's FormField definions


Tag : django , By : user123284
Date : March 29 2020, 07:55 AM
it helps some times in one of my admin forms, I override a model form field (location) in order to use a different, map specific form field (olwidget). This MapField should include a layer (InfoLayerField) that displays all other model instances but the one that is being edited at the moment. Right now, it displays all the model instances (see MyModel.objects.all()) which means, if a model is edited the current location is displayed twice. , I think you just need to override the __init__ on your form:
class MyModelAdminForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self,*args,**kwargs):
        super(MyModelAdminForm, self).__init__(*args,**kwargs)
        qs = MyModel.objects.exclude(pk = self.instance.pk) #grab instance.pk here
        self.fields['location'] = MapField([
            EditableLayerField({
                'geometry': 'point',
                'name': 'location',
            }),
            InfoLayerField(
                [(get_ewkt(m.location), m.name) for m in qs if m.location ], {
                    'geometry': 'point',
                    'name': 'other locations',
                    'cluster': True,
                    'cluster_display': 'list',
                }
            )
        ])

Test if Django ModelForm has instance


Tag : django , By : pacorro2000
Date : March 29 2020, 07:55 AM
help you fix your problem Try checking if form.instance.pk is None.
hasattr(form.instance, 'pk') will always return True, because every model instance has a pk field, even when it has not yet been saved to the database.

Difference between Django ModelForm and Model instance save methods


Tag : python , By : johntynan
Date : March 29 2020, 07:55 AM
it fixes the issue In the commented line you have, project.save() simply won't do anything. The instance has not been updated with the form data, it is simply the empty instance you created two lines before. The only way to update an existing instance is by saving its form.

Django restrict options of ManyToMany field in ModelForm based on model instance


Tag : django , By : inquiringmind
Date : March 29 2020, 07:55 AM
will be helpful for those in need The instance setting has nothing to do with limiting the choices. In essence, it simply populates the form's values with the ones from a specific record. You usually provide an instance in an edit operation, whereas you skip it in an add operation.
The representation of a models.ManyToManyField in the ModelForm is a forms.ChoiceField for which you can simply override its queryset property, and specify the queryset you desire.
form = OrderForm()
form.fields['color'].queryset = Design.object.all()  # for example

Django: select a instance of a parent model at ModelForm


Tag : python , By : Edwin
Date : March 29 2020, 07:55 AM
Hope this helps I've just solved. By adding name="product", I've achieved it. Thank you for your cooperation!
  <select>
    {% for product in products %}
      <option value="{{ product.id }}">{{ product.name}}</option>
      <div class="error">{{ form.product.id.errors }}</div>
    {% endfor %}
  </select>

  <select name="product">
    {% for product in products %}
      <option value="{{ product.id }}">{{ product.name}}</option>
      <div class="error">{{ form.product.id.errors }}</div>
    {% endfor %}
  </select>
Related Posts Related QUESTIONS :
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com