python/ django/ django-models/ django-forms/ django-views
I Managed to Filter the ForeignKey choices "Context.name" by "request.user" with the Code Below. First, I defined the Models.
models.py
class Extension(models.Model):
username = models.CharField(primary_key=True, max_length=200, help_text='')
callerid = models.CharField(max_length=200, help_text='')
extension = models.CharField(max_length=3, help_text='')
firstname = models.CharField(max_length=200, help_text='')
lastname = models.CharField(max_length=200, help_text='')
password = models.CharField(max_length=200, help_text='')
context = models.ForeignKey('Context', on_delete=models.SET_NULL, null=True)
def get_absolute_url(self):
return reverse('extension-detail', args=[str(self.username)])
def my_get_absolute_url(self):
return reverse('my-extension-detail', args=[str(self.username)])
def __str__(self):
return self.username
class Context(models.Model):
name = models.CharField(primary_key=True, max_length=200, help_text='')
countryprefix = models.CharField(max_length=200, help_text='')
cityprefix = models.CharField(max_length=200, help_text='')
number = models.CharField(max_length=200, help_text='')
extensionsfrom = models.CharField(max_length=200, help_text='')
extensionstill = models.CharField(max_length=200, help_text='')
portscount = models.CharField(max_length=200, help_text='')
def get_absolute_url(self):
return reverse('context-detail', args=[str(self.name)])
def my_get_absolute_url(self):
return reverse('my-context-detail', args=[str(self.name)])
def __str__(self):
return self.name
According to this model I created a ModelForm with an initial section init , in which the username will be grabbed.
The available contexts will then be filtered by the username.
forms.py
# __init__ stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform/1244586#1244586
# ModelForm learningaboutelectronics.com/Articles/How-to-save-data-from-a-form-to-a-database-table-in-Django.php
# commit tutorial.djangogirls.org/en/django_forms/#saving-the-form
class MyExtensionCreateForm(forms.ModelForm):
def __init__(self, context, *args, **kwargs):
name = kwargs.pop('user')
super(MyExtensionCreateForm, self).__init__(*args, **kwargs)
self.fields['context'].queryset = Context.objects.filter(name=name)
class Meta:
model = Extension
fields = '__all__'
# fields= ["firstname", "lastname", "extension", "password"]
# def clean_data(self):
# data = self.cleaned_data
# # Remember to always return the cleaned data.
# return data
Than in the view I basically want to just save the to the database.
The user=request.user part of the Form Call will pass the username to the ModelForm so we can filter the choices like we did in the forms.py.
views.py
def MyExtensionCreate(request):
# If this is a POST request then process the Form data
# if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding) AND pass the username to the Form
form = MyExtensionCreateForm(request.POST or None, user=request.user)
# Check if the form is valid:
if form.is_valid():
form = form.save(commit=False)
# process the data in form.cleaned_data as required
# form.callerid = "Max"
# form.username = "telba.de_888"
# form.context = str(request.user)
# form.context.queryset = Context.objects.filter(name=request.user)
form.save()
# Return to the Extensions List View "My Extensions"
return HttpResponseRedirect(reverse('my-extensions'))
# Return to the newly created Extension Detail View
# return redirect('extension-detail', pk=post.pk)
# If this is a GET (or any other method) create the default form.
# else:
# # Predefine the Extension.context Attribute with the current Username in GET
# form = MyExtensionCreateForm({'context': request.user})
context = {
'form': form,
}
# def get_form_kwargs(self):
# kwargs = super(MyExtensionCreate, self).get_form_kwargs()
# kwargs.update({'user': request.user})
# return kwargs
return render(request, 'catalog/extension_form-by-user.html', context)
I created a little Video to show of the Current behavior of the Form.
Video of the Form:
I can view the form, and the choices will be limited like I want them to be. But submitting the Form will just reload the Page and does nothing besides it. So it does not save the Values to the Database, and I don't get any Error.
Please, can anyone help me out here?
You have changed the signature of the form's __init__
method to take context
as the first positional argument. This means that the POST data is not being passed to the form.
I don't know why you are doing that, as you never use context
. Remove that argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.