MultichoiceField in ModelForm for Django with DB relations

MultichoiceField in ModelForm for Django with DB relations

By : Pascal Simon
Date : December 01 2020, 04:52 PM
this one helps. This is my first post ever on Stackoverflow so please ignore mistakes. Before posting I had tried a dozen solutions bun none worked. I have table relations in models for users. I need to create a ModelForm to let customer select multiple users for any project from the frontend. I am having hard time implementing it in code. Also for another field I need to limit the choice to one user. Following is the code. , forms.py:
code :
from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        assigned_users = kwargs.pop('assigned_to', [])
        super(ProjectForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs = {"class": "form-control"}
        self.fields['project_name'].required = True
        self.fields['project_url'].required = True

        if assigned_users:
            self.fields['assigned_to'].queryset = assigned_users
        self.fields['assigned_to'].required = True

            'placeholder': 'Project Name'})
            'placeholder': 'Project URL'})
    class Meta:
        model = Project
        fields = ('project_name', 'project_url', 'assigned_to')
def create_project(request):
    template_name = "create.html"
    users = []

    form = ProjectForm(assigned_to=users)

    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES, assigned_to=users)
        if form.is_valid():
            proj_obj = form.save(commit=False)
            proj_obj.created_by = request.user

            if request.POST.getlist('assigned_to', []):
                assigned_to_list = request.POST.getlist('assigned_to')
            success_url = reverse('projects:list')
            if request.POST.get("savenewform"):
                success_url = reverse("leads:add_lead")
            return JsonResponse({'error': False, 'success_url': success_url})
        return JsonResponse({'error': True, 'errors': form.errors})
    context = {}
    context["proj_form"] = form
    context["users"] = users

    context["assignedto_list"] = [
        int(i) for i in request.POST.getlist('assigned_to', []) if i]

    return render(request, template_name, context)
<div class="form-control">
    {{ proj_form.project_name }}
    {{ proj_form.assigned_to }}
    {{ proj_form.project_url }}


Share : facebook icon twitter icon
Django: CSS class does not show for ModelForm that extends another ModelForm

Django: CSS class does not show for ModelForm that extends another ModelForm

By : Ujala
Date : March 29 2020, 07:55 AM
I wish this help you Found out what the problem was: incorrect updating the widget dictionary. The class MyModelForm should look as following:
code :
class MyModelForm(BaseModelForm):
    class Meta(BaseModelForm.Meta):
        model = MyModel
        fields = BaseModelForm.Meta.fields + ("title",)
        widgets = BaseModelForm.Meta.widgets
        "title" : TextInput(attrs={"class" : "title"}),
How to set User-based form field choices in a django ModelForm (with django-allauth)

How to set User-based form field choices in a django ModelForm (with django-allauth)

By : siddhu
Date : March 29 2020, 07:55 AM
Hope this helps Since this needs the currently logged in user then you have to do it in the View where you override the form characters QuerySet based on your user.
code :
form.character.queryset = Character.objects.filter(....)
Django - MultiChoiceField to_field_name and selected

Django - MultiChoiceField to_field_name and selected

By : Bilel Kharrati
Date : March 29 2020, 07:55 AM
hope this fix your issue Well, I managed to achieve what I wanted. As suggested by @Alasdair, I created an intermediary model.
code :
class Model1(models.Model):
name = models.Charfield(...)
muscles = models.ManyToManyField(Model2, blank=True, null=True,)

class Model2(models.Model):
    name = models.CharField(...)
    field1 = models.CharField(...)

class Model1Model2(models.Model):
    model1 = models.ForeignKey(Model1)
    model2 = models.ForeignKey(Model2)

class MyForm(ModelForm):
    muscles = forms.ModelMultipleChoiceField(
                                to_field_name="field1", required=False,)

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)

    self.fields['muscles'].queryset = Model2.objects.all()
Django ModelForm fails to save "many to many" records using ModelForm and save_m2m

Django ModelForm fails to save "many to many" records using ModelForm and save_m2m

By : Hai Kara
Date : March 29 2020, 07:55 AM
should help you out hope this solve your problem just but this line after save your journal instance journal.crypto_id.set(form.cleaned_data.get("cryptos"))
How can I apply filter to Django modelform and return form to view in Django?

How can I apply filter to Django modelform and return form to view in Django?

By : OscarES
Date : March 29 2020, 07:55 AM
like below fixes the issue I found the way for this while fetching objects we can filter using limit_choices_to in model fields like this...
code :
manager = models.ForeignKey(User, on_delete=models.PROTECT, limit_choices_to={'is_admin':False})
Related Posts Related Posts :
  • redux how to use state
  • All data in the db is lost when closing a express based node js server
  • How to convert javascript code for Angular
  • XPath select on child nodes
  • Idle event on mouse move - how to stop script permanently on mouse move
  • Why do I get logic is not defined in this code
  • When I enter a number in the input, the first function starts
  • ES6 imports and node_modules hell
  • How to get css selector of clicked-on element?
  • How to auto input MySQL data (input column 1 data to auto input column 2 data with same column) in php?
  • Appending to Datalist Via Javascript
  • Customizing Material-UI Components with Styled-Components
  • Populate elements with class name using Javascript
  • How to execute promises in batches (first resolving 10, then next 10 and so on)
  • Maximo JS automation script: "importPackage" is not defined
  • How to surround selected text inside textarea with <em> on key combination CTRL+i?
  • Your configured registry does not support audit requests ~ On npm audit
  • What's the Angular equivalent of Vue <slot/>?
  • Iconify icon not updating when "data-icon" set with setAttribute()
  • Javascript newbie stuck with XMLHttpRequest return data
  • How to add obj to to state in my example Redux React
  • Loading "grunt-karma.js" tasks...ERROR >> SyntaxError: Unexpected identifier
  • Why do I get log is not defined
  • get the multiple index of the same string
  • How can I iterate over an Array object by using For IN or FOR OF
  • Launch local executable from web browser
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org