Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django views force download not open in browser
views.py: I make excel file on demand and its always different with user by user def down_excel(request): response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}-Orders.xlsx'.format( date=timezone.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title = request.user.username workbook.save(response) return response urls.py re_path(r'^test/down_excel/$', views.down_excel, name='down_excel'), template.html <a href="{% url "base:down_excel" %}">get_down</a> When I click get_down in template, It opens file on browser(I use chrome) I want to force download file with file name: {date}-Orders.xlsx'.format(date=timezone.now().strftime('%Y-%m-%d') How can I do it? -
How to sync the upload progress bar with upload on s3 bucket using Django Rest Framework
I am working on a REST API (using Django Rest Framework). I am trying to upload a video by sending a post request to the endpoint I made. Issue The video does upload to the s3 bucket, but the upload progress shows 100% within a couple of seconds only however large file I upload. Why is this happening and how can I solve this it? PS: Previously I was uploading on local storage, and the upload progress was working fine. I am using React. -
Updating fields in django table not working
currently i am trying to update some fields in a table with ajax post method, i have given acondition if ajax[data] != 'None' then update one field. it works only if condition has one statement if i pass another one it is updating only that field instead of all metioned in the update quesry. def outwardmailupdateMaker(request): datetime = 'None' if request.is_ajax() and request.method == "POST": out_id = request.POST['out_id'] senders_details = request.POST['senders_details'] mail_particulars = request.POST['mail_particulars'] address = request.POST['address'] sender_remarks = request.POST['remarks'] pod_number = request.POST['pod_number'] if pod_number != 'None': bm_pod_confirmation = 'Updated' else: bm_pod_confirmation = 'Pending' OutwardMailTable.objects.filter(pk=out_id).update(senders_details=senders_details, mail_particulars=mail_particulars, address=address, sender_remarks=sender_remarks, pod_number=pod_number, bm_pod_confirmation=bm_pod_confirmation) return HttpResponse("test") this is updating all the fields in passed to update method, but below one is only updating the pod_uploaded_date field when pod_number!='None' def outwardmailupdateMaker(request): datetime = 'None' if request.is_ajax() and request.method == "POST": out_id = request.POST['out_id'] senders_details = request.POST['senders_details'] mail_particulars = request.POST['mail_particulars'] address = request.POST['address'] sender_remarks = request.POST['remarks'] pod_number = request.POST['pod_number'] if pod_number != 'None': bm_pod_confirmation = 'Updated' pod_uploaded_date = now else: bm_pod_confirmation = 'Pending' OutwardMailTable.objects.filter(pk=out_id).update(senders_details=senders_details, mail_particulars=mail_particulars, address=address, sender_remarks=sender_remarks, pod_number=pod_number, pod_uploaded_date=pod_uploaded_date, bm_pod_confirmation=bm_pod_confirmation) return HttpResponse("test") -
POPULATE DJANGO MODEL BY IMPORTING CSV FILE - IndexError list index out of range
In my Django project i have a list full of client's information: client, name, surname, email, phone This is the code of my Client Model: class Client(models.Model): client = models.CharField(max_length=1500) name = models.CharField(max_length=255, blank=True) surname = models.CharField(max_length=255, blank=True) email = models.EmailField(blank=True) phone = PhoneNumberField(blank=True) def __str__(self): return f"{self.client}" def get_absolute_url(self): return reverse('rubrica-clienti-view') This is the model that represents the CSV FILE that the user will upload: class csvCliente(models.Model): file_name = models.FileField(upload_to='csvs/clienti-csv') uploaded = models.DateTimeField(auto_now_add=True) activated = models.BooleanField(default=False) def __str__(self): return f"File id:{self.id}" def get_absolute_url(self): return reverse('rubrica-clienti-view') This is the form: class csvClienteForm(forms.ModelForm): class Meta: model = csvCliente fields = ('file_name',) I want to give the users the possibility of adding new Clients by importing a CSV FILE, so I implemented this function in the views.py: def import_csv_clients(request): form = csvClientForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = csvClientForm() obj = csvClient.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for row in enumerate(reader): row = "".join(row) row = row.replace(",", " ") row = row.split() cliente = row[1].upper() Client.objects.create( client=cliente, name=row[2], surname=row[3], email=row[4], phone=row[5], ) obj.activated = True obj.save() template = 'csv-importa-clienti.html' context = {'form': form} return render(request, template, context) After i upload the file i get this … -
Django Admin - Populate subcategory based on category
I'm trying to create in django admin interface a subcategory populated based on category previously selected. (same as in the image) django version: django-3.1.2 python version: Python 3.7.7 I followed the following tutorial: https://medium.com/better-programming/optimizing-django-admin-6a1187ddbb09 (which was also mentioned on a previous question here. Unfortunately, the same code doesn't work for me. Bellow is my code: models.py class department(models.Model): name = models.CharField(max_length=60) def __str__(self): return (self.name) class team(models.Model): department=models.ForeignKey(department, on_delete=models.CASCADE) teamName=models.CharField(max_length=150) def __str__(self): return (self.teamName) class employee(models.Model): department = models.ForeignKey(department, on_delete=models.CASCADE) team=models.ForeignKey(team, on_delete=models.CASCADE) employeeName=models.CharField(max_length=150) def __str__(self): return (self.employeeName) admin.py class departmentAdmin(admin.ModelAdmin): list_display = ["name" ] search_fields = ["name"] class Meta: model = department class teamAdmin(admin.ModelAdmin): list_display = ["teamName" ,"department"] search_fields = ["teamName", "department"] class Meta: model = team class employeeAdmin(admin.ModelAdmin): list_display = ["employeeName","team", 'get_name'] search_fields = ["employeeName", "team"] class Meta: model = employee def get_name(self, obj): return obj.team.department get_name.admin_order_field = 'department' get_name.short_description = 'department' views.py def get_subcategory(request): id = request.GET.get('id','') result = list(team.objects.filter(department_id=int(id)).values('id', 'name')) print(result) return HttpResponse(json.dumps(result), content_type="application/json") urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^/getSubcategory/$', views.get_subcategory), url(r'home', views.home) ] change_form.html - Placed on project templates {% extends "admin/change_form.html" %} {% block extrahead %} {{ block.super }} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> $(function(){ // inspect html to check id of category select … -
Define a radio button in django
I am new in Django and I need to provide a simple form in my site. the form looks like this: My form I searched and I couldn't find any tutorial on this. html file: <form id="form" name="form" method="POST"> {% csrf_token %} <b>Is this prediction True?</b> <br> <label>No ! </label> <input type="radio" value="0" name="No" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="No"> <br> <label>Yes!</label> <input type="radio" value="1" name="Yes" data-form-field="Option" class="form-check-input display-7" id="checkbox2" title="Yes"> <br> <label>It is not a proper picture!</label> <input type="radio" value="2" name="Yes" data-form-field="Option" class="form-check-input display-7" id="checkbox3" title="none"> <br> forms.py: class FormYesOrNo(forms.Form): pvs1 = forms.TypedChoiceField(label = 'Was this prediction True?', choices=choices, widget=forms.RadioSelect) I am not sure about the above code and I don't know how to get the value response and use it in my views.py. Can you please help me in this or send me a proper documentation? -
how to show the values of a object without the name of foreign key class in python(django)
the Customer class has a foreign key to User class. i want to return this information but i don't want to show user__ before username and first_name and ... . data = {"customers": list(p.values("id", "user__username", "user__first_name", "user__last_name", "user__email", "phone", "address", "balance"))} how can i get something like that: { "customers": [ { "id": 12, "username": "leon2", "first_name": "lee", "last_name": "michalson", "email": "hamed@example.com", "phone": "042-22334455", "address": "Tehran, No.1", "balance": 20000 } ] } -
I am trying to load new page from my dashboard menu but getting page not found
my dashboardExample: I created a dashboard containing three menu under sidebar menu. On clicking "Tables menu" I receive errors like -->> Page not found Using the URLconf defined in Analyticweb.urls, Django tried these URL patterns, in this order: website/ [name='home'] website/ dd [name='dev'] admin/ The current path, website/static/home2.html, didn't match any of these. My codes are as follows: Analytic.urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('website/', include('website.urls')), path('admin/', admin.site.urls), ] website.urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('dd', views.deb, name='dev'), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): # return HttpResponse("<h1>hello world</h1>") return render(request, 'website/home1.html' ) def deb(request): return render(request, 'website/home2.html' ) -
Django bootstrap datepicker plus formset new field does datepicker does not work
Whenever a new field is dynamically added to the form the datepicker does work. If I am saving the form, and then try to update it, the datepicker works on the an additional field. I am using Django-bootstrap-datepicker-plus template.html {% load crispy_forms_tags %} {% load staticfiles %} {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {{ formset.media }} <table class="col-md-9" style="margin-left: 10px;"> {{ formset.management_form|crispy }} {% for form in formset.forms %} <tr class="{% cycle 'row1' 'row2' %} formset_row-{{ formset.prefix }}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field|as_crispy_field }} </td> {% endfor %} </tr> {% endfor %} </table> <br> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src='{% static "jquery.formset.js" %}'></script> <script type="text/javascript"> $('.formset_row-{{ formset.prefix }}').formset({ addText: 'add another', deleteText: 'remove', prefix: '{{ formset.prefix }}', }); </script> forms.py from bootstrap_datepicker_plus import DatePickerInput class DebtForm(forms.ModelForm): class Meta: model = Debt exclude = () widgets = { 'period_start': DatePickerInput(), } Any ideas how to make it work? Thanks Best wishes, Ted -
Got AttributeError when attempting to get a value for field `author` on serializer `CommentViewSerializer`
Here is the serializers.py class CommentViewSerializer(serializers.ModelSerializer): author = UserViewSerializer() class Meta: model = Comment fields = ('author','content','article') def create(self, validated_data): return Comment.objects.create(**validated_data) Here is the models.py class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlefda') author = models.ManyToManyField(User,unique=False, related_name='articsles') parent = models.ForeignKey('self', null=True, blank=True,on_delete=models.CASCADE, related_name='replies') content = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now=True) why do i keep getting the error?There is no typo or something. Got AttributeError when attempting to get a value for field `author` on serializer `CommentViewSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'author'. -
Django: Passing parameter to a URL pattern name inside views
In the example below, I'm trying to use the URL pattern name (ie, 'update_profile') instead of the absolute path (/profile/str:pk/update) in one of my views. This way if I later change my url path, I don't have to go an change each time I used the absolute path. My question: how do I pass 'pk' into a pattern name? I've tried things like: success_url = 'update_profile' % (pk) But that doesn't seem to work. urls.py path('/profile/<str:pk>/update', views.ProfileUpdateView.as_view(), name='update_profile'), views.py def submit_profile_form(request, pk): if request.method == "POST": success_url = 'update_profile' // <------ How do I pass 'pk' in here? ... return redirect(success_url) Thanks for your help! -
Can we upload a django project on cpanel and run it if the cpanel doesnt have a terminal?
I got the basic hosting plan from godaddy. Most tutorials on youtube are trash. So can we use a cpanel which doesn't have terminal to run a django project? and should we include the venv folder while we upload? -
Django NoReverseMatch at http://127.0.0.1:8000/boards/1/new/
This is my site urls: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('boards.urls')) ] And this is my app urls: urlpatterns = [ path('',views.home,name='home'), path('boards/<int:pk>',views.board_topic,name='board_topic'), path('boards/<int:pk>/new/',views.new,name='new_topic') ] This is the Views for app: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse,Http404 from .models import Board # Create your views here. def home(request): board = Board.objects.all() return render(request,'home.html',{ 'board':board, }) def board_topic(request,pk): # try: # board = Board.objects.get(pk=pk) # except: # raise Http404 board = get_object_or_404(Board,pk=pk) return render(request,'topics.html',{ 'board':board }) def new(request,pk): boards = get_object_or_404(Board, pk=pk) return render(request, 'new_topic.html', { 'board' : boards }) when I try to go to http://127.0.0.1:8000/boards/1/new/ then this error occurs: enter image description here please help me. -
Wagtail set default page explorer view location for PageChooserBlock in admin
Way to browse pages from particular location in PageChooserBlock, like browse "sub pages or same level pages" from current editing page in which this block is used. I observed that when any page is selected in PageChooserBlock then browsing starts from the same current selected page. I wanted to start default browsing from current edting page (in which this PageChooserBlock block is used) if no page is already selected. Is there any way to do it? I googled for some way or direction for doing it but no success. I also checked chooser hook but there is no way to get current editing page in this hook. So can't use it. Also tried to search in source code of PageChooserBlock for such possibility but no success for me or may be I missed the possible way. Your help is appreciated. -
Django Model Creating with Verbose Name
When creating a model object, can you use the verbose name to create? I have a model that has a dot in the name and I cannot have dot in a variable name. -
access Task attributes in comment CreateView(form) in Django
Good evening! I need a little help... Again :) I have two classes in my models.py (same app) Tasks and Comments, in order to create a comment I made a Class in views.py CreateView, is a built in form that django creates... Well when I send the user to comment_form to create a new comment I would like to have the task info in that page... Something like: {{user.username}} you're about to comment in {{task.title}} - {{task.content}} {{form}} The problem is that I can not access task.title, task.content and for that matters not even user.username variables in that form... I went through the docs and couldn't find a solution not even a clue on how to think to solve that. Models.py: class Task(models.Model): title = models.CharField(max_length=50) content = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) responsable = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name="author", default=author) STATUS_CHOICES = [('D', 'Done'),('P','Doing'),('N','Not done')] Status = models.CharField(max_length=1,choices=STATUS_CHOICES, default='N') IMPORTANCE_CHOICES = [('H', 'High'),('M','Medium'),('L','Low')] importance = models.CharField(max_length=1,choices=IMPORTANCE_CHOICES, default='M') DEPARTAMENT_CHOICES = [('D', 'Dev'),('M','Marketing'),('H','HR'),('L','Legal'),('F','Finances'),('O','Others')] departament = models.CharField(max_length=1,choices=DEPARTAMENT_CHOICES, default='M') is_public = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("task-detail", kwargs={"pk": self.pk}) class Comment(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) body … -
Paginating FormView
My goal is to create a mixin that would take care of paginating both ListView and FormView that has a list of FormSets in the template. While ListView part is mostly straight forward, I'm having hard times trying to paginate created formsets. Is there any clever way to include pagination inside generic views? All tips and any contribution will be highly appreciated! -
how to run docker-compose up . i get this ERROR: ""Top level object in './docker-compose.yml' needs to be an object not '<class 'NoneType'>'.""
I using python 3.8, Docker version 19.03.13, build 4484c46d9d 3.8 version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 -
Serve multiple web requests in Django
I am using Django with Nginx and want to serve multiple requests in parallel. We have Docker configuration and one pod has 10 cores. I am trying to create multiple workers in uWSGI like (uwsgi --socket /tmp/main.sock --module main.wsgi --enable-threads --master --processes=10 --threads=1 --chmod-socket=666) Request first lands to view and from there it calls service file which does heavy work. Actually, I am using openCV library in service file which has loop over all pixels to remove colored ones(pretty time consuming..) I also tried using multiple cores and 1 worker as (uwsgi --socket /tmp/main.sock --module main.wsgi --enable-threads --master --processes=1 --threads=10 --chmod-socket=666). But still performance did not improve. I think it is due to GIL which is getting acquired while doing heavy I/O operations, not sure how I can find a work around it. Or use all cores in some other efficient way? TIA! -
Django Celery Beat for periodic task in Django with Celery is not working
I wanted to add celery to my django project. But somehow it does not seem to work as expected although I followed the steps in the official documentation. Here are the parts of my Django project: # celery.py import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookProjectSetting.settings') app = Celery('bookProjectSetting') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() app.conf.beat_schedule = { 'update-lifetime': { 'task': 'tasks.update_life_time_of_books', 'schedule': crontab(minute='*/5'), }, } Then the init file: # __init__.py from .celery import app as celery_app __all__ = ('celery_app',) Now, in my app folder( called books), the tasks.py looks like follows: from books.models import Book from celery import shared_task @shared_task def update_life_time_of_books(): # Query all the books in our database print("Query all books.") books = Book.objects.all() # do sth. with books. for the sake of brevity I do not show this In my settings.py file I have this for celery: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_TIMEZONE = 'Europe/Berlin' # ... bla bla INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_celery_beat', 'rest_framework', 'books', ] I started the redis server in a second tab via the redis-server command so that it can take the part as a broker. I … -
Python Executing SQL fails over due to non existing field in json data
I am getting some JSON data from a third party API. I am trying to add that data into my own database to be used for a website. I loop through each record in the JSON and execute a SQL query to insert that data into my database. However some records in the JSON data doesn't exist, and therefore causes my query to fail. I have set defaults for these fields for this reason however it still falls over. isNonFoilOnly field will only appear in some of of the records in the JSON data. models.py class Set(models.Model): code = models.CharField(max_length=100, unique=True) keyrune_code = models.CharField(max_length=100) name = models.CharField(max_length=100) type = models.CharField(max_length=100) release_date = models.DateField() base_set_size = models.IntegerField() total_set_size = models.IntegerField() is_online_only = models.BooleanField(default=False) is_non_foil_only = models.BooleanField(default=False) is_foil_only = models.BooleanField(default=False) sale_status = models.BooleanField(default=False) def __str__(self): return self.name views.py response = requests.request("GET", "https://mtgjson.com/api/v5/SetList.json") data = response.json()["data"] sorted_obj = sorted(data, key=lambda k: k['releaseDate'], reverse=False) sql = """ INSERT INTO dashboard_set (code, keyrune_code, name, type, release_date, base_set_size, total_set_size, is_online_only, is_non_foil_only, is_foil_only, sale_status) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ) ON CONFLICT (code) DO UPDATE SET keyrune_code = %s, name = %s, type = %s, release_date = %s, base_set_size … -
Exists check takes forever in Django SQLite
I am running a webservice where a user sends a word as a request, and I use that word to filter entries in my database (the default Django SQLite). The relationship word-to-entry is one-to-one. That means there are two possible cases: The word exists in the database -> Return the associated Entry. The word doesn't exist -> Throw exception. The following lookup should then return a QuerySet with 1 or 0 objects: Entry.objects.filter(word__iexact=word) Expected Behavior: Cases 1 and 2 do not differ perceptibly in speed. Current Behavior: Case 1 takes at most half a second. Case 2 takes forever, around 1-2 minutes. I find this puzzling. If an existing word can be looked up regardless of where it is in the database, then why does case 2 take forever? I am not a django or database expert, so I feel like I'm missing something here. Is it worth just setting up a different type of database to see if that helps? Here is the relevant portion of my code. I'm defining a helper function that gets called from a view: mysite/myapp/utils.py from .models import Entry def get_entry(word): if Entry.objects.filter(word__iexact=word).exists(): entry = Entry.objects.filter( word__iexact=word ) # Case insensitive exact lookup return … -
Multiple user types with multiple authectication methods in Django
How can i create multiple user types with multiple authentication method. Consider the following scenario. User Types: Admin, Staff, User, Writer, Business Admin and Staff types are need to authenticate with company email address and password Staff and Writer types are need to authenticate only with phone number. (no password) Business type is need to authenticate with email(any) and password. How can I create Django models, according to above example. -
ValueError could not convert string to float: ''
I'm having my app on heroku. I use timeme js to record user's active time spend on the page, and use a hidden form to store the value into the database. Additionally, I'm using otree package to write my app. The following is the code I use: models.py class Active(ExtraModel): active_duration = models.FloatField() active_record = models.LongStringField() views.py/pages.py in otree class intro_instructions(Page): def before_next_page(self): data = self.form.data p = self.player active = Active.objects.create(active_duration=data['active_duration'], active_record=data['active_record']) active.save() html <form method="post" role="form" id="form" autocomplete="off">{% csrf_token %} <input type="text" name="active_record" id="id_active_record" style="display: none" > <input type="number" step='any' name="active_duration" id="id_active_duration" style="display: none"> </form> The error ValueError could not convert string to float: '' { "csrfmiddlewaretoken": "vVhVRLrAUokmiNGRpzCaP78bnTOQyowf5VMfIDgKGglWGuEyQAU2wooWjQzXuBgD", "active_duration": "", "active_record": "" } Is it because active_duration is empty? Will it help if I set blank=true, null=true for the forms? I was assuming that every use would have value for the input. Also any ideas about why the input is empty? Could it be that the user used scripts to skip the page without visible fields? From the sentry error message, this happened to one user twice. -
Is it possible to use rows of one table as columns of other in django?
I am creating a quiz in Django where we add questions in one table and options in another table (using foreign key to link it to a question). I want to create a new table named Quiz which will store user input for each questions. I mean if I add four questions in Question table, having three Options objects each one, then quiz table has three columns which will store user input of each question. Quesions table : columns = ('id', 'question') rows = {(1, 'What is your name'), (2, 'Where do you live)} Choices table : Columns = ('id', 'choice', 'Question id(foreign key)') Rows = { ('1',"ram", QID-1,), ('2',"Sham", QID-1,), ('3',"India", QID-2,), ('4',"USA", QID-2,) } Quiz table (I want) : Columns = ('quizID', 'QID-1','QID-2') Rows = {('1', 'ChoiceID-1', 'ChoiceID-4'), ('2', 'ChoiceID-2', 'ChoiceID-4')} The idea is shown in the example...However, I don't find any other way than creating quiz columns manually for each question. I am trying to do this in Django. Kindly help me. or let me know if you have another idea to do the same thing.