Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generate fields from enum in django-graphene?
I am trying to accomplish the following scheme: distance { km mi } That will return distance to some object. There is enum of all possible distances, and I want to generate them automatically. So far, I came with the following code: DISTANCE_FIELD_CHOICES = D.UNITS.keys() distance_fields = { k: graphene.Float(description=f'{k} measurement') for k in DISTANCE_FIELD_CHOICES } DistanceField = type('DistanceField', (graphene.ObjectType,), distance_fields) It works as desired, but I am convinced that there should be a simpler way, without implicit usage of metaclasses. -
QuerySet: Filter for entries
I want to show all answers for question__focus=QuestionFocus.REASON_FOR_ATTENDING where question__focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS is >= 9. The answer field is not an integer field, but a TextField as all questions share the same Answer model. I tried a lot, but nothing worked for me so far. I first tried to go from the Answer model, but that also didn't work as I filter for different answers than what I want to show at the end. event = Event.objects.get(pk=12) survey = event.surveys.get( template=settings.SURVEY_POST_EVENT ).questions.[HOW TO CONTINUE?] models.py class Survey(TimeStampedModel): class SurveyTemplate(Choices): CHOICES = ((survey, survey) for survey in settings.SURVEY_TEMPLATES.keys()) id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) event = models.ForeignKey( "events.Event", on_delete=models.CASCADE, related_name="surveys" ) is_active = models.BooleanField(default=False, verbose_name=_("Is active?")) template = models.CharField( max_length=SurveyTemplate.get_max_length(), choices=SurveyTemplate.CHOICES, verbose_name=_("Survey template"), ) class Response(TimeStampedModel): class Language(Choices): CHOICES = settings.LANGUAGES survey = models.ForeignKey( "surveys.Survey", on_delete=models.CASCADE, related_name="responses" ) order = models.ForeignKey( "orders.Order", on_delete=models.SET_NULL, null=True, blank=True, related_name="response", ) attendee = models.ForeignKey( "attendees.Attendee", on_delete=models.SET_NULL, null=True, blank=True, related_name="response", ) total_time = models.PositiveIntegerField( null=True, blank=True, verbose_name=_("Total time") ) ip_address = models.GenericIPAddressField(null=True, verbose_name=_("IP Address")) language = models.CharField( max_length=Language.get_max_length(), choices=Language.CHOICES, verbose_name=_("Language"), ) class Answer(TimeStampedModel): question = models.ForeignKey( "surveys.Question", on_delete=models.CASCADE, related_name="answers" ) response = models.ForeignKey( "Response", on_delete=models.CASCADE, related_name="answers" ) answer = models.TextField(verbose_name=_("Answer")) choices = models.ManyToManyField( "surveys.AnswerOption", related_name="answers", blank=True ) class Question(TimeStampedModel): … -
2 Forms in a django template using cookiecutter-django
I'm creating 2 forms on one template in cookiecutter-django. I have both forms working on a normal django project but when I migrated them to cookiecutter-django, the forms did not work on the user_detail template. This is the forms.py class NarrateForm(ModelForm): class Meta: model = Narrate fields = [ 'title', 'body', ] exclude = ('status',) class TranslateForm(ModelForm): class Meta: model = Translate fields = [ 'title', 'body', ] exclude = ('status',) These are the views.py of forms that I have: class TranslateFormView(FormView): form_class = TranslateForm template_name = 'user_detail.html' def post(self, request, *args, **kwargs): add_translation = self.form_class(request.POST) add_narration = NarrateForm() if add_translation.is_valid(): add_translation.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( add_translation=add_translation, ) ) class NarrateFormView(FormView): form_class = NarrateForm template_name = 'users/user_detail.html' def post(self, request, *args, **kwargs): add_narration = self.form_class(request.POST) add_translation = TranslateForm() if add_narration.is_valid(): add_narration.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( add_narration=add_narration, ) ) Now this is the view of the user_details from cookiecutter-django class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "username" slug_url_kwarg = "username" user_detail_view = UserDetailView.as_view() This is the code on the template which works on the old django project <form method="POST" action="#"> {% csrf_token %} {{ add_narration }} <button type="submit" … -
Update other models field when new record adds
I am working on Question-Answer Website. In that i want to mark Question hasAnswered whenever new Answer adds for that question. Question Model class Question(models.Model): question = models.CharField(max_length=400) uid = models.ForeignKey("User",on_delete=models.SET_DEFAULT,default=1,related_name='user_q_id_set') vote = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) catitle = models.ForeignKey("Category", on_delete=models.CASCADE) editUser = models.ManyToManyField("User",related_name='user_q_edit_set',null=True,blank=True) hasAnswer = models.BooleanField(default=False) Answer Model class Answer(models.Model): answer = models.TextField() qid = models.ManyToManyField("Question") uid = models.ForeignKey("User",on_delete=models.CASCADE,related_name='user_a_id_set') vote = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) editUser = models.ManyToManyField("User",related_name='user_a_edit_set',null=True,blank=True) class Meta: ordering = ['-vote'] def save(self,*args, **kwargs): self.qid.hasAnswer=True This is what i tried but got error ValueError at /admin/qa/answer/add/ "<Answer: None>" needs to have a value for field "id" before this many-to-many relationship can be used. So how i get change hasAnswer to True whenever new Answer Adds ? -
How to insist on https in browsable api
I have a Django Rest Framework running at: https://dev-example.domain.com in kubernetes behind an ingress with http traffic disabled. Therefore, trying to go to http://dev-example.domain.com returns a 404. Rightfully. In the Browsable api, however, all links are prefixed with http::// Therefore, when one of these links is clicked on, the redirect returns a 404. Is there a setting that will allow that prefix to be https? -
Passing queryset instance django inlineformset factory?
I am filtering a queryset and trying to pass the filtered queryset to a Formset instance. However, when I try to render the formset, I get the error Queryset object has no attribute pk.I tried passing queryset instead of instance but when I pass Queryset nothing is being rendered in the template. What could I be doing wrong ? def get_context_data(self, **kwargs): data = super(CollectionCreate, self).get_context_data(**kwargs) if self.request.POST: data['formset1'] = WorkExperienceFormSet(self.request.POST,instance=WorkExperience.objects.exclude(company_name__isnull=True)) return data else: data['formset1'] = WorkExperienceFormSet(instance=WorkExperience.objects.exclude(company_name__isnull=True)) return data WorkExperienceFormSet = inlineformset_factory( UserProfile, WorkExperience, form=WorkExperienceForm, fields=['company_name', 'start_date','end_date','work_description'], can_delete=True,extra=1,max_num=5 ) Traceback <QuerySet [{'id': 20, 'user_id': 6, 'company_name': 'Mumsvillagessss', 'start_date': datetime.date(2013, 5, 21), 'end_date': datetime.date(2019, 11, 8), 'work_description': 'Test this'}, {'id': 23, 'user_id': 6, 'company_name': 'emmie', 'start_date': datetime.date(2013, 7, 7), 'end_date': datetime.date(2019, 11, 6), 'work_description': 'jfdjdj'}]> -
Using Django to display different features of a template in different "pages" of the project
I am working on the front-end of a website and now I am focusing on its responsive side. In the desktop design, I have four pages in total. Therefore, 4 main templates: page1.html (containing 3 features total), page2.html and so on. Hence, 4 top navbar items. In the phone design, I replaced the top navbar by a bottom navbar containing the same navbar items plus two additional ones. The additional items are features contained in page1.html. In the desktop design, page1.html shows all the 3 features. In the phone design, there are three bottom navbar items for each feature. Aiming to avoid having to create additional templates for those features, views and urls so the user does not "guess" the url (e.g. www.mywebsite.com/page1/feature... I would like to know if there is a way of showing each feature (of the same template) according to the active bottom navbar item. So if all three features found in page1.html have an independent bottom navbar item, when I have click on the navbar item of feature 1, features 2 and 3 would be hidden and feature one would be the one displaying. If I click on the navbar item of feature 2, features 1 … -
docker-compose and initializating a database
I have two docker containers, one Django and one PostgreSQL. My issue is that when I first run the containers, including the create step, using docker-compose up [--force-recreate] --build, the Django instance fails because it cannot connect to the database. Subsequent use of docker-compose up is fine. It looks to me like the database initialization is not complete before Django is started. I'm using the common 'environment variables' method to initialize the database. On a related note, is there a way to get the Django migrate done on first docker image creation too? -
Django: Filter answers
I have different questions that are all "collected" in the attached answer model. My goal is to show a table with question__focus=QuestionFocus.REASON_FOR_ATTENDING. The challenge I have is that I only want to show these answers, where QuestionFocus.RECOMMENDATION_TO_FRIENDS is >= 8. Do you have any idea how to do so? That's how far I got. The problem is that it now shows me the answers for RECOMMENDATION_TO_FRIENDS. But I need them for for REASON_FOR_ATTENDING. q = Answer.objects.filter( question__focus__in=(QuestionFocus.REASON_FOR_ATTENDING, QuestionFocus.RECOMMENDATION_TO_FRIENDS), response__survey__event=12, response__survey__template=settings.SURVEY_POST_EVENT, ).annotate( nps=Case( When(question__focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS, then=Cast('answer', output_field=IntegerField())), ), ).filter(nps__gte=8) models.py class Answer(TimeStampedModel): question = models.ForeignKey( "surveys.Question", on_delete=models.CASCADE, related_name="answers" ) response = models.ForeignKey( "Response", on_delete=models.CASCADE, related_name="answers" ) answer = models.TextField(verbose_name=_("Answer")) choices = models.ManyToManyField( "surveys.AnswerOption", related_name="answers", blank=True ) -
Check if username exist in database
Well i am creating a django based website and two user's can't have the same username. I want to check during registration if a username already exist then return a message in the register page to alert the person views.py from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) email = form.cleaned_data.get('email') emails = User.objects.filter(is_active=True).values_list('email', flat=True) username = form.cleaned_data.get('username') names = User.objects.filter(is_active=True).values_list('username', flat=True) if username in names: messages.error(request, 'Sorry. This username is taken', extra_tags='name') return redirect('register') else: user.save() messages.success(request, "New account created") return redirect('login') else: form = UserRegisterForm() return render(request, 'user/register.html', {'form': form}) register.html {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{message}} </div> {% endfor %} ``` Some help would be nice -
Tabs layout in Django
I am new in Django and exploring page design and layout. I want to put in the middle of the page tabs so that when i click Information tab it shows only contact information. However in my case none of i wanted to implement works. Could you please explain what i am doing worng. In my case it shows all information so no need to click different tabs to get certain information. {% extends "base.html" %} {% block content %} <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="pills-home-tab" data-toggle="pill" href="#pills-home" role="tab" aria-controls="pills-home" aria-selected="true">Summary</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-profile-tab" data-toggle="pill" href="#pills-profile" role="tab" aria-controls="pills-profile" aria-selected="false">Information</a> </li> <li class="nav-item"> <a class="nav-link" id="pills-contact-tab" data-toggle="pill" href="#pills-contact" role="tab" aria-controls="pills-contact" aria-selected="false">References</a> </li> </ul> <div class="tab-content" id="pills-tabContent"> <div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">...</div> <div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">A "Hello, World!" program is traditionally used to introduce novice programmers to a programming language. "Hello, World!" is also traditionally used in a sanity test to make sure that a computer language is correctly installed, and that the operator understands how to use it</div> <div class="tab-pane fade" id="pills-contact" role="tabpanel" aria-labelledby="pills-contact-tab"> Layla Freedman </div> </div> {% endblock content %} Could you please explain what … -
Cannot encode decode in django template
I am using django 2.2 and python 3.6. I have a django template html file. Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xe7 in position 1407: invalid continuation byte The string that could not be encoded/decoded was: "">Se�in If the string was in views.py i was able to encode decode it. But this string is manually put in html template file. If i delete this character it works fine. How can i encode decode this string in the template? -
Django: Check if updated field is already present in database
I am trying to update a django ModelForm with email as a field. In the create form, I am checking if the field is already present in database, if so raise validation error. That part is working as expected. however, if I use the same check in update form, it throws validation error as the existing record has the given email. Is there a direct method to ensure this validation? forms.py class MyObjCreateForm(forms.ModelForm): first_name = forms.CharField(max_length=50, label='First name') last_name = forms.CharField(max_length=50, label='Last name') email = forms.EmailField(label='Email') location = forms.ChoiceField(choices=TP_TM_Location, label='Location') designation = forms.ChoiceField(choices=TP_TM_Designation, label='Designation') date_of_joining = forms.DateField(label='Date of joining', widget=forms.TextInput(attrs={'type': 'date'}), initial=date.today()) username = forms.CharField(label='Login username') password = forms.CharField(widget=forms.PasswordInput(), label='Login password') current_status = forms.ChoiceField(choices=TP_Status, label='Current status') def clean_email(self): email = self.cleaned_data.get('email') try: match = MyObj.objects.get(email=email) raise forms.ValidationError("email already exists in system. Please check the existing list.") except MyObj.DoesNotExist: return email class MyObjUpdateForm(forms.ModelForm): first_name = forms.CharField(max_length=50, label='First name') last_name = forms.CharField(max_length=50, label='Last name') email = forms.EmailField(label='Email') location = forms.ChoiceField(choices=TP_TM_Location, label='Location') designation = forms.ChoiceField(choices=TP_TM_Designation, label='Designation') date_of_joining = forms.DateField(label='Date of joining', widget=forms.TextInput(attrs={'type': 'date'}), initial=date.today()) current_status = forms.ChoiceField(choices=TP_Status, label='Current status') username = forms.CharField(label='Login username') def clean_email(self): email = self.cleaned_data.get('email') try: match = MyObj.objects.get(email=email) raise forms.ValidationError("email already exists in system. Please check the existing list.") … -
Django - ModuleNotFoundError: No module named '“backend'
while setting up Django Development environment, I am encountering error while running Django local server: (env) ➜ blogsite python manage.py runserver Traceback (most recent call last): File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/achintsharma/Desktop/workspace/learning/blog-site/env/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named '“backend' Python version is 3.7.4. Just to resolve, I have tried: export DJANGO_SETTINGS_MODULE=“backend.settings.dev” Can anyone help me with this? -
How to distribute Django web app to users?
I am developing a Django app to run on every client computer separately. The question is, which technologies should I use to distribute such as docker, virtual machine etc.? How can I protect the Django app's code? How can I prevent to distribute without licenses? -
how child added firebase concept working?
I'm learning firebase and try to use child added firebase listener to show every data that i have added. But, when i just added a data, the listener read show more than once with same data I already use index variable to debug my code, but still don't know why it show more than once with same data. var chatref = firebase.database().ref('/candy').orderByChild('timestamp'); var parent = $('.candy_color'); parent.empty(); var index = 0; var date = null; chatref.on('child_added', function(snapshot) { var candy = ""; var data = snapshot.val(); var context = data.content; if(data.color == 'red' && data.pattern == 'waves'){ console.log("index first : "+index); candy += "<div class='m-messenger__message m-messenger__message--out'>"+data.color+"</div>"; parent.append(candy); console.log("content : "+data.color); console.log("index second: "+index); index++; console.log("index after added: "+index); } else if (data.color == 'green' && data.pattern == cracks){ console.log("index cracks first : "+index); candy += "<div class='m-messenger__message m-messenger__message--in'>"+data.color+"</div><div>"+data.pattern+"</div>"; parent.append(candy); console.log("contents : "+data.content); console.log("index cracks second: "+index); index++; } }); When i show for the first time (i have 3 candy data), it look normal, which index show in console.log are 0,1,2 and 'index after added' is 3 but when i add new data, the console log will display 3 and 'index after added' is 4, then display again 3 and … -
Automatically create another entry after user posts a data Django rest framework
when user submits a pet, the petid would be stored in the table 'likes' with the default value in numOflikes 0. I am not sure how to approach this other than doing 2 post requests which seems tedious What I tried: submitting a pet post request and then grabbing id and doing another post request for 'likes' Model class pet(models.Model): name = models.CharField(max_length=50) class likes(models.Model): petId = models.ForeignKey( "pet", on_delete=models.CASCADE, null=True) numOflikes = models.PositiveSmallIntegerField(default=0) Serializer class PetSerializer(serializers.ModelSerializer): class Meta: model = pet fields = '__all__' class LikesSerializer(serializers.ModelSerializer): class Meta: model = likes fields = '__all__' expected pet { "id": 1, "title": "dog", }, likes { "id": 1, "petid": 1 "numOflikes": 0 }, -
Django: Update value for a field in Update view
I am trying to show a update form for a model wherein I also want to show its parent object's field (just 1 field) in the same view. I created a forms.Form with all the model fields and 1 parent field and want to show the same form pre-filled in the update view. models.py class Teammember(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) location = models.CharField(max_length=50) designation = models.CharField(max_length=50) date_of_joining = models.DateField() current_status = models.CharField(max_length=50) def __str__(self): return self.first_name + " " + self.last_name def get_absolute_url(self): return reverse('teammember-detail', kwargs={'pk': self.pk}) forms.py class TeammemberUpdateForm(forms.Form): first_name = forms.CharField(max_length=50, label='First name') last_name = forms.CharField(max_length=50, label='Last name') email = forms.EmailField(label='Email') location = forms.ChoiceField(choices=TP_TM_Location, label='Location') designation = forms.ChoiceField(choices=TP_TM_Designation, label='Designation') date_of_joining = forms.DateField(label='Date of joining', widget=forms.TextInput(attrs={'type': 'date'}), initial=date.today()) current_status = forms.ChoiceField(choices=TP_Status, label='Current status') username = forms.CharField(label='Login username') #this field is referring to parent object def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['current_status'].initial = "Initial" views.py class TeamUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): template_name = 'project_tracker/teammember/teammember_form.html' form_class = TeammemberUpdateForm model = Teammember #fields = ['first_name','last_name','email','location','designation','date_of_joining','current_status', 'username'] def get(self, request, *args, **kwargs): #self.object = self.get_object() print("object id: " ,self.get_object().id) return super(TeamUpdateView, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) formclass = self.get_form_class() print(self.get_form_class()) #print(formclass.username) … -
What is the proper way to create a user creation view (signup view) in django (version 2.2.7)
I got to know about the django.contrib.auth.forms.UserCreationForm, but in the documentation I see this message: screenshot of message UserCreationForm was for version 1.8 What should I use in version 2.2.7? -
How to populate a database accessing values from a spreadsheet in Django in a proper manner
As my first website project, I am trying to build a 'Just Eat' alike app. I have called this first app homepage as that's were is going to be displayed first. The app is essentially a search box in which the user types a postcode and the output will be a list of restaurants in a given range. At the current stage, I have managed to access values from the table through a static method populate_addresses_db() which currently accesses only the postcode value. How do I actually populate the model Address (and therefore the database) so that when I access the admin view on the internet, and I select Addresses, the page will display all the addresses? here is my model.py: this is http://127.0.0.1:8000/admin/ and here is http://127.0.0.1:8000/admin/homepage/address/ which I would like to be automatically populated when I run the server Should I just create an instance of an object of the Address class and then call the function I have mentioned above? (everything inside model.py) Or is there another approach, a best practise? I am sorry if my question sounds a bit silly but I am still trying to grasp the way Django works. -
How to implement barcode scanner in reactjs application?
I am developing an Order Scan application, and the challenge I'm facing is that, if barcode matches, where I'm going to recieve data in my react application. I'll be using a barcode scanner device, so can I use this npm package https://www.npmjs.com/package/react-barcode-reader. If so, how to implement it in my react app? I have searched the web for answers. I couldn't find anything to my specific problem in react -
Django call custom manager method in CreateView and UpdateView
your expert knowledge of Django demanded :smile: So here is the problem. I created a custom create_number manager method. class NumberQueryset(models.QuerySet): def create_number(self, number, user): if number_validator(number): if self.filter(is_verified=True, user=user, number=number).exists(): raise ValidationError("Number already verified") else: verification_code = generate_random() self.create(user=user, number=number, verification_code=verification_code, operator=get_operator(number), valid_until = timezone.now()+timezone.timedelta(seconds=VALID_UNTIL_CONSTANT)) So in a views.py i created a view that get only number input from template. I have to redirect to verify page after submission of number from user. Also i have to call this method above. I tried using CreateView and created a form with following but it did not call my method unless i invoke my method manually. I tried calling it inside form_valid function scope, but since its using CreateView with ModelForm form_save method is invoking. How can i achieve this, or my approach is wrong from the first place? class NumberRegistrationForm(forms.ModelForm): class Meta: model = Number fields = ["number"] class NumberRegister(LoginRequiredMixin, CreateView): form_class = NumberRegistrationForm success_url = reverse_lazy("account:verify") def form_valid(self, form): if form.is_valid: Number.objects.create_number(number=form.cleaned_data['number', user=self.request.user .....) redirect(reverse('verify)) class Verify(LoginRequiredMixin, UpdateView): -
How to use a list in django query [duplicate]
This question already has an answer here: How can I filter a Django query with a list of values? 3 answers I have a list of owner_id and I want to use that list in a django query, but it gives me the following error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' Here's the code: d = DispatchPlan.objects.filter(Q(created_on__range=[date_to,date_from]) | Q(owner_id = [3,2,5])) How can I do that ? -
Ajax call from a dropdown to open a new page is not working
// I have a form where there are 3 fields and i want to insert them into databse. My table is kitty_member and fields are code, slot and customer. code belongs to primary key of kitty table which is having a field "totalmembers". As user selects "code". i want to show the list of intigers from 1 to "totalmembers" wrt to "code". For example when totalmembers = 100 for code = 'K00001' the in slots dropdown 1 to 100 should show and if code = 'k00002' which is having totalmembers = 50 then 1 to 50 should show on the dropdown. So i have written one ajax on the "code" field. I am trying to call an url by passing paramter "code". So that i can able to return the "totalmembers" to populate the dropdown "Slots". Ajax call is below which is in base.html. <script> function callsamepage() { var code1 = $('#code').val() console.log(code) $.ajax({ type:"POST", url: "kitty_member1" , data:{ code: code1 }, success: function(result){ console.log('correct',result) } }); } Views.py ----- def kitty_member1(request,code='None'): url_name = request.resolver_match.url_name print(url_name) print(code) customers = customer.objects.all().distinct('mobile') kittys = kitty.objects.all() if code != 'None' : kittys = kittys.filter(code=code) for i in kittys: totalmembers = i.totalmembers members = … -
QuerySets are lazy in template
I am working on one question and answer website.I think i have mess with code.I am sending querysets all objects when only one needed. Like sending all answer of one question when only one needed. I print only one. So at that time will it affect database's all record or only record which i will print in template? View.py questions = Question.objects.all() context = { 'questions':questions } return render(request,'index.html',context=context) template_tag.py @register.simple_tag def getmostvotedanswer(answers): answer = answers.order_by('-vote')[0] return answer.answer index.html <p>{% getmostvotedanswer question.answer_set.all %}</p> In this i am sending all answers but only needed so will it affect database's performance?