Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to keep checkbox checked during pagination in django
how to keep checkbox checked during pagination in django ??? I built an online store and had a problem when filtering products. When I select a brand, the products related to that brand are displayed to me, and if I go to the next page, it will still work without any problems. If I select two brands, the products related to these two brands will be displayed on the first page without any problems, but by going to the next page, only the products related to the second brand that I have selected will be displayed and the first brand check box will be checked Will be removed and only the second brand check box remains. How can I keep the status of the checkbox stable after going to the next page? (use djago-filter) my script : $(document).on('change','.filter-form',function(event){ event.preventDefault(); $.ajax({ type:'GET', url:'filter/', data : $(this).serialize(), dataType: 'json', success: function (data) { console.log("success"); $('#product-main').html(data['form']); }, error: function (data) { alert("error" + data); } }); }); my form : <form action="" class="filter-form"> <div class="d-flex justify-content-between mt-2"> <div class="form-check"> <label class="form-check-label"> {{filter.form.brand}} </label> </div> </div> </form> -
Django-celery task not firing after post-save signal for large image files (like > 10MB) but works for normal images
hey guys I am quite confused with what's happening with the code and doesn't seem to understand why large images are not getting processed with the celery task and the entire post object is not getting saved in the db while it works with normal images. This is the post-signal I have: @receiver(post_save, sender=PostImage) def save_image_after_processing(sender, instance, **kwargs): post_image = instance.image task_process_image_for_posts.delay(post_image.path) Sometimes it runs with large image files, most of the time it doesn't. Can anyone help with the issue? Thanks -
My models property filtering total sum and answer correct but gave me each row what i have db
Below def. given me correct answer, but when i added html total sum. written me in db how many rows i have, same as row result gave? def total_overtime(self): total = (Salary.objects .filter(currency='Tenge') .aggregate( total=Sum('overtime', field="overtime*overtime_hourly_rate") )['total']) return total -
I am not able to get a field in my Django ManyToMany Relation
I have a model called announcement in my Django Models, the way it works is that it has a message field which I can type the body of the message as well as the student_id which is the receiver of the message. I am using the many-to-many field on the student_id so that I am able to send the message to either some particular student and then filter the particular student message in on their frontend, but when I am trying the filter the particular student which I selected when sending the message, it doesn't display any information at all. models.py class Announcement_by_dean(models.Model): student_id = models.ManyToManyField(add_students_by_manager) message = models.TextField() sent_date = models.DateField(default=datetime.now(), blank=True) updated_date = models.DateField(auto_now=True, blank=True) def __str__(self): return "message sent on "+ str(self.sent_date) class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address = models.CharField(max_length=200) dob = models.CharField(max_length=200) major = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.student_name views.py def dean_page(request): annoucement_list = Announcement_by_dean.objects.all().order_by('-id') return render(request, 'dean_page.html', context) dean_page.html <div class="tab-pane fade show" id="nav-announcement-list" role="tabpanel" aria-labelledby="nav-announcement-list-tab"> {% if annoucement_list %} {% for k in annoucement_list %} <div class="card container mt-4 mb-5"> <div class="card-body"> Messsage: {{k.message}}<br> Sent to: {{k.student_id.student_ID}}<br> </div> </div> {% endfor … -
Django Querysets adding additional information inside View
I'm currently working on a small django application for my school. I got two models involved in this problem: "category" and "device", which are connected in a one-to-many relationship category---<device(s) I added one page/template/view for the category overview, containing a large table with all the relevant information on every category created. Querying the categories like this: categories = Category.objects.filter(is_activ=True) And displaying them inside the template like this: {% for category in categories %} {{ category.title }} {{ category.otherField }} {% endfor %} is no Problem. The Issue: Now I need to add an extra field to the table containing the amount of devices in the category. Since the amount of devices is no field in my category model, but can rather be determined like this: amount_devices_in_c1 = Device.objects.filter(category=c1).count() it's not possible for me to access the amount in the template by just doing: {{ category.amount }} Solution? Since adding a field to the category model is not an option and makes the code even less agile, I am loooking for a way to join/merge the information to the categories Queryset. I guess it's a pretty basic question, but I think I am missing some basic knowledge on Querysets/Mege/Join. Thank you … -
Django chunked file upload continue after offline
I'm aware of django-chunked-upload but I'd like to understand how to receive and write file chunks with Django. From my Frontend (Dropzone) I'm getting following post data: {'dzuuid': ['42938e49-57cc-4cee-bf1d-9dd7a35dae29'], 'dzchunkindex': ['0'], 'dztotalfilesize': ['242129'], 'dzchunksize': ['1000000'], 'dztotalchunkcount': ['1'], 'dzchunkbyteoffset': ['0']} <MultiValueDict: {'file': [<TemporaryUploadedFile: MY_FILE.png (application/octet-stream)>]}> With a simple django view (code only for testing!) I can receive and write my chunks: class UploadView(View): def post(self, request, *args, **kwargs): # variables and post data file = request.FILES['file'] chunk_byte_offset = int(request.POST.get("dzchunkbyteoffset")) current_chunk = int(request.POST.get("dzchunkindex")) total_chunks = int(request.POST.get('dztotalchunkcount')) save_path = os.path.join(./media/, str(file)) #write chunks destination = open(save_path, 'a+b') for chunk in file.chunks(): destination.write(chunk) destination.close() # response if current_chunk + 1 == total_chunks: return HttpResponse(('Upload complete')) else: return HttpResponse(('Uploaded Chunk')) While this is working I'd like to implement the resumption of a paused or interrupted file upload. The idea is instead of just appending the chunks to a file, to seek the last offset and append it after. with open(save_path, 'a+b') as f: f.seek(chunk_byte_offset) f.write(file.stream.read()) Questions: f.seekthrows an error AttributeError: 'TemporaryUploadedFile' object has no attribute 'stream' what do I overlook here? What is the suggested way of knowing where to continue even after hours of downtime. My idea is either to write the history of … -
I am getting "This field is required." error on load of webpage when using the Django ModelForm
I made a model called Annoucement in my models.py file as well as the form for it in my forms.py file. I then made the simple create view for it in my my views.py and made it show on the frontend using the django-crispy-forms package but anytime i load the website, the border of the field appears red showing that there is an error. I have tried checking what the error could be but I am not getting any luck around it. models.py class Announcement_by_dean(models.Model): student_id = models.ManyToManyField(add_students_by_manager) message = models.TextField() sent_date = models.DateField(default=datetime.now(), blank=True) updated_date = models.DateField(auto_now=True, blank=True) def __str__(self): return "message sent on "+ str(self.sent_date) forms.py class Annoucement_form(ModelForm): class Meta: model = Announcement_by_dean fields = ['student_id', 'message'] views.py def dean_page(request): annoucement_list = Announcement_by_dean.objects.all() if request.method == 'POST': form = Annoucement_form(request.POST) if form.is_valid(): form.save() messages.success(request, _("Message Sent Successfully!!!")) return redirect('dean_page') else: messages.error(request, _("Message Not Sent, Something is Wrong!!!")) else: form = Annoucement_form() messages.error(request, _("Invalid Method!!!")) context = {"form":form, "annoucement_list":annoucement_list} return render(request, "dean_page.html", context) dean_page.html <!-- Send Announcement --> <div class="tab-pane fade show" id="nav-announcement" role="tabpanel" aria-labelledby="nav-announcement-tab"> <div class="container mt-4 p-3"> <form action="{% url 'dean_page' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn btn-success btn-sm">Submit</button> </form> </div> </div> -
Django, datatables doesn't render table in html template
I'm sending the data from the views function to the template as a table and trying to use datatables to turn the table into a more functional table, so I can order elements based on the different columns... The table by itself appears... But it's only html structured table, not dynamic table, where it could be ordered by the columns. I was following: https://datatables.net/manual/ So far I found advises: -- Check the integrity of the table (so it has head and body tags)- I have it --all tags must be closed - they are closed -- use the java function, like so: $(document).ready( function () { $('#table_id').DataTable(); } ); I have no idea what else could be wrong... I have to mention... I would like to avoid saving data to the database, just would like to take data from view and post it to the table in the template... That's why I choose datatables over django_tables2... Because it seems datatables have a way just render the tables from the data... My code: views.py: ... for Loop: ... data_list.append({'ref':ref[k], 'ref_num':ref_num[k], 'ref_pr':ref_pr[k]}) k=k+1 context={ data_list, } return render(request, 'objects.html', context=context) The page renders, so no faults in urls... html page: {% extends … -
Django union queries throwing database error.( ORDER BY not allowed in subqueries of compound statements.)
MY search bar is not working when I try to make union queries. My function looks like this def search(request): query=request.GET['query'] allPostsTitle= Post.objects.filter(title__icontains=query) allPostsAuthor= Post.objects.filter(author__icontains=query) allPostsContent =Post.objects.filter(content__icontains=query) allPosts= allPostsTitle.union(allPostsContent, allPostsAuthor) if allPosts.count()==0: messages.warning(request, "No search results found. Please refine your query.") params={'allPosts': allPosts, 'query': query} return render(request, 'home/search.html', params) Please help me out of this I am getting this error DatabaseError at /search ORDER BY not allowed in subqueries of compound statements. Request Method: GET Request URL: http://127.0.0.1:8000/search?query=continue Django Version: 3.1.5 Exception Type: DatabaseError Exception Value: ORDER BY not allowed in subqueries of compound statements. Exception Location:virtualenvs/myvirtualenv/lib/python3.6/site- packages/django/db/models/sql/compiler.py, line 444, in get_combinator_sql Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.9 -
favicon icons not found , djabgo website with bootstrap at front , its a simple website
favicon icons not found , djabgo website with bootstrap at front , its a simple website . it was working a few minuts ago i tried chanding the whole boot strap code . the log i am getting when the django server is runing and i use the users profile: Not Found: /favicon.ico [06/Feb/2021 08:53:13] "GET /favicon.ico HTTP/1.1" 404 4502 Session data corrupted this is were the bootstrap static is coming though in the page: {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> -
"Database is Locked" error while deploying django webapp on azure
I am trying to deploy an django webapp on azure, it shows on web totally functional, except one thing, It doesnt let me create superuser on webssh, Every time I try to run python manage.py createsuperuser and after giving all credentials it throws an error django.db.utils.OperationalError: database is locked I don't understand what to do I am using default database of django. -
Django template language logical issue
In this code line no. 4 if "user.number" is greater than "i", (add:'4') this will done. but if "i" is greater than "user.number", (add:'-4) this will done ...but i do not understand why ..? because if (i < users.number) is False then (i > users.number) this should not run please explain {% for i in users.paginator.page_range %} {% if users.number == i %} <li class="page-item active"><a class="page-link">{{ i }}</a></li> {% elif i < users.number|add:'4' and i > users.number|add:'-4' %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} -
Django3 : how to add an attribute from a foreign key filed
I have to migrate some code from python2.7/django1.11 to python3.7/django3.x I get an error and could not find why. The error is that i can access the foreign key value nom_ingredient. "Instance of 'ForeignKey' has no 'nom_ingredient' member". The problem is the same with mode_operatoire field class Ingredient(models.Model): id_ingredient = models.AutoField(primary_key=True) nom_ingredient = models.CharField(max_length=100) def __str__(self): return self.nom_ingredient class Meta: managed = True db_table = 'ingredient' class Recette(models.Model): id_recette = models.AutoField(primary_key=True) nom_recette = models.CharField(max_length=100, blank=True) mode_operatoire = models.CharField(max_length=1000, blank=True) class ComposerRecette(models.Model): id = models.AutoField(primary_key=True) id_ingredient = models.ForeignKey('Ingredient', db_column='id_ingredient', on_delete=models.DO_NOTHING) quantite_ing = models.FloatField() def mode_operatoire(self): return self.id_recette.mode_operatoire def __str__(self): return self.id_ingredient.nom_ingredient -
How to download a database from the postgresql in the format of zip with Filestore by using python(Django)
I am trying to implement a django project, in that project there is a postgresql database with filestore. I need to download the database along with filestore in the ZIP format and it can be restore to database as well. Thanks in advance -
Remove from cart button not appearing - django template language
So it is supposed to show remove from cart when user has that item in their cart and add to cart when they don't, I am trying to use django template language for this but remove from cart button is not appearing, home function handles the page i am talking about, It passes all the variables to home.html. home.html <h1>Here are products</h1> <h1>{{ error }}</h1> <h1>Your cart currently costs ${{ price }}</h1> {% for book in books %} <h3>{{ book.name }}</h3> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% if book in cart %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} <button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button> </form> {% else %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% endif %} {% endfor %} views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist import random # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in … -
Exception in thread django-main-thread django
Whenever running the server the following exception is poping up. Exception in thread django-main-thread: Following are the respective Traceback. Traceback (most recent call last): File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\core\management\base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: web.Profile.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". System check identified 1 issue (0 silenced). I had already installed the pillow but its showing error in importing ImageField. Please let me know if you have any idea regarding this. Thanking you in advance. -
Hello.. I am making project on online exam system in django. I don't understand following code inside **
I am making project on online exam system in django. I recently download one template for same form GitHub.I don't understand following code inside ** ''' def student_signup_view(request): userForm=forms.StudentUserForm() studentForm=forms.StudentForm() mydict={'userForm':userForm,'studentForm':studentForm} if request.method=='POST': userForm=forms.StudentUserForm(request.POST) studentForm=forms.StudentForm(request.POST,request.FILES) if userForm.is_valid() and studentForm.is_valid(): **user=userForm.save() user.set_password(user.password) user.save() student=studentForm.save(commit=False) student.user=user student.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user)** return HttpResponseRedirect('studentlogin') return render(request,'student/studentsignup.html',context=mydict) ''' Thank you. -
Using a variable in xpath as "request.method.POST.get" in Python Selenium
I am trying to get data from HTML form, seems like Xpath is not able to fetch POST data. here is my HTML form <form action="pay/" onsubmit="string()" method="post"> <label for="amount">amount</label> <input type="text" formmethod="post" name="amount"><br> <input type="submit" value="Toggle" id="toggle1" /> </form> after submit it run the test. def string(request): if request.method == 'POST' ... goes well till here. then stops at: ... sleep(5) amount = request.method.POST.get("amount") j = pay.find_element_by_xpath("//strong[contains(text(),'" + amount + "']") action = ActionChains(pay) action.move_to_element(j).click().perform() Error returns with "'str' object has no attribute 'POST'". the 'amount' is in integer form which actually searches for text in xpath.`` -
I am looking to run a django server on my personal PC that can be available through WAN
I am currently working on a developmental website and I need to be able to move it to a public domain, so I went and made the purchase of a domain and now i want to make the django app i have written publically available without purchasing a web hosting service quite yet or I might plan on investing in an actually windows server, if anyone knows how to go about doing this purely for developmental use and proff of concept practice, it would be great to see a video or a step by step guide. -
Why does my clean_email and clean_username not work
Over here, I am trying to make it such that users cannot update their username and email to a username/email that is already existing. However, though no errors are shown, it does not work. Can someone advise why this is so? This worked for my register page. forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('username', 'email',) def clean_email(self): email = self.cleaned_data['email'].lower() try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_username(self): username = self.cleaned_data['username'] try: account = Account.objects.exclude(pk=self.instance.pk).get(username=username) except Account.DoesNotExist: return username raise forms.ValidationError('Username "%s" is already in use.' % username) def save(self, commit=True): account = super(AccountUpdateForm, self).save(commit=False) account.username = self.cleaned_data['username'] account.email = self.cleaned_data['email'].lower() if commit: account.save() return account views.py def edit_account_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) if account.pk != request.user.pk: return HttpResponse("You cannot edit someone elses profile.") context = {} if request.POST: form = AccountUpdateForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect("account:view", user_id=account.pk) else: form = AccountUpdateForm(request.POST, instance=request.user, initial={ "email": account.email, "username": account.username, } ) context['form'] = form -
Django model CharField choice clashes with itself
I was extending my Survey model with models.CharField(choices) but I cannot due to Error: surveys.Survey.status: (models.E006) The field 'status' clashes with the field 'status' from model 'surveys.survey'. My Model Code: class Survey(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) finish_date = models.DateTimeField(blank=True, null=True) uuid = models.UUIDField(unique=True, editable=False, db_index=True, default=uuid.uuid4) Finished = 'FI' OnProgress = 'OP' ReportGenerated = 'RG' STATUSES = [ (Finished, 'Finished'), (OnProgress, 'OnProgress'), (ReportGenerated, 'ReportGenerated') ] status = response = models.CharField( max_length=2, choices=STATUSES, default=OnProgress, ) Other models there I used Survey in case it may help: class SurveyCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) survey = models.ForeignKey(Survey, on_delete=models.CASCADE) class SurveyQuestion(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) response_explanation = models.TextField(blank=True, null=True) Not_Responded = 'NR' Fully_Implemented = 'FI' Partially_Implemented = 'PI' Not_Implemented = 'NI' SURVEY_RESPONSE_CHOICE = [ (Not_Responded, 'Not Responded'), (Fully_Implemented, 'Fully Implemented'), (Partially_Implemented, 'Partially Implemented'), (Not_Implemented, ' Not Implemented'), ] response = models.CharField( max_length=2, choices=SURVEY_RESPONSE_CHOICE, default=Not_Responded, ) -
How to serialize list of model objects in django model serailizer field?
Here I have a model and inside the model there is a property method and inside the method there will be a list of model objects. Now I am trying to get the products from the property method in my serializer like this but I am getting the error: TypeError: Object of type Product is not JSON serializable model class MyModel(models.Model): title = models.CharField(max_length=255) products = models.ManyToManyField(Product) categories = models.ManyToManyField(Category) @property def get_products(self): all_prods = [] products = list(self.products.all()) all_prods.extend(products) categories = self.categories.all() for category in categories: prods = [prod for prod in category.product_categories.all()] all_prods.extend(prods) return all_products serailizer class MySerializer(serializers.ModelSerializer): all_products = serializers.ReadOnlyField(source='get_products') class Meta: model = MyModel fields = ['title','all_products'] -
How to render Vue with Django
I'm working on a small application using Vue.js and Django on Digitalocean, so I have installed Django Webpack loader and the tracker also, now I have executed my Django server and my vue.js also using npm run serve and when I access to my webpage localhost:8000 I see only a blank page since everything is installed correctly, This is my HTML page ( when I inspect on chrome browser ) <html> <head> <title>Title of the document</title> </head> <body> <div id="app"></div> <script type="text/javascript" src="http://0.0.0.0:8080/js/app.js"></script> </body> </html> PS : i think the problem is in app.js ( because i follow the link and i get an error ) This site can’t be reachedThe webpage at http://0.0.0.0:8080/js/app.js might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID -
Django | changing pk view parameter breaks the view
I have a Django app I'm making where each user has a card, consisting of several text tiles. Here's my models: class Card(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") class Tile(models.Model): card = models.ForeignKey( Card, on_delete=models.CASCADE, related_name="card") content = models.TextField() I would like to populate the same HTML template with the card/tile data based on the URL, so I am passing the primary key of the card through the URL: urlpatterns = [ path('card<int:pk>/', views.card, name='card'), ] My question is about my views. I am trying to pass only the tiles in that have a card foreign key with the primary key id that was passed through the URL. So, this works: def card(request, pk): try: card = Card.objects.get(pk=pk) if card: context = { 'title': 'Card', 'tiles': Tile.objects.filter(card=pk) } return render(request, 'cards/card.html', context) except: return HttpResponseNotFound() However, this, does not work: def card(request, card_pk): try: card = Card.objects.get(pk=card_pk) if card: context = { 'title': 'Card', 'tiles': Tile.objects.filter(card=card_pk) } return render(request, 'cards/card.html', context) except: return HttpResponseNotFound() I get the following error: card() got an unexpected keyword argument 'pk' Why is that? I was under the impression I was just renaming the parameter for my view function... -
I cant run hello world
enter image description here urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include ('portfolio.urls')), ] views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return HttpResponse("Hello World"); please help I'm still a newbie in django