Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Related fields on model?
There is a model ElectoralTable class ElectoralTable(models.Model): name = models.CharField(max_length=250) country_owner = models.ForeignKey(Country, on_delete=models.CASCADE) city_owner = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=400) latitude = models.CharField(max_length=250, blank=True) longitude = models.CharField(max_length=250, blank=True) How can I to select a city related to a country. Rigth now I receive every city on Model City but I want only to receive the cities related wiht country owner -
Getting Jquery error while integrating ADMINLTE template in django
I am getting error while i was integrating ADMINLTE3 in django . i was developing webapp so for admin dashboard I was using it. But I did everything right still I am getting lots of error in the console about the jquery. can anyone help me on this error solving please. My console screen shot: browser consle screenshot -
Validating a choice field with ModelSerializer with Django
I have a model BaseUser which inherits from AbstractUser and has two additional fields: complex_list and active_complex. complex_list is a ManyToManyField connected to the BaseComplex model through an enrollment table. I want the default value for active_complex to be null which can be taken care of at the model initiation. I also need the user to be able to choose the active_complex only from the values within the complex_list. For that, I tried to use a customized ModelSerializer: from rest_framework import serializers from .models import BaseUser class ActiveComplexSerializer(serializers.ModelSerializer): this_user = serializers.SerializerMethodField('get_this_user') choice =[] qs = BaseUser.objects.get(username = this_user) for cmplx in qs.complex_list: choice.append((cmplx.id, cmplx.name)) active_complex = serializers.ChoiceField(choices = choice) class Meta: model = BaseUser fields = ('active_complex') def get_this_user(self, request): return request.user I know I'm doing something wrong because I get a query not found ERROR. I would appreciate it if you could correct this or suggest a better approach to achieving the same goal. -
Materialize autocomplete not updating v-model of Vue app
So I'm using Django, Vue, and Materialize. Just using Vue to have some smoother functionality. I have a text input that has a v-model on it. I'm also using Materialize's autocomplete component on it. When I select an option from the autocomplete, it does not update the data in vue that I have attached to the "v-model". The v-model just stays with the data I have typed in so far. How do I get around/fix that? How do I update the vue data on materialize's autocomplete? https://materializecss.com/autocomplete.html -
Django password reset/change view
I want to implement password reset/change feature in my app i just googled it & saw everyone using Django default Authentication Views. Is this the best way to do this? I'm new to django so i don't know much about this so suggest me the best way to do this. currently i implemented this path('password_change/done/', auth_view.PasswordChangeDoneView.as_view( template_name='registration/password_change_done.html'), name='password_change_done'), path('password_change/', auth_view.PasswordChangeView.as_view( template_name='registration/password_change.html'), name='password_change'), path('password_reset/done', auth_view.PasswordResetDoneView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view( template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset/', auth_view.PasswordResetView.as_view( template_name='registration/password_reset_form.html'), name='password_reset'), path('reset/done/', auth_view.PasswordResetCompleteView.as_view( template_name='registration/password_reset_complete.html'), name='password_reset_complete') -
Django auto repost data a week, month or a year depending on it's frequency of recurrence
In my django project I am trying to repost a record based on its frequency of recurrence which could be daily, weekly, monthly etc. Let's say a record is posted today and it's frequency of recurrence is weekly, I want the record to keep reappearing on a weekly basis on the 'day' and 'time' as the previous week when it was created and so on, that is, an old record will be new and top of other records which will now be older than it based on frequency of recurrence. models.py class Menu(models.Model): none = 0 Daily = 1 Weekly = 7 Monthly = 30 Quarterly = 90 SemiAnual = 180 Yearly = 365 Frequency_Of_Reocurrence = ( (none, "None"), (Daily, "Daily"), (Weekly, "Weekly"), (Monthly, "Monthly"), (Quarterly, "After 3 Months"), (SemiAnual, "After 6 Months"), (Yearly, "After 12 Months") ) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) name = models.CharField(verbose_name="food name", null=False, blank=False, max_length=100) description = models.TextField(verbose_name="Food Description", max_length=350, null=False, blank=False) image = models.ImageField(upload_to=user_directory_path, default='veggies.jpg') isrecurring = models.BooleanField(default=False) frequencyofreocurrence = models.IntegerField(choices=Frequency_Of_Recurrence) datetimecreated = models.DateTimeField(verbose_name='date-time-created', auto_now_add=True) How exactly can I achieve what I'm trying to do in my views. Thanks in advance. -
How to check if one field matches another in Django Form
I'm trying to have my form check if the email field matches the verify_email field in my Django form but it is not working. My forms.py file: class SignupForm(ModelForm): class Meta: model = FormSubmission fields ='__all__' widgets = {'botcatcher': forms.HiddenInput()} def clean(self): cleaned_data = super().clean() email = self.cleaned_data.get('email') vmail = self.cleaned_data.get('verify_email') if email != vmail: raise forms.ValidationError(_("Emails must match"), code="invalid") return cleaned_data My model.py file: class FormSubmission(models.Model): first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) email = models.EmailField(unique= False) verify_email = models.EmailField(unique = False) text = models.CharField(max_length=250) botcatcher = models.CharField(max_length= 1, blank=True, validators=[validators.MaxLengthValidator(0)]) def __str__(self): return "%s %s"% (self.first_name, self.last_name) -
ReportLab get_FOO_display() Not Working On A List
Ive created a form which users fill out, then it uses reportlab to create a pdf of their answers. It works well except for a charfield (preferred_topics) which contains a list. Data is saved like this: ['ANI', 'EDU', 'ENV'] I think that might be a problem as id exect it to save the data like this: [['ANI'], ['EDU'], ['ENV']] However it works fine on the website. So to print human readable data to the pdf im using get_FOO_display(), but this doesnt work for preferred_topics. If i call (user.personalinformation.get_preferred_topics_display() i get: AttributeError at /enrolment/final_question/ 'PersonalInformation' object has no attribute 'get_preferred_topics_display' Here is my other relevant code: utils.py # generate pdf def generate_pdf(request): # get user user = request.user # data that will be printed to the pdf page_contents = [ ['Personal Information'], ['Name:', '%s %s' %(user.personalinformation.first_name, user.personalinformation.surname)], ['E-mail:', '%s' %(user.email)], ['Gender:', '%s' %(user.personalinformation.get_gender_display())], # this field is causing grief ['Preferred Topics:', '%s' %(user.personalinformation.preferred_topics)] ] forms.py TOPICS = ( ('ANI', 'Animals'), ('ART', 'Art'), ('COM', 'Communication'), ('CRI', 'Crime'), ) preferred_topics = forms.MultipleChoiceField(choices=TOPICS, required=False, widget=forms.CheckboxSelectMultiple()) Im expecting to be told that the data is being saved wrongly in my db, but dont know how to change it, and wanted confirmation before i started changing … -
django template - how to show different html based on for loop
Hello I'm trying to display a list in an html template which will display the information in a different configuration depending on the index of the list element. however, I'm getting all the information displayed with the html defined between the first condition and I can't figure out why is it not working. Excuse me for my bad programming I'm new at this. Can anyone help??? THANKS! this is my code so far: {% for service in service_list %} <section class="section {{service.bg}}" id={{service.tag}}> <div class="container"> <div class="row align-items-center"> {% if loop.index is odd %} <div class="col-lg-8"> <h2 class="text-white mb-3">{{service}}</h2> <p class="text-white lead">{{service.abstract}}</p> </div> <div class="col-lg-4 text-lg-right"> <a href="{% url 'main:spec_service' %}" class="btn btn-outline-white px-4 py-3">{{service.btn_text}}</a> </div> {% else %} <div class="col-lg-4 text-lg-left"> <a href="{% url 'main:spec_service' %}" class="btn btn-outline-white px-4 py-3">{{service.btn_text}}</a> </div> <div class="col-lg-8"> <h2 class="text-white mb-3 text-lg-right">{{service}}</h2> <p class="text-white lead">{{service.abstract}}</p> </div> {% endif %} </div> </div> </section> {% endfor %} -
Changing in the Quantity of variants reflecting in the wrong item in Order Summary
I have a problem with the variations and the quantity related to it in the order summary page. It was working perfectly and all of a sudden (this is an example to simplify): when I add to the cart 2 items: Item X with a size small Item X with a size medium When I change the quantity of item X size medium, this change is reflecting in item X size small which was chosen first. In the order summary, there are a plus and minus in the template to change the quantity. I have identified the problem but I can't figure out why it is occurring Here is the template: <h2> Order Summary</h2> <tbody> {% for order_item in object.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ order_item.item.title }}</td> <td>{{ order_item.item.price }}</td> <td> <a href="{% url 'core:remove-single-item-from-cart' order_item.item.slug %}"><i class="fas fa-minus mr-2"></a></i> {{ order_item.quantity }} <a href="{% url 'core:add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></a></i> </td> <td> {% if order_item.variation.all %} {% for variation in order_item.variation.all %} {{ variation.title|capfirst }} {% endfor %} {% endif %} </td> Here is the views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, … -
In VS Code is there any shortcut to make {% %} for Django?
Is there any keyboard shortcut or extension that contains a shortcut where {% %} is automatically written out, and preferably the cursor is placed inside? Just starting with learning Django and it seems like you'll be using this enough that a shortcut would be useful. -
Django form is valid return that is NOT valid and error unknown
can anybody help me understand why the form is not validating? I have the following error: > I don't get any error message unless I print the form.is_valid The code is similar to what I normally use so it is strange that is not working this time.. I've looked the code over and over but can't find the issue. Let me know if there is more code I should show Thank you for any help you could provide. Views.py @login_required(login_url="sign-in") def restaurant_add_meal(request): form = MealForm() if request.method == "POST": form = MealForm(request.POST, request.FILES) if form.is_valid(): new_meal = form.save(commit=False) new_meal.restaurant = request.user.restaurant new_meal.save() messages.success(request, "It's saved!") return redirect(restaurant_add_meal) return render(request, "restaurant/dashboard/add_meal.html", {"form": form},)</code> And this is forms.py class MealForm(forms.ModelForm): meal_name = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), max_length=500, required=True, ) short_description = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), max_length=500, required=True, ) image = forms.ImageField( widget=forms.FileInput(attrs={"class": "form-control dropify"}), required=True, ) price = forms.IntegerField( widget=forms.TextInput( attrs={"class": "form-control price", "placeholder": "0.00"} ), required=True, ) category = forms.CharField( widget=forms.TextInput( attrs={"placeholder": "Ex. starters", "class": "form-control"} ), max_length=500, required=False, ) class Meta: model = Meal exclude = ("restaurant",) -
Linking Urls in django
I recently started learning as a way of setting foot in python programming. I've been facing problems with URLs since I'm a beginner. So I've been doing this signature verification web app. I'm not facing major problems except when it comes to URL patterns. When I enter the localhost address and the port and execute the program, it displays this error displayed here. I've gone to the URL files on Django and I see no errors on the code that I've written and also on the main folders URL. Can someone help me find the problem or what I'm doing wrong by checking the images and telling me? Thank you to all the people who checked this out. -
Django/Python: Raw SQL Query - Error binding parameter
I'm having a hard time figuring why I'm receiving the below error when the SQL I'm aiming for seems valid. Any ideas? Thank you! sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. Here's my raw SQL query in question: entries = Entry.objects.raw("SELECT * FROM learning_logs_entry LEFT JOIN learning_logs_document ON (learning_logs_entry.id = learning_logs_document.entry_id) WHERE learning_logs_entry.topic_id = %s AND learning_logs_entry.tag_id IN %s ORDER BY learning_logs_entry.date_added DESC", params=[topic_id, (1,2,3)]) Here's the SQL query produced: SELECT * FROM learning_logs_entry LEFT JOIN learning_logs_document ON (learning_logs_entry.id = learning_logs_document.entry_id) WHERE learning_logs_entry.topic_id = 1 AND learning_logs_entry.tag_id IN (1, 2, 3) ORDER BY learning_logs_entry.date_added DESC Here's my model for both Entry & Tag: class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete=models.CASCADE, related_name='entries') text = models.TextField(validators=[validate_text]) date_added = models.DateTimeField(auto_now_add=True) tag = models.ForeignKey(Tag, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: #metadata verbose_name_plural = 'entries' class Tag(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) -
Pass Seralizer URL params
some context: I am trying to determine which DB to use (every user has its own db) by a given url param. When url is "domain/<identifier>/Guest/" identifier is the url_param i need to pass to the serializer to use that DB I understand i need to override the create(self,validated_data) from the serializer serializer.py class GuestSerializer(serializers.ModelSerializer): def create(self, validated_data): db="???" return models.Guest.objects.using(db).create(**validated_data) class Meta: model = models.Guest fields = "__all__" So i need to pass the url param information to the serializer I'd like to know if there is a better approach -
Slow speeds on AWS S3 bucket upload
I'm using an S3 bucket for my media files on my django project. I've enabled Transfer Acceleration on my s3 bucket and I've also changed these settings from this S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME to S3_URL = '//%s.s3-accelerate.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3-accelerate.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME Unfortunately, these changes have made 0 difference when it comes to my upload speed. From where I am, my upload seems to hit 200kb/s, which is fairly slow. I'm on a 330mbit download / 15mbit upload connection. Questions: Is 200kb/s a good speed for upload to s3? Are there any other obvious or not so obvious things I can check for or change so that my speeds improve? Thanks for your help! -
How to display A only a users entered data related in a foreignkey on detailview in django
I am building this simple quiz app. This app allows all users to submit an answer to an assignment in Docx format. I what that any time a user views the question on the DetailView page, if the user has already submitted a solution for that assignment, that solution should be shown on the DetailView page as well. Current I get is all that answers submitted by all users. I only want a user's answer to that assignment on the detailpage this is my model. class Assignment(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=500) course = models.ForeignKey(Course, on_delete=models.CASCADE) class_or_level = models.ForeignKey(StudentClass, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) Text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) date_expire = models.DateTimeField() def __str__(self): return self.title class Answer(models.Model): slug = models.SlugField(max_length=500) assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='assignment') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} - {} '.format(self.assignment, self.student) Below is my view class AssignmentSubmitView(DetailView): model = Assignment template_name = 'assignment_submit.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['student_answer'] = self.object.answer_set.all() return context Below is my filter on detailview template. {% for answer in student_answer %} {{ answer.file }} {% endfor %} -
How to override the Django generic base View's dispatch method?
If I write a class that inherits from Django's generic base View, what is the correct way to override its dispatch method? The documentation seems to indicate it can be overridden but the example doesn't show exactly how to do it. If I do this, class MyView(View): def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): response = dispatch(request, *args, **kwargs) return HttpResponse('Hello, world!') Django says, NameError: name 'dispatch' is not defined. If I then change the dispatch statement to this, response = self.dispatch(request, *args, **kwargs) Django says, RecursionError: maximum recursion depth exceeded -
Report Lab Printing Values From Forms Rather Than Database
I have a website where users must complete a large questionnaire spread over four webpages (and four forms) and after completing the questionnaire reportlab generates a pdf of their answers. Here is my working code utils.py def generate_pdf(request): # get user user = request.user # get users age born = request.user.personalinformation.dob age = user_utils.get_age(born) doc = SimpleDocTemplate(settings.MEDIA_ROOT+'\pdf_templates\\enrolment_form_%s.pdf' %user.id) styles = getSampleStyleSheet() enrolment_form = [Spacer(1,2*inch)] style = styles["Normal"] page_contents = [ ("Name: %s %s" % (user.personalinformation.first_name, user.personalinformation.surname)), ("Gender: %s" % (user.personalinformation.gender)), ("Age: %s" % (age)) ] for sections in page_contents: p = Paragraph(sections, style) enrolment_form.append(p) enrolment_form.append(Spacer(1,0.2*inch)) doc.build(enrolment_form) models.py class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') gender = models.CharField(max_length=1, choices=GENDERS) dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now) def __str__(self): return f'{self.user.username}' (I also have a form.py but dont think its worth including) This works fine, except for fields like 'gender'. Because its getting the values its printing on the pdf from user.personalinformation from the database, instead of printing 'Gender: Male', its printing 'Gender: M'. While this example seems trivial, there are many more fields with key/value pairs and booleans which make no sense printed this way. … -
send_mail() fails with privateemail.com
When I test this code it returns HttpResponse('Invalid header found.'). I'm not sure if this is the best approach for a client. Can't I have it so the client receives the email from the senders email? Rather than using a proxy email to send to their email? That way I don't have to ask them for one of their passwords? forms.py class ContactForm(forms.Form): name = forms.CharField(required=True) from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) views.py def contact_page(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_mail, ['mygmail@gmail.com']) except: return HttpResponse('Invalid header found.') return redirect('main:homepage_view') context = { 'form': form, } return render(request, 'main/contact.html', context) main.contact.html <form method='post' action=''> {% csrf_token %} {{form|crispy}} {{form.errors}} <button type='submit'>Submit</button> </form> settings.py EMAIL_HOST = 'mail.privateemail.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'me@mydomain.com' EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_USE_TLS = True -
How to filter greater than or is null?
If I want to filter "greater than or equal to", I can use gte: MyModel.objects.filter(mydatetimefield__gte=mydate) Likewise, if I want to filter "is none/null", I can use isnull: MyModel.objects.filter(mydatetimefield__isnull=mydate) How can I combine these to filter for "greater than or equal to or is null", so the above filter would return both objects if i) mydatetimefield >= mydate, and ii) mydatetimefield == null? -
Nested relationship returns empty dictonary DRF
I wrote the following code: class PredictionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Prediction fields = ["id", "market"] depth = 1 class FixtureSerializer(serializers.HyperlinkedModelSerializer): predictions = PredictionSerializer() class Meta: model = Fixture fields = ["sofascore_id", "home", "away", "league", "round", "date", "predictions"] depth = 1 Corresponding with the following models: class Market(models.Model): name = models.CharField(max_length=200) class Fixture(models.Model): sofascore_id = models.CharField(max_length=200) home = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home") away = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away") league = models.ForeignKey(League, on_delete=models.CASCADE, blank=True) round = models.CharField(max_length=200, default=None, blank=True, null=True) date = models.DateTimeField() statistics = models.ForeignKey(Statistics, on_delete=models.CASCADE, default=None, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return u'{0} - {1}'.format(self.home.name, self.away.name) class Prediction(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, blank=True) fixture = models.ForeignKey(to=Fixture, on_delete=models.CASCADE, related_name="predictions", null=True, blank=True) When I make an request to /fixtures, the 'predictions' dictionary is always empty, but when I run some test code with the following statement: f = Fixture.objects.get(sofascore_id=match).predictions.all() I get the the following as return value: <QuerySet [<Prediction: Prediction object (23)>, <Prediction: Prediction object (24)>, <Prediction: Prediction object (25)>, <Prediction: Prediction object (26)>, <Prediction: Prediction object (27)>, <Prediction: Prediction object (28)>]> What is the issue here and why am I unable to retrieve my predictions using the written code? -
Django project sort by votes
so I found this youtube video about a cool django project.! Video ! I was wondering how it would be possible to sort the votes (In the admin) by vote count and not "last voted".I think it would be possible using a filter but im fairly new in the programming game so i dont know where/how to add it but i want to learn! Or even another question. Is there a way to place the top 10 votes in a special list (or show them via html?) Thank you for reading. -
Django and javascript and using URL template to pass variables for jvectormap
I've been teaching myself python and Django and wanted to show a clickable map on a webpage. I don't know javascript but I found jvectormap and it seems to be easy and works well. However I am confused about template tags. With the code below I can show a world map, and using the onregion function can get the country code and send it to an alert, if I comment out the alert, I can send using the Django URL tag to another web page. {% load static %} {% load static %} {{params}} <!DOCTYPE html> <html> <head> <title>jVectorMap demo</title> <link href="{% static 'css/jquery-jvectormap-2.0.5.css' %}" rel="stylesheet" type="text/css" media="screen"/> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="{% static 'js/jquery-jvectormap-2.0.5.min.js' %}"></script> <script src="{% static 'js/jquery-jvectormap-world-mill-en.js' %}"></script> </head> <body> <div id="world-map" style="width: 600px; height: 400px"></div> <script> $(function(){ $('#world-map').vectorMap({ map: 'world_mill_en', onRegionClick:function(event, code){ var message = (code); alert( code ); window.location.assign ("{% url 'mainapp:home2' %}") } }); }); </script> </body> </html> So a couple of questions: I thought I should be able to use the template tag in the alert like alert( {{params}} ) but that doesn't seem to work. I thought you might be able to pass the string in params that way. I saw … -
Search Sql server use django
[I want search data form sql sever use by Django but error ,error show 'The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000'].I use request nethod:GET1