Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show a django form for many to many with through field?
I have created 3 model: class PropertyExtra(models.Model): type = models.CharField(choices=ExtrasType.choices, max_length=7) property_type = models.IntegerField(choices=PropertyType.choices) title = models.CharField(max_length=100) identifier = models.CharField(max_length=20, unique=True) class Property(models.Model): extras = models.ManyToManyField(PropertyExtra, through="PropertyExtraData") class PropertyExtraData(models.Model): value = models.CharField(blank=True, null=False, max_length=300) property_extra = models.ForeignKey(PropertyExtra, on_delete=models.CASCADE) property = models.ForeignKey(Property, on_delete=models.CASCADE) In PropertyExtra an admin user can add items like Electricity, Gas, Central Heating, etc. Some values will be boolean and some int which depends on the ExtrasType enum in the PropertyExtra. The specific value per property will be saved within the PropertyExtraData.value. Currently I'm have a form wizard to create a new Property using django-formtools and I'd like one of the steps to include a form that shows all the available PropertyExtras for a specific property_type. Basically if I have the above mentioned Electricity, Gas, Central Heating records in PropertyExtra - for a specific property_type I want to render 3 checkboxes where the user can mark them. Preferably would like to use ModelForm or ModelFormSet in order to simplify editing and saving but it's not possible - I'm looking for suggestions or 3rd party packages. -
Django template to Vue component
So I need to turn some of my templates to Vue components but I am currently using server-side rendering with Jinja how can I turn Jinja render into Vue? I am new to Vue.js so I apologies if that is a terrible question. -
Django Rest Framework - Doesn't appear to be paginating queryset correctly causing a long wait time before displaying on front end
I am experiencing an issue where it is taking upwards of 30 seconds to receive 25 items in a paginated response. This happens on original load of the page as well as any subsequent page requests via the datatables previous and next buttons. The model in question has roughly 600k records in it with the request to the api providing a query parameter to filter this by listing type (Letting or Sale). There are other filters applied to the queryset to ignore items that don't fall into the queue leaving 37k records on the Sales side and 90k on lettings that are returned. My model structue is as follows: class Listing(models.Model): date_added = models.DateField(verbose_name='Date Added', auto_now_add=True, auto_now=False) listing_id = models.CharField(max_length=15, blank=False, primary_key=True) portal = models.CharField(max_length=30, blank=False) url = models.URLField(max_length=200, blank=False) date = models.DateField(verbose_name='Listing Date', auto_now_add=False, auto_now=False, null=True, blank=True) listing_status = models.CharField(max_length=30, blank=False) outcode = models.ForeignKey( 'postcode_data.Outcode', blank=True, null=True, default=None, on_delete=models.CASCADE, related_name='+') sector = models.ForeignKey( 'postcode_data.Sector', blank=True, null=True, default=None, on_delete=models.CASCADE, related_name='+') address = models.CharField(max_length=200, blank=False) postcode = models.CharField(max_length=15, blank=False) description = models.TextField(blank=True) price = models.DecimalField(max_digits=9, decimal_places=1, default=Decimal(0.0)) property_type = models.CharField(max_length=30, blank=False) beds = models.PositiveIntegerField(default=0) baths = models.PositiveIntegerField(default=0) agent = models.CharField(max_length=150, blank=False) agent_company = models.CharField(max_length=100, blank=False) agent_branch = models.CharField(max_length=50, blank=False) available = … -
Django DeleteView Not Saving Changes
I'm using django DeleteView to delete user account. when i set the user's is_active property to False, it doesn't get saved in the database. it's still set to True here's my views.py from django.shortcuts import get_object_or_404 from django.urls import reverse_lazy from django.http import HttpResponseRedirect from django.views.generic.edit import DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.messages.views import SuccessMessageMixin class DeleteAccount(LoginRequiredMixin, SuccessMessageMixin, DeleteView): """ DeleteAccount: view to delete user account """ model = User template_name = 'registration/delete_account.html' success_url = reverse_lazy('core:index') success_message = 'Account Successfully Deleted!' def form_valid(self, form): """ Delete account and logout current user """ account = self.get_object() # verify if user is the rightful owner of this account if not account.id == self.request.user.id: return HttpResponseRedirect(reverse_lazy('accounts:index')) account.is_active = False # DOESN'T GET SAVED account.save() # EVEN AFTER CALLING MODEL.SAVE() METHOD logout(self.request) return super().form_valid(form) def get_object(self): return get_object_or_404(User, pk = self.request.user.id) -
Manytomany relationship with through field doesn't show up in admin edit panel
I am trying to add new functionality to an existing project, where users can add multiple country locations with cities. Here are the models: class OfferCountries(models.Model): country = models.ForeignKey("Country", on_delete=models.CASCADE) cities = models.ManyToManyField("City", related_name="offer_cities", blank=True) offer = models.ForeignKey("Offer", related_name="offer_id",on_delete=models.CASCADE) class Offer(BaseModel): ... offer_country = models.ManyToManyField('Country', through='OfferCountries', related_name='offer_countries',blank=True) Now when I try to add a new Offer instance in admin there is no field of offer_country. Any ideas on how can I fix it? -
python: How can I import my own module? ModuleNotFoundError in python
I'm going to import my own module to my main.py. I made some python files in my scripts directory.(DataExtractor~KorTextPreProcessor) enter image description here I wrote my code like this... import DataExtractor import KoreTextPreprocessor and so on... Pycharm doesn't show me any errors, but my ec2 command errors... which says :: "No module named 'DataExtractor" << I want to import them all in main.py. Someone recommends to write this way from FileTransformer import method but it still shows error... how can I fix it? Maybe shoud I wrote somethin in my init.py? -
Invalid command 'PassengerPython', perhaps misspelled or defined by a module not included in the server configuration IN Django godaddy
Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request. -
Using Django template tags and filters in javascript
I am building a search engine using Algolia in a client's Django project. In the html section of the template the client uses this line to format the date correctly. <span><em>posted</em> <strong>{{ dealer_announcement.publish_date|date:"F jS, Y" }}</strong></span> In the script on the template I define what each hit on the search engine should look like in a template like so. {% verbatim %} const hitTemplate = '' + '<span><em>posted</em> <strong>{{ publish_date }}</strong></span>' + '</div>' + ''; {% endverbatim %} This works fine, however the date is not formatted correctly so I tried to match the same format like so. {% verbatim %} const hitTemplate = '' + '<span><em>posted</em> <strong>{{ publish_date|date:"F jS, Y" }}</strong></span>' + '</div>' + ''; {% endverbatim %} but then nothing shows up. How can I use the same filters and tags within the script to have it match the original output. -
How to cleanly and efficiently delete an app from django
I have rewritten and renamed an entire app. It has now passed my tests, so it is time to delete the old version. To my surprise, this is either much harder than it should be, or I just haven't found the right answer. Where is 'python manage.py delete app 'appname'? I looked at this How to delete a record in Django models? and at the docs https://docs.djangoproject.com/en/4.0/topics/migrations/#workflow. First I tried just removing the entire app from the filesystem, but migrations complained: File "/home/malikarumi/.virtualenvs/LogBook/lib/python3.9/site-packages/django/db/models/base.py", line 113, in new raise RuntimeError( RuntimeError: Model class uppergi.models.Food doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ python manage.py delete uppergi Unknown command: 'delete' Type 'manage.py help' for usage. (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ manage.py help manage.py: command not found (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ git revert 8bb60951 So I put it back and tried deleting one model at a time. Migrations complained about that, too. (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ python manage.py makemigrations Traceback (most recent call last): ... File "/home/malikarumi/Projects/LogBook/uppergi/admin.py", line 6, in from . models import Grocer, Food, ShoppingTrip, Cook, Eaten ImportError: cannot import name 'Eaten' from 'uppergi.models' (/home/malikarumi/Projects/LogBook/uppergi/models.py) and specifying the app: (LogBook) malikarumi@Tetuoan2:~/Projects/LogBook$ python manage.py makemigrations uppergi Traceback (most recent call last): File "/home/malikarumi/Projects/LogBook/manage.py", … -
AttributeError: 'list' object has no attribute 'lower' django/utils/http.py
I've been getting an exception from the site-packages/django/utils/http.py module when ALLOWED_HOSTS in my settings is a list. File "/home/xxxx/.local/lib/python3.8/site-packages/django/utils/http.py", line 292, in is_same_domain pattern = pattern.lower() AttributeError: 'list' object has no attribute 'lower' Usually fires from module from django.test.Client To solve, I left only one item in ALLOWED_HOSTS. Does anyone know why? Thanks! -
How to make a field the same as int:pk in django rest framework?
I have a serializer class AnswerQuestionsSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Answer fields = ('answer', 'user', 'question', 'number_of_points', 'moderate_status',) And the view class AnswerQuestions(generics.CreateAPIView, generics.GenericAPIView): queryset = Answer.objects.all() serializer_class = AnswerQuestionsSerializer def perform_create(self, serializer): return serializer.save(user=self.request.user) def get_queryset(self): return super().get_queryset().filter( question_id=self.kwargs['pk'] ) The model looks like this answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) And i set the url to answerQuestions/int:pk, so when i use post request lets say answerQuestions/3 i still need to put "question": "3" in body because it won't read it automatically. Do you have any idea how to make it automatically hit the question of the id provided in the url? Which in this case would be 3. -
React VS NextJS for Django
I am still quite new to React, and I am currently working on a Django-React app. I read a bit about Next JS and it seems quite useful and interesting (especially for SEO), but I've heard various opinons about it. I am considering using it for the front end and rendering only. Therefore I was wondering, would it be worth it to learn and implement NextJS (and re do some of the work I did with react), or is the effort to great for a minimal result? Will NextJS allow me to do more than react (in terms of SEO and rendering)? Does the complexity of a project really increases when implementing Nextjs + React-Django? Lots of people are talking about NextJs and I was wondering if it was just "another framework" or really something more. Have a good day -
get none object in upload file in Apollo graphql
After uploading a file to the server returning an none object. client setup apollo.use apollo-upload-client module and set graphql uri const apolloLink = createUploadLink({ uri: API_URL, credentials: "same-origin", }); export const apolloFetch = createApolloFetch({ uri: API_URL }); const apolloCache = new InMemoryCache(); const authLink = setContext((_, { headers }) => getAuth().then(jwt => ({ headers: { ...headers, Authorization: jwt?.token ? `JWT ${jwt.token}` : "", }, })) ); const refreshTokenLink = new ApolloLink((operation, forward) => { operation.setContext((_: any) => isAuthenticated().then(is => { !is && getAuth().then(rt => { rt != null && apolloFetch({ query: gqlPrint(mutations.REFRESH_TOKEN), variables: { token: rt?.token }, }).then( ({ data: { user: { refreshToken }, }, }: any) => { if (refreshToken.success) setAuth(refreshToken.token); else clearAuth(); } ); }); }) ); return forward(operation); }); export const gplClient = new ApolloClient({ link: from([refreshTokenLink, authLink, apolloLink]), cache: apolloCache, }); and setup mutation upload file .I sure this part is right and think set apollo link is wrong import React, { useCallback } from "react"; import { useDropzone } from "react-dropzone"; import gql from "graphql-tag"; import { useMutation } from "@apollo/react-hooks"; import { filesQuery } from "./Files"; const uploadFileMutation = gql` mutation UploadFile($file: Upload!) { uploadFile(file: $file) } `; export const Upload = () … -
Django {% include %} TemplateDoesNotExist at / blog/includes/post.html
Hello,good day to you, I'm currenttly taking a Django course where im building a blog . i keep getting a: TemplateDoesNotExist at / blog/includes/post.html which i can not seem to solve. but i think it has something to do with the {%include%} template tag i have two files: 1)post.html and 2)index.html i am trying to {%include%} the post.html in the index.html but when i do i get this: TemplateDoesNotExist at / blog/includes/post.html template does not exist error but i have tested the path several times i have checked settings.py and my path is correct {% include "blog/includes/post.html" %} ### HERE IS THE PROBLEM in index.html {% include "blog/post.html" %} {% include "blog/templates/blog/includes/post.html" %} i have tried all paths none work. the only way i can make it work is by not using the the {% include%} and instead copying and pasting the post.html directly but this is impractical and does not let me move on with my project ##### index.html ###### {% extends "templates/base.html" %} {% load static %} {% block title %} My Blog {% endblock %} {% block css_files %} <link rel="stylesheet" href="{% static "blog/post.css" %}" /> <link rel="stylesheet" href="{% static "blog/index.css" %}" /> {% endblock %} {% … -
django missing csrf token in javascript .submit() function (non ajax)
I am using a javascript to send an html form to django. js looks like this: document.getElementById("fooform").submit(); and the html form looks like this: <form class="form-inline" id="fooform" action ="{% url 'foo:doo' %}" method="post"> {% csrf_token %} <input type="hidden" id="fooinput" value="" /> </form> the js can write the data into the input field without any problems and also carry out the submit. my problem is using the crsf token. I have already put the token {% csrf_token %} in every conceivable place. (Before the form, before the js...). in the html code is the token also correct. django gives me the error: Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as … -
Invalid address when sending mail via Django
I am trying to send mail via Django, but have an error: (501, b'5.1.7 Invalid address', '"emea\\\\sss1ss1"') My EMAIL_HOST_USER = r'emea\xss1ss1'. As you can see my user consist \x so I am using r''. How to fix it, the real EMAIL_settings are correct. my view.py def home(request): subject = 'Test mailing' message = 'Hello world!!!' email_from = settings.EMAIL_HOST_USER recipient_list = ['smth@smth.com'] send_mail(subject,message,email_from,recipient_list) return HttpResponse('Test mailing') -
Django: how to update a ManyToManyField in a custom Django management task?
In Django I have a model where one of the fields (tags) is a ManyToManyField: class MyModel(models.Model): id = models.CharField(max_length=30, primary_key=True) title = models.CharField(max_length=300, default='') author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') tags = models.ManyToManyField(Tag) I have a custom management task below where I'm getting all of the instances of the MyModel table on a server and using that to replace the instances of the MyModel table on my local server. (I'm running this custom management task from my local) Here's what I'm trying so far. However I'm getting this error: CommandError: Direct assignment to the forward side of a many-to-many set is prohibited. Use tags.set() instead. How can I update the tags field that's a ManyToMany field? from bytes.models import MyModel class Command(BaseCommand): def handle(self, *args, **options): try: // get queryset of MyModel instances from server queryset = MyModel.objects.using('theserver').all() // loop through that queryset and create a list of dictionaries mymodel_list = [ { 'id': mymodel['id'], 'title': mymodel['title'], 'author': mymodel['author'], 'copy': mymodel['copy'], 'tags': mymodel['tags'] } for mymodel in queryset ] //delete all objects in the local MyModel table MyModel.objects.all().delete() //replace with MyModel instances from server new_mymodel = [ MyModel( id=mymodel['id'], title=mymodel['title'], author=mymodel['author'], copy=mymodel['copy'], tags=mymodel['tags'] <--- causing error ) for … -
How to go to a form section which is in a bootstrap modal by using another button which is located in the navbar section of my website?
So I'm building a Ecommerce website, I've made different categories for different product so here an admin can add new products in the category section by clicking this + icon. Now I've added a new button in the navbar section which is Add Items (navbar section is in base.html), I also want that an admin can add products by clicking that button and I want that the same modal will pop up after clicking that button but I'm getting 404-Not Found which is obvious because in the views.py I've written only if the method is post I will allow this request and now I'm trapped how do I handle this navbar button? What condition's should I use here? views.py def add_product(request): if request.method=='POST': product_name = request.POST['product_name'] product_category = request.POST['product_category'] product_price = request.POST['product_price'] product_photo = request.FILES['product_photo'] product_description = request.POST['product_description'] add_product = Product(product_name=product_name,category=product_category,price=product_price,description=product_description, pub_date=datetime.today(),image=product_photo) add_product.save() messages.success(request, 'Product has been added successfully!!!') return render(request,'index.html') else: return HttpResponse("404-Not Found") Here is the photo of my Add product modal which will pop up after clicking + button This is the code for Add Item inside modal which is located in vegetable.html <div class="modal-body"> <form action="/add_product" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Product … -
how to access to property in view(django)
I'm beginner and I need some solution First, I have Racket and Detail class. class Racket(models.Model): name = models.CharField(max_length=20) class RacketDetail(models.Model): racket = models.OneToOneField(Racket, related_name='detail', on_delete=models.CASCADE) adminReview = models.TextField() adminPower = models.FloatField(default=0) adminSpin = models.FloatField(default=0) adminManeuverability = models.FloatField(default=0) adminStability = models.FloatField(default=0) adminComfort = models.FloatField(default=0) @property def adminAvgScore(self): scoreAvg = ( self.adminPower + self.adminSpin + self.adminManeuverability + self.adminStability + self.adminComfort ) / 5 return round(scoreAvg, 2) Second, I want to rander list using the @property(adminAvgScore), so I made view like this. def racketMain(request: HttpRequest): getRacket = Racket.objects.all().order_by('detail__adminAvgScore') return render(request, "racket/racketMain.html", {'racketItems': getRacket, }) Unfortunally when I use 'RacketDetail' class's column I can access all column except 'adminAvgScore' using by "order_by('detail__". If I use like "order_by('detail__adminAvgScore')" then Django show to me error "Unsupported lookup 'adminAvgScore' for BigAutoField or join on the field not permitted." How can I solve it? Or should I think in a different way? -
Django python + javascript countdown – time is off by 3 hours
I am relatively new and just a hobbyist programmer. At the moment I try to work on a small Django project where I want to set a date and time in the future via a form and after the user clicks "Submit", the page shows a countdown from now until the set date and time. After experimenting a bit with the datetime module, I find myself with an awkward problem. I have two fields in the forms: 1. date, and 2. time With timestamp = datetime.datetime.combine(date, time).strftime('%s') I combine those two information and get a seconds output. I then, pass timestamp to my .js file with {{ timestamp|json_script:'timestamp'}}. In javascript, I do the following: const setTime = JSON.parse(document.getElementById('timestamp').textContent); var difference = setTime * 1000 - now.getTime(); //Python gives me seconds not milliseconds date = new Date(difference); datevalues = [ date.getYear() - 70, date.getMonth(), date.getDate() - 1, date.getHours(), date.getMinutes(), date.getSeconds(), ]; document.getElementById("countdown").innerText = datevalues[0] + "years" + datevalues[1] + "months" + datevalues[2] + "days" + datevalues[3] + "hours" + datevalues[4] + "minutes" + datevalues[5] + "seconds" + setTime * 1000 + " ... " + now.getTime() + " ... " + difference let t = setTimeout(function () { timer() }, 1000); … -
local variable 'product' referenced before assignment ? in Django
I am facing the issue I can't find the solution yet. It's working so far. but now showing an error. don't know how to fix this. please need help. views.py def add_product(request): product_form = ProductForm() product_variant_images_form = ProductVariantsImagesForm() if request.method == 'POST': product_form = ProductForm(request.POST) product_variant_images_form = ProductVariantsImagesForm(request.POST,request.FILES) if product_form.is_valid(): print(request.POST) product = product_form.save(commit=False) vendor = CustomUser.objects.filter(id=request.user.id) product.vendoruser = vendor[0] product.save() vendor = CustomUser.objects.get(id=request.user.id) product_variant = ProductVariants() product_variant.product_id = product ###ERROR SHOWING IN THIS LINE product_variant.vendoruser = vendor product_variant.price = request.POST.get('price') product_variant.initial_stock = request.POST.get('initial_stock') product_variant.weight_of_product = request.POST.get('weight_of_product') product_variant.save() return redirect('vendor:inventory_display') else: productform = ProductForm() productvariantsform = ProductVariantsForm() product_variant_images_form = ProductVariantsImagesForm() return render(request, 'vendor/add_product.html', {'productform': productform,'product_variant_images_form':product_variant_images_form, 'productvariantsform': productvariantsform}) It's working fine.After product added multiple time the error occurred. how can I get rid of this error.please some help much appreciated. -
How to access a specific element from a CHOICES list in Django?
In my models, I have a choices list, such as: class Graduation(models.Model): YEAR_IN_SCHOOL_CHOICES = [ ('FR', 'Freshman'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Senior'), ('GR', 'Graduate'), ] student_level = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES) In my views, I want to get the value for a specific element. I have this: search = 'JR' all_choices = Graduation.YEAR_IN_SCHOOL_CHOICES My goal is to get Junior returned by the system. How can I do that? I tried: all_choices[search] but that doesn't work. I know I can change the format of my choices list in the models, but in this case my models can not be changed. What is the right way to obtain the label from this list? Do I have to loop through the list and use an if statement? That doesn't seem efficient but I am not sure if I have another choice. -
How can I login to two django applications with a single access credential?
I currently have several applications developed in django, and they ask me that with a single credential and depending on the permissions assigned to each user, they can access the different applications, how could I do that taking into account the session management middleware what does django have? -
Why My video is not playing from my code...?
I am working on a project and my video element is not working. here is my code below for html file <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Jangeer</title> </head> <body> {% load static %} <video src="{% static 'video.webmhd.webm' %}" muted autoplay loop></video> </body> </html> I am working in django framework. -
Django Shell Plus Clear History
Is there a command to clear the history of Django's Shell Plus? I did not find any hints in the documentation or by typing ?.