Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin select dropdown
I have a field in my model called day. I want in the admin area to have a pre populate dropdown for this field instead of the text input. I have search and cant find a solution. <select name="day" id="day"> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> </select> Modle: class Timetable(models.Model): gym_class = models.ForeignKey('GymClass', on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() day = models.CharField(max_length=12) time_slot = models.CharField(max_length=12) trainer = models.ForeignKey('Trainer', on_delete=models.CASCADE) def __str__(self): return self.gym_class.name admin.py: from django.contrib import admin from .models import GymClass, Category, Trainer, Timetable admin.site.register(GymClass) admin.site.register(Category) admin.site.register(Trainer) admin.site.register(Timetable) -
Trying to COPY adjacent folder into Docker image but copies the entire folder over
I have a directory structure like the following: project-root/ api/ docker/ Dockerfile ... src/ auth/ contact/ settings/ asgi.py settings.py urls.py wsgi.py manage.py client/ docker/ Dockerfile nginx.conf src/ App.js index.js In my API Dockerfile I'm trying to just copy src in to /app. However, I keep getting the entire api directory. What I expect to see is: app/ auth/ contact/ settings/ asgi.py settings.py urls.py wsgi.py manage.py This stage is the only one where src is copied over. The python-base and builder-base are either env vars or application dependencies. FROM python-base as production COPY --from=builder-base $VENV_PATH $VENV_PATH RUN chmod +x . /opt/pysetup/.venv/bin/activate COPY ../src /app WORKDIR /app CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application", "-t", "150"] I've tried COPY ../src /app, COPY ./src /app, COPY src /app. How should I copy over just the src to app in this project structure? -
Need help iterating through each row in SQLite DB to render to html template
I'm using the Django framework with SQLite DB. I'm using SQL queries in my views.py and connecting that data to render on the frontend in my dashboard.html template. I'm having trouble iterating through each row in my database table 'scrapeddata'. When I view the dashboard, the data being rendered is all bunched up together in one div. I'm hoping to get each row in the database to render in one div each. I tried placing a for loop in my views.py but when I do that, I only get one row from the database rendered on dashboard.html. Any help is appreciated, thank you. views.py: def dashboard(request): connection = sqlite3.connect('db.sqlite3') cursor = connection.cursor() col1 = '''SELECT companyname FROM scrapeddata ORDER BY companyname ASC''' cursor.execute(col1) companyname = cursor.fetchall() col2 = '''SELECT name FROM scrapeddata''' cursor.execute(col2) name = cursor.fetchall() col3 = '''SELECT portfolio FROM scrapeddata''' cursor.execute(col3) portfolio = cursor.fetchall() people_data = [] data = { 'companyname': companyname, 'name': name, 'portfolio': portfolio } people_data.append(data) connection.close() if request.user.is_authenticated: return render(request, 'dashboard.html', {'people_data':people_data}) else : return redirect('/login') dashboard.html: Here's the for loop in the template. {% for data in people_data %} <div> <p>{{ data.companyname }}</p> <p>{{ data.name }}</p> <p>{{ data.portfolio }}</p> </div> {% endfor %} -
Django passing a variable through the path, causing path repetitions. how to get out of that loop?
I know this is an armature question but here goes. I have a url path as follows: path('projects/<s>', PL.projects), and i pass a string from the html template by putting it into an herf tag like so projects/some_string. this works once but then the base url changes to <ip>/projects/some_string. so when i try to excite the path to pass a string in that domain then I get an error as the url is now <ip>/projects/projects/some_string. how do i set it up so that i can pass as many strings as possible as many times as possible without having to clean my url in the browser everytime. Thanks for the help. -
Get cumulative running sum with group by in django orm
I have a table of two (relevant) columns. table: Transaction columns: transaction_date, amount I would like to get the cumulative amount for each month. So, for each month, get the sum of transactions from the beginning to that point in time. In PostgreSQL I would do something like this: SELECT date_trunc('month', transaction_date::date) AS formatted_transaction_date, SUM(SUM(amount)) OVER (ORDER BY date_trunc('month', transaction_date::date) ROWS UNBOUNDED PRECEDING) AS cumulative_transaction_amount FROM transaction GROUP BY date_trunc('month', transaction_date::date); I am trying to do the same in Django Orm. The closest I have gotten is this: Transaction.objects.values( formatted_transaction_date=TruncMonth('transaction_date') ).annotate( cumulative_transaction_amount=Window( expression=Sum('amount'), order_by=TruncMonth('transaction_date').asc(), frame=RowRange(start=None, end=0), ), ) This however throws an error: django.db.utils.ProgrammingError: column "transaction.amount" must appear in the GROUP BY clause or be used in an aggregate function I understand that the Django query I am executing is not identical to the PostgreSQL query. The PostgreSQL query runs SUM(SUM(amount)), while the Django query translates simply to SUM(amount). However, I was unable to find the syntax of Django to achieve same result. What am I doing wrong? -
One database with multiple django projects
I have two django projects connecting to same database. One of them is using authentication with custom user model and is working fine. Now i have to secure second project and use user authentication. It will be more or less similar to what we are using in first project. I tried creating models in second project but i think it is conflicting with already existing django tables. My question is how can we have two separate projects, each having their own django tables (auth and other). Till now i have tried and i am getting following error ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'app.customuser', but app 'app' doesn't provide model 'customuser'. -
Django Annotate - get list of numbers in annotate
This models djago implements annotate with ArrayAgg, just in excecuted queryset view error Unable to get repr for <class 'project.model.auditoria.AuditoriaQuerySet'>. Help me please. this is query: modelA.objects.filter(field_a_id__in=list_elements,field_b_id=n).annotate(arrar_list_with_annotate=ArrayAgg(list(ModelB.objects.filter(ModelB.field_a = Cast('modelA.field_a', IntegerField()), modelA.field_c = int(nn)).values_list('ModelB.field_a', flat=True)))).values('create','view','modified','delete','arrar_list_with_annotate') -
Add delete raw button to table from database Django
I have a form on the page that adds data to the database and displays it in a table I need to add a button that will delete a specific row by id from the database index.html <tbody> {% for expense_item in expense_items %} <tr> <td>{{ expense_item.username}}</td> <td>{{ expense_item.expense_name }}</td> <td>{{ expense_item.category }}</td> <td>{{ expense_item.cost }}zł</td> <td>{{ expense_item.date_added}}</td> <td>BUTTON HERE</td> </tr> {% endfor %} </tbody> Models.py class ExpenseInfo(models.Model): username = models.CharField(max_length=255, default='NoName') expense_name = models.CharField(max_length=20) category = models.CharField(max_length=20) cost = models.FloatField() budget_id = models.CharField(default='0123456789', max_length=10) date_added = models.DateField() user_expense = models.CharField(max_length=20) Views.py def add_item(request): budget_id = request.user.last_name name = request.POST['expense_name'] category = request.POST['category'] expense_cost = request.POST['cost'] expense_date = request.POST['expense_date'] try: ExpenseInfo.objects.create(username=request.user, expense_name=name, category=category, cost=expense_cost, date_added=expense_date, user_expense=budget_id) except ValueError or TypeError: print('No data.') return HttpResponseRedirect('app') -
Django 3 Form Data not posting to DB and I would like it to, what am I missing?
This in in the early stages of testing and my expectation is that I should have enough here to write to the DB and I see no signed of a failure anywhere aside from the empty table after several POST attempts. #WEB FORM <form action="/" method="POST" id="ticketsubmitform"> {% csrf_token %} <div class="form-control" {% if form.date_submitted.errors %}errors{% endif %}> {{ form.date_submitted.label_tag }} {{ form.date_submitted }} {{ form.date_submitted.errors }} </div> <div class="form-control" {% if form.contact_name.errors %}errors{% endif %}> {{ form.contact_name.label_tag }} {{ form.contact_name }} {{ form.contact_name.errors }} </div> <div style="padding-bottom: 12pt"> <button type="submit"> >>> Submit Ticket >>> </button> </div> </form> #views.py def ticketing_app(request): if request.method == 'POST': form = TicketForm(request.POST) if form.is_valid(): ticket = Ticket( date_submitted=form.cleaned_data['date_submitted'], contact_name=form.cleaned_data['contact_name'], ) ticket.save() else: form = TicketForm() return render(request,'authentication/ticketing-app.html',{ "form": form }) #forms.py class TicketForm(forms.Form): date_submitted = forms.DateField(label="Date Submitted:", required=True, error_messages={ "required": "Date must not be empty." }) contact_name = forms.CharField(label="Contact Name:", max_length=45, required=True, error_messages={ "required": "Contact Name must not be empty.", "max_length": "Please enter a shorter name." }) #models.py class Ticket(models.Model): #---Base Meta----------------------------------------- date_submitted = models.DateField(max_length=15) contact_name = models.CharField(max_length=45) No errors on post - [29/Sep/2021 21:18:55] "POST / HTTP/1.1" 200 I do not see anything missing that would prevent a DB write -
django coverage not covering the urls despite writing specific tests for the urls
in my app named backoffice_engine, my urls.py file is as follows from django.urls import path, include from . import views urlpatterns = [ path('test/', views.test, name='test'), path('', views.dashboard, name='dashboard'), path('dashboard/', views.dashboard, name='dashboard'), path('add_new_client/', views.add_new_client, name='add_new_client'), path('edit_client/<int:client_id>', views.edit_client, name='edit_client'), .....some more paths.... ] my test_urls.py file for this urls.py file is as follows from django.test import SimpleTestCase from django.urls import reverse, resolve from backoffice_engine.views import * class TestBackofficeEngineUrls(SimpleTestCase): def test_test_url(self): url = reverse('test') self.assertEquals(resolve(url).func, test) def test_blank_url_uses_dashboard_function(self): url = reverse('dashboard') self.assertEquals(resolve(url).func, dashboard) def test_add_new_client(self): url = reverse('add_new_client') self.assertEquals(resolve(url).func, add_new_client) def test_client_detail(self): url = reverse('client_detail', args=['1']) self.assertEquals(resolve(url).func, client_detail) my understanding is runnning coverage on this file should result in coverage report showing that the following urls have been covered by unit tests. however coverage report for backoffice_engine.urls.py is zero missing by default. the report only is checking only the first 3 lines of the urls.py file -
how to take multiple images from webcam and save into database javascript - django
i'm trying to use modelformset_factory with capturing image from webcam , in order to take several images and save into database ? i'm only able to take one image , is there any way to achieve that please ? or how to use dynamic number of canvas ? class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] UploadDocumentFormSet = modelformset_factory(Document,form=UploadDocumentsForm,extra=1,can_delete=True) views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('take a picture or choose an image')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) **NOTE ** my javascript solution doesnt work with formset const player = document.getElementById('player'); const docs = document.getElementById('document') const captureButton = document.getElementById('capture'); const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); context.drawImage(player, 0, 0, canvas.width, canvas.height); const imgFormat = canvas.toDataURL(); docs.value = imgFormat e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); <button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none … -
Django custom user 'Account' object has no attribute 'has_module_perms'
I create a custom user model to login via email, but i got some issue when im tried to login on admin channel from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManajer(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name, last_name, username, email, password): user = self.create_user( email = self.normalize_email(email), password= password, username = username, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self.db) return user I'm able to create a superuser. However, when I try to login with email. I got this Error Exception Type: AttributeError Exception Value: 'Account' object has no attribute 'has_module_perms' Exception Location: ....\env\lib\site-packages\django\utils\functional.py, line 241, in inner Can someone fix that ? -
Django join between 3 tables
Hi i dont know really how i can perfom a join between this 3 tables. class Table1(models.Model): '''Productos a ser utilizados''' name = models.CharField() class Table2(models.Model): '''Productos a ser utilizados''' table1 = models.ForeignKey(Table1, related_name='TableTwo', on_delete=models.CASCADE, null=True, blank=True) class Table3(models.Model): '''Productos a ser utilizados''' codigo = models.IntegerField() table1 = models.ForeignKey(Table1, related_name='TableThree', on_delete=models.CASCADE, null=True, blank=True) im really confused about subquerys and join on django i dont know how i can do this. -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value
I am trying docker-compose an app with django and postgres using docker-compose but I get an error with the "NAME" Here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'POSTGRES_NAME': 'postgres', 'POSTGRES_USER': 'postgres', 'POSTGRES_PASSWORD': env('POSTGRES_PASSWORD'), 'POSTGRES_HOST': 'localhost', 'POSTGRES_PORT': '5432', } } Here is my docker-compose version: "3.8" services: web: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db environment: DATABASE_URL: postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_NAME env_file: - .env db: image: postgres container_name: pgdb ports: - "5432" env_file: - .env environment: POSTGRES_USER: $POSTGRES_USER POSTGRES_PASSWORD: $POSTGRES_PASSWORD POSTGRES_NAME: $POSTGRES_NAME Here is my .env DEBUG=on SECRET_KEY=sec DATABASE_URL=postgres://postgres:pass@localhost:5432/postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=pass POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_NAME=postgres Where does this "NAME" come from? Thanks for your help -
Django, Postgres and Docker compose: django.db.utils.OperationalError: could not connect to server: Connection refused
Here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': env('POSTGRES_PASSWORD'), 'HOST': 'localhost', 'PORT': '5432', } } Here is my docker-compose version: "3.8" services: web: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db environment: DATABASE_URL: postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_NAME env_file: - .env db: image: postgres container_name: pgdb ports: - "5432" env_file: - .env environment: POSTGRES_USER: $POSTGRES_USER POSTGRES_PASSWORD: $POSTGRES_PASSWORD POSTGRES_DB: $POSTGRES_NAME Here is my .env DEBUG=on SECRET_KEY=thekey DATABASE_URL=postgres://postgres:thepassword@localhost:5432/postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=thepassword POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_NAME=postgres Inside my postgres database it says 2021-09-29 20:29:02.375 UTC [1] LOG: starting PostgreSQL 13.4 (Debian 13.4-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit 2021-09-29 20:29:02.375 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2021-09-29 20:29:02.375 UTC [1] LOG: listening on IPv6 address "::", port 5432 2021-09-29 20:29:02.379 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2021-09-29 20:29:02.384 UTC [26] LOG: database system was shut down at 2021-09-29 20:29:00 UTC 2021-09-29 20:29:02.390 UTC [1] LOG: database system is ready to accept connections PostgreSQL Database directory appears to contain a database; Skipping initialization I am not able to connect the django app with the postgres, can someone please help? I have started … -
Django - PermissionRequiredMixin - Return a 'permission_denied_message' in current View, instead of a 403 Page?
Django version 3.0.5 I want to use the PermissionRequiredMixin in my View to display a banner message the same way I would with the SuccessMessageMixin. For example, if a user attempts to delete an object and they do not have permissions, the permission_denied_message would essentially be treated as an error message an displayed in the current view as a banner message. Is that even possible? the code that I currently have does not work - it always redirects to the 403 page. see below: class DocDeleteView(PermissionRequiredMixin, SuccessMessageMixin, DeleteView): model = SlateDoc success_url = reverse_lazy('slatedoc-list') success_message = "SlateDoc was deleted!" permission_required = ('slatedoc.delete_slatedoc') raise_exception = True permission_denied_message = "Permission Denied" def delete(self, request, *args, **kwargs): if self.has_permission() is False: messages.error(self.request, self.permission_denied_message) else: self.object = self.get_object() self.object.soft_delete() messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url()) -
django register_simple_tag send two parameter and how can ı use this in if condition?
In my project I want user make just one comment to Doctor profile.So ı choosed to use register_simple_tag and find if user made comment before bu if condition doesn't work.Can anyone know which part is wrong or has the another better way to solve this issue? commentExist.py register=template.Library() @register.simple_tag def isCommentExist(request,doctor): commmentExist=CommentModel.objects.filter(parent=None,is_published=True,doctor=doctor,comment_user=request.user).count() if commmentExist: return True else : return False profile.html {% if request.user.is_authenticated %} {% load commentExist %} {% isCommentExist request doctor as existComment %} {% endif %} {% if existComment %} # make some operation {% else %} # make some operation {% endif %} -
redirect doesn't convert special characters correctly on redirect in django
I have a page in my django app that requires authentication. If the user hits mydomian/my_page the view will evaluate if the request is authenticated. If authenticated the request will get routed to the right html page (my_page.html). If the request is unauthenticated the request will be routed to the login page with a redirect: class MyView(View): def get(self, request): user = request.user context = { 'username': user.username } if user.is_authenticated and user.is_staff: return render(request, 'path/to/my_page.html', context) logout(request) return redirect('/admin/login?next=/my_page') This worked pretty well, when an unauthenticated user hit mydomain/my_page it will get routed to mydomain/admin/login/?next=/my_page and once authenticated it will get routed to mydomain/my_page with will serve path/to/my_page.html. Now I updated to the latest django version and the rerouting changed: When an unauthenticated request hits my page it gets rerouted to this url mydomain/admin/login/?next=/admin/login%3Fnext%3D/my_path. Once the login happens on that page, the page gets rerouted to mydomain/admin instead of mydomain/my_page. Then when I call mydomain/my_page it gets routed to the right page (since the request is authenticated). I tried replacing the redirect with return HttpResponseRedirect((('/admin/login?next=/my_page').encode('utf-8'))) but didn't work. I also couldn't find anything in the django docs on if and how the changed the redirect method. Any ideas? -
'AnonymousUser' object has no attribute '_meta' | Django
Errors occurs while authenticating user, CODE settings.py AUTH_USER_MODEL = 'Authentication.User' AUTHENTICATION_BACKENDS = ( ('django.contrib.auth.backends.ModelBackend'), ('Authentication.auth.CustomAuthEmailBackend.EmailAuthBackend'), ) Custom Backend from django.contrib.auth.models import User from django.contrib.auth.backends import BaseBackend class EmailAuthBackend(BaseBackend): def Authenticate(self, request, email, password): try: user = User.objects.get(email=email) success = user.check_password(password) if success: return user except User.DoesNotExist: pass return None def get_user(self, uid): try: return User.objects.get(pk=uid) except: return None views.py user_id = 1 password = ******* user = User.objects.get(pk=user_id) user.unique_username = unique_username userid = int(user_id) user.custom_user_id = createUserUnqiueId(userid) user.is_active = True useremail = user.email user.save() user = auth.authenticate(request, email=useremail, password=password, backend='Authentication.auth.CustomAuthEmailBackend.EmailAuthBackends') auth.login(request, user, backend='Authentication.auth.CustomAuthEmailBackend.EmailAuthBackend') return redirect('index') CODE EXPLANATION Working with email login by overriding username login. Then in authentication I have coded a custom for authentication but sometimes it works fine and default gives error and sometimes custom authentication back-end displays error and default authentication back-end works fine. Why? Also, if an authentication back-end is working fine on localhost, it displays errors after uploading on C panel. ERROR AttributeError at /auth/activate/Mjc/atr5z0-1d1d9f0050ff97fec5e766fd2418b520/s%2523f%253FO%253E%2560!c%257CK-0B92 'AnonymousUser' object has no attribute '_meta' Request Method: POST Request URL: http://app.barter.monster/auth/activate/Mjc/atr5z0-1d1d9f0050ff97fec5e766fd2418b520/s%252523f%25253FO%25253E%252560!c%25257CK-0B92 Django Version: 3.2.7 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute '_meta' Exception Location: /home4/barter/virtualenv/Barter/3.8/lib/python3.8/site-packages/django/utils/functional.py, line 247, in inner Python Executable: /home4/barter/virtualenv/Barter/3.8/bin/python3.8 Python Version: 3.8.6 Python … -
how to iterate multiple lists in django template
I'm trying to iterate a zip list to templates.So basically I have three lists of zip list I want to iterate it to template with this format(example picture). that's why I used three for loop in here all data are dynamic like (content,cards,posts).I think i may be some error with for loop on templates. If you need more info I can give you.And also if you have another better way than this please let me know. So here is my zip list zipped_lists = zip(card_postings, arrays, post_content) And also this is template {% for card,posts,contents in zipped_lists %} <div class="card"> <div class="card-body"> <h4 class="text-center">{{ card }}</h4> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for post in posts %} <div class="col"> <div class="card"> <div class="card-header text-center text-primary"> <h5>{{ post }}</h5> </div> <ul class="list-group list-group-flush"> <li class="list-group-item border-0"> {% for subj in contents %} <i>{{subj}} <br> </i> {% endfor %} </li> </ul> </div> </div> {% endfor %} </div> </div> </div> {% endfor %} </div> -
Django upload and read vcard object - loosing my mind
I am trying to let users of my Django app upload vcards through a form, parse those vcards on the fly and then serve some of the content back to the front-end without storing the vcards on server. I have successfully found a way to read and extract content from vcards that are stored on my machine using the vobject library and a few lines of code like the one below with open(vcard_path) as source_file: for vcard in vobject.readComponents(source_file): full_name = vcard.contents['fn'] .... However, I am failing to replicate this approach when accessing a vcard file that has been uploaded through a django form. I have this form <form action="{% url "action:upload_vcard" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <div class="col-md-8"> <input type="file" name="vcard" id="vcard_file" required="True" class="form-control"> </div> </div> <div class="form-group"> <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;"> <button class="btn btn-primary"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button> </div> </div> </form> and this is the view def upload_vcard(request): data = {} if "GET" == request.method: return render(request, "action/upload_test.html", data) # if not GET, then proceed file = request.FILES["vcard"] with open(file) as source_file: for vcard in vobject.readComponents(source_file): full_name = vcard.contents['fn'] return HttpResponseRedirect(reverse("action:upload_vcard")) In this case … -
NoReverseMatch Django Project
I want to create the products through the customer's profile, so that the customer's name is attached to the form when creating the product that is related to it. But i cant find the error, please help me urls.py urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/<str:pk>', views.createOrder, name='create_order'), path('update_order/<str:pk>', views.updateOrder, name='update_order'), path('delete_order/<str:pk>', views.deleteOrder, name='delete_order'), path('create_customer/', views.createCustomer, name='create_customer'), ] views.py Here I focus on the "create Order" function passing the customer's primary key and using "initial" to append the customer's name to the form def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): customer = Customer.objects.get(id=pk) form_value = OrderForm(initial={'customer':customer}) if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form_value = OrderForm(instance=order) if request.method == … -
How to repair flex in one part of page?
I created website, with this template. But somehow I get not to work flex on this part where is copyright. I'm working in django and even if I copy same code, this part is not working. Any idea how to solve this? <!-- Fotter Bottom Area --> <div class="footer-bottom-area"> <div class="container h-100"> <div class="row h-100"> <div class="col-12 h-100"> <div class="footer-bottom-content h-100 justify-content-between d-flex align-items-center"> <div class="copyright-text d-flex"> <p>Copyright &copy;<script>document.write(new Date().getFullYear());</script> All rights reserved | This template is made with <i class="fa fa-heart-o" aria-hidden="true"></i> by <a href="https://colorlib.com" target="_blank">Colorlib</a></p> </div> </div> </div> </div> </div> </div> -
Is there a way I can download the headers only as a file in Django ImportExportModelAdmin
Is there a way to just download a file that contains only the field titles? For example, the download template button will download a file that has all the necessary fields as shown in the help text. The downloaded file would look like this: Any help is appreciated. -
Download mp3 files in client system from api using django framework
I have built a website where I need to let users download mp3 files by calling API. But, the files are downloading in the server, not in the client system. def download(url: str, dest_folder: str): if not os.path.exists(dest_folder): # create folder if it does not exist os.makedirs(dest_folder) filename = "1.mp3" file_path = os.path.join(dest_folder, filename) r = requests.get(url, stream=True) if r.ok: print("saving to", os.path.abspath(file_path)) with open(file_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024 * 8): if chunk: f.write(chunk) f.flush() os.fsync(f.fileno()) download(i="API URL mylink", dest_folder="C:/Users/"+username+"/Desktop/call_logs") Please help me how to change this code in such a way that the file has to download into the client system!