Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React On Click Prevent Download but show excel
I have a link from microsoft one drive which is generated when we upload file pythonically. I have linked this link to a button whichis supposed to show the file but not download however on click it is donloading the file so i neeed help regarding how to prevent download but show the excel file linked. Below is react code I have been using function Files(props){ let getFileOnClick=(fileAddress)=>{ window.location.href=fileAddress } return( <button style={{float:'right'}} onClick = {()=>getFileOnClick(props.link)} className="btn btn-primary"> Get File </button> ) } -
Retrieve field values to Django Admin using many to many relationships
I have a simple task: I need to expose player name related to Game in game list (Django Admin). Game object has ManyToMany relationship with Player object via 'players' attribute. The problem is that now I have empty 'players_list' field (empty list means I don't know what to do and just leave it here[enter image description here][1]), though I tried Player.objects.all() and obviously got all players even those who are not bound to particular game. I feel it has simple solution but my brain refuses to work after 55 opened tabs. Thanks in advance! This is my models.py from django.db import model class Player(models.Model): name = models.CharField(max_length=54, default="") email = models.EmailField(max_length=54) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Game(models.Model): name = models.CharField(max_length=254, default="") players = models.ManyToManyField(Player, blank=True, related_name='player_games') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) players_list = [] def __str__(self): return self.name and admin.py from django.contrib import admin from .models import Game, Player class PlayerInline(admin.TabularInline): model = Game.players.through @admin.register(Player) class Admin(admin.ModelAdmin): search_fields = ['name', 'email'] list_display = ('name', 'email', 'created_at', 'updated_at') inlines = [ PlayerInline, ] @admin.register(Game) class AdminAdmin(admin.ModelAdmin): list_display = ('name', 'created_at', 'updated_at', 'players_list') inlines = [ PlayerInline, ] exclude = ('players',) Pic as it looks … -
Trying startapp in Django and i get core exception update sqlite3
When starting project in Django no sqlite3 file created. Trying startapp i get core exception update sqlite3 later version required. How update? -
How to send images to DRF with json request?
I am working on a ecommerce project, and I want to add products from the frontend. The files in my product app in django is as follows models.py: from django.db import models from django.forms import CharField from PIL import Image from io import BytesIO from django.core.files import File # Create your models here. class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: ordering = ('name',) def __str__(self): return self.name def get_absolute_url(self): return f'/{self.slug}/' class Product(models.Model): category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=6, max_digits=6) image = models.ImageField(upload_to='uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-date_added',) def __str__(self): return self.name def create_thumbnail(self, image, size = (300,200)): img = Image.open(image) img.convert('RGB') img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'JPEG') thumbnail = File(thumb_io, name=image.name) return thumbnail def get_image(self): if self.image: return f'http://localhost:8000' + self.image.url else: return '' def get_thumbnail(self): if self.thumbnail: return f'http://localhost:8000' + self.thumbnail.url else: if self.image: self.thumbnail = self.create_thumbnail(self.image) self.save() return f'http://localhost:8000' + self.thumbnail.url else: return '' def get_absolute_url(self): return f'/{self.slug}/' views.py: from sys import excepthook from unicodedata import category from django.http import Http404 from django.shortcuts import render from .serializers import ProductSerializer from rest_framework.views import … -
Serializer for status check
I have a Django project where a restaurant with orders and tables. You can see below the model: class Order(models.Model): STATUS_CHOICES = ( ("in_progress", "In_progress"), ('completed', 'Completed') ) table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=False, null=False, related_name='order_table') user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, related_name='order_user') status = models.CharField(choices=STATUS_CHOICES, null=True, max_length=15) I should restrict creating a new order if the table is still in progress. I guess it should be done through serializer but hove no idea about the validation and how to connect request with database information current serializer (standard): class OrdersModelSerializer(ModelSerializer): class Meta: model = Order fields = "__all__" current view: class OrdersFilter(filters.FilterSet): class Meta: model = Order fields = ( 'user', 'table__id', 'status', ) class OrdersModelViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrdersModelSerializer pagination_class = LimitOffsetPagination filter_backends = (DjangoFilterBackend, OrderingFilter) filter_class = OrdersFilter ordering_fields = ('table', 'user', 'status') -
Why is the system telling me that I don't have Python 3.10 in my system when I do?
I'm using pipenv for my virutal enviroment and am trying to install psycopg2 in Docker. However, when I try to install it, I get the following error. docker-compose exec web pipenv install psycopg2-binary Warning: Python 3.10 was not found on your system... Neither 'pyenv' nor 'asdf' could be found to install Python. You can specify specific versions of Python with: $ pipenv --python path/to/python I checked the python version within the virtual enviroment and it gives me 3.10.2. % python --version Python 3.10.2 I also checked the python version outside of the virtual enviroment(the system) but here, it gives me python 3.8.8 as default. python --version Python 3.8.8 Despite this, when I type python3.10 in the command line, it shows me that I have it installed in the system, so I'm unsure why it says 3.10 isn't found on my system. python3.10 Python 3.10.2 (v3.10.2:a58ebcc701, Jan 13 2022, 14:50:16) [Clang 13.0.0 (clang- 1300.0.29.30)] on darwin Type "help", "copyright", "credits" or "license" for more information. Lastly, this all happens when I'm in using conda activate. I need conda activate for pipenv to work. When I do "conda deactivate" and type python --version , it gives me the following: conda deactivate % … -
How to customize the validation error message in Django?
I am trying to create a registration page in Django and to check fields validation. I wanna set a custom validation error message to the email field. Can you help me, please? Here is the view.py: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc def newUser(request): form = NewUserFrom(request.POST or None) if not form.is_valid(): context = {'frmNewUser':form} return render(request,'login/newuser.html', context) return render(request, "login/welcome.html") Here is the forms.py: from ctypes import alignment from email import message from urllib import request from django import forms class NewUserFrom(forms.Form): error_css_class = 'error' username = forms.CharField(max_length=50, widget=forms.TextInput, label="Username") password = forms.CharField(widget=forms.PasswordInput, label="Password") confirm_password = forms.CharField(label="Confirm password", widget=forms.PasswordInput) name = forms.CharField(max_length=50, widget=forms.TextInput, label="Name") email = forms.EmailField(max_length=50, widget=forms.EmailInput, label="Email") def clean_password(self): cleaned_data = super().clean() pwd = cleaned_data.get('password') cof_pwd = cleaned_data.get('confirm_password') # if pwd and cof_pwd: if pwd != cof_pwd: raise forms.ValidationError('Password is not match.') return cleaned_data def clean(self): cleaned_data = super(NewUserFrom,self).clean() email = cleaned_data.get('email') if email.strip() == "".strip(): # self.add_error('email','Email is reqiered.') raise forms.ValidationError('Email is reqiered.') else: fistPart, secPart = str(email).split('@') raise forms.ValidationError('Email error.') Here is the NewUser.html: {% block content %} <form method="POST"> {% csrf_token %} <table> {{frmNewUser.as_table}} {% for field in frmNewUser.fields %} {% … -
I tried updating django_site row to change the name but I have gotten ERROR: column "alt native" does not exist
I tried updating django_site to change the name (and later domain) to something more appropriate so that i could use these strings for email sending operations. I understand it is based on this: https://docs.djangoproject.com/en/4.0/ref/contrib/sites/ but I do not know what they are really talking about. Any help much appreciated. What I tried: postgres=# update django_site set django_site.name = "alt native"; ERROR: column "alt native" does not exist LINE 1: update django_site set django_site.name = "alt native"; ^ postgres=# select * from django_site id | domain | name ----+-------------+------------- 1 | example.com | example.com (1 row) -
How to install pillow on Namecheap server
Collecting pillow Using cached Pillow-9.0.1.tar.gz (49.5 MB) Preparing metadata (setup.py) ... done WARNING: Generating metadata for package pillow produced metadata for project name unknown. Fix your #egg=pillow fragments. Discarding https://files.pythonhosted.org/packages/03/a3/f61a9a7ff7969cdef2a6e0383a346eb327495d20d25a2de5a088dbb543a6/Pillow-9.0.1.tar.gz#sha256=6c8bc8238a7dfdaf7a75f5ec5a663f4173f8c367e5a39f87e720495e1eed75fa (from https://pypi.org/simple/pillow/) (requires-python:>=3.7): Requested unknown from https://files.pythonhosted.org/packages/03/a3/f61a9a7ff7969cdef2a6e0383a346eb327495d20d25a2de5a088dbb543a6/Pillow-9.0.1.tar.gz#sha256=6c8bc8238a7dfdaf7a75f5ec5a663f4173f8c367e5a39f87e720495e1eed75fa has inconsistent name: filename has 'pillow', but metadata has 'unknown' Using cached Pillow-9.0.0.tar.gz (49.5 MB) Preparing metadata (setup.py) ... done WARNING: Generating metadata for package pillow produced metadata for project name unknown. Fix your #egg=pillow fragments. Discarding https://files.pythonhosted.org/packages/b0/43/3e286c93b9fa20e233d53532cc419b5aad8a468d91065dbef4c846058834/Pillow-9.0.0.tar.gz#sha256=ee6e2963e92762923956fe5d3479b1fdc3b76c83f290aad131a2f98c3df0593e (from https://pypi.org/simple/pillow/) (requires-python:>=3.7): Requested unknown from https://files.pythonhosted.org/packages/b0/43/3e286c93b9fa20e233d53532cc419b5aad8a468d91065dbef4c846058834/Pillow-9.0.0.tar.gz#sha256=ee6e2963e92762923956fe5d3479b1fdc3b76c83f290aad131a2f98c3df0593e has inconsistent name: filename has 'pillow', but metadata has 'unknown' Using cached Pillow-8.4.0.tar.gz (49.4 MB) Preparing metadata (setup.py) ... done Building wheels for collected packages: pillow Building wheel for pillow (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [144 lines of output] /opt/alt/python38/lib64/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) /opt/alt/python38/lib64/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'project_urls' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/PIL copying src/PIL/BlpImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/ImageFilter.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/ImageGrab.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/FpxImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/ImageShow.py -> build/lib.linux-x86_64-3.8/PIL copying src/PIL/Hdf5StubImagePlugin.py -> build/lib.linux-x86_64-3.8/PIL … -
ImproperlyConfigured at /books/ Field name `Published_date` is not valid for model `Books`
I am building this rest api which gets data from database and shows all the fields regarding the books in database. models.py code: class Books(models.Model): Name = models.CharField(max_length=250) Author = models.ForeignKey('Authors', on_delete=models.CASCADE, default=None) Published_Date = models.DateField(blank=False) Pages = models.IntegerField() critics = models.IntegerField(default=0) def __str__(self) -> str: return self.Name serializer.py code: class BookSerializer(serializers.ModelSerializer): class Meta: model = Books fields = ['Name', 'Author', 'Published_date', 'Pages', 'critics'] urls.py code: urlpatterns = [ path('books/', views.BookList.as_view()), path('Bdetails/<str:pk>', views.BookDetail.as_view()), ] views.py code: class BookList(generics.ListCreateAPIView): queryset = Books.objects.all() serializer_class = BookSerializer class BookDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Books.objects.all() serializer_class = BookSerializer traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/books/ Django Version: 3.2.9 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'genebox', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python39\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch response … -
Auto guess Profit/Loss from django and react
I'm creating and analysis website using Yahoo Finance API. models.py class Stock(models.Model): money_to_invest = models.CharField(max_length=100) stock_price = models.CharField(max_length=100) company = models.CharField(max_length=50) profit_or_loss = models.CharField(max_length=20) author = models.ForeignKey(User, on_delete=models.CASCADE) In profit_or_loss field want to auto save value Profit or Loss. if money_to_invest is greater than stock_price than is is Profit. How it can be possible through Django and React. I'm also using Redux for state management. -
How to check if an input value is exists and validate if yes in Django
I made a text input filed with jquery autocomplete where I query the users. So if I start typing the name of a user it shows the related users. It works fine but I like to avoid that if the user like note to choose from the pupped up list and possibly type all the name and it has a mistake. So I like to make a function that checks if the added value of the field is equals with any of the users in the database. How to do that? html <input type="text" class="form-control" placeholder="Type name here" name="kap_bar_01" id="kap_bar_01"> <script> $(function() { var names = [ {% for u in related_users %} "{{ u.user.last_name }} {{ u.user.first_name }}", {% endfor %} ]; $( "#kap_bar_01" ).autocomplete({ source: names }); }); </script> models.py class Kapcsolodasok(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) kap_bar_01 = models.TextField(max_length=200) views.py def kapcsolodasok(request): profile = Profile.objects.get(user=request.user) related_users = Profile.objects.filter(projekt=profile.projekt) context = { 'related_users': related_users, 'profile': profile, } #lots of stuffs here return render(request, 'stressz/kapcsolodasok.html', context) Thank you in advance! -
Create a timer which resets itself after 24 hours but doesn't get restarted after the page is reset
i'm creating a web app and i'm trying to create a countdown timer for a certain product that is on discount and i'm wondering if there is a way to not reset the timer after the page has been refreshed and when it reaches 0 , wait 24 hours and then reset itself automatically. Here is a picture of a timer down below: Here is the code of a timer: var count = 420; var counter = setInterval(timer, 1000); function timer() { count = count - 1; if (count == -1) { clearInterval(counter); return; } var seconds = count % 60; var minutes = Math.floor(count / 60); minutes %= 60; document.getElementById("timer").innerHTML = (minutes).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) + ":" + (seconds).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}); // watch for spelling document.getElementById("timer2").innerHTML = (minutes).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}) + ":" + (seconds).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false}); // watch for spelling } -
Import issue in Djoser- Django
I'm trying to build an user authentication system with React and Django. I'm using JWT, Djoser for authentication model. serializers.py: from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ("id", "email", "name", "password") settings.py: DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_USERNAME_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid},{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid},{token}', 'ACTIVATION_URL': 'activate/{uid}{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } But I get import error for Djoser, Import "djoser.serializers" could not be resolved I have tried changing names but nothing helped. The package isn't importing. I can edit and add more things like models.py and other things if they are necessary. Any help is appreciated. -
Count() outputs list and not a dictionary in django
I don't know what's happening this might be easy but I am stuck. I have the below queryset job_title = Employee.objects.filter().values('role__name').annotate(total=Count('id')) output I get [{'tole__name': 'Manager', 'total':2}, {'role__name': 'Director': 3}] now when I try to get the dictionary like {2, 3} using totals = job_title['total] I get an error -
how to setup 2 static files in nginx
am host a project in AWS . but static file is not access in the project. i have 2 app in my Django project. am set up the nginx . nginx have only set up the 1 static file. how am set 2 static file in the nginx -
Starbank Webhook not working with django and ngrok
I´ve trying to receive invoices with webhook in starbank webhook with django, but i don´t know what i´m doing wrong. In ngrok receive 502 BAD GATEWAY. Could anyone help me ? this is my coide in view: from django.http import HttpResponse from pypro.base.djangosdkstarkbank import webhook_extracting_and_sending_transfer ,sending_invoices_for_24_HRs import json from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST sending_invoices_for_24_HRs() # Create your views here. @csrf_exempt @require_POST def webhook_request(request): jsondata = request.body data_v = json.loads(jsondata) print(data_v) for answer in data_v['form_response']['answers']: # go through all the answers type_v = answer['type'] print(f'answer: {answer[type_v]}') type_u=f'answer: {answer[type_v]}'# print value of answers webhook_extracting_and_sending_transfer(type_u) return HttpResponse(200) and this is my code in djangostarkbank : import starkbank from datetime import datetime, timedelta import json from decouple import config from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST import time import names from random import randint private_key, public_key = starkbank.key.create("sample/destination/path") private_key_content = """""" # This is asecret key, you have to get one new_name = names.get_full_name() current_time = f'{(datetime.now())}' current_data_bank = current_time[0:9] new_avenue = f'Avenida {names.get_full_name()},{randint(0, 15000)}' new_zip_code = f"{randint(0, 99999)}-{randint(0, 999)}" new_tax_id = f'{randint(0, 999)}.{randint(0, 999)}.{randint(0, 999)}-{randint(0, 99)}' new_city = names.get_full_name() new_district = names.get_full_name() new_state = f"{names.get_full_name()}" new_simbol_state = f'{new_state[0:2]}'.upper() user = starkbank.Project( environment="sandbox", id="5933018535428096", private_key=private_key_content ) … -
One field in Django cannot retrieve the correct value when showing in template
models.py class Order(models.Model): PAYMENT_OPTIONS = ( ('VISA','VISA'), ('Master','Master'), ('Octopus','Octopus'), ('Cash','Cash'), ) STATUS = ( ('Pending','Pending'), ('Delivered','Delivered'), ('Collected','Collected'), ) METHODS = ( ('外賣自取','外賣自取'), ('送遞','送遞'), ) user = models.ForeignKey(User,models.CASCADE,null=True,blank=True) customer = models.CharField(max_length=200,null=True,blank=True) card_id = models.IntegerField(null=True,blank=True) mobile = models.IntegerField(null=True,blank=True) email = models.CharField(max_length=200,null=True,blank=True) total_price = models.DecimalField(decimal_places=2,max_digits=7) payment_method = models.CharField(max_length=50,choices=PAYMENT_OPTIONS,null=True,blank=True) status = models.CharField(max_length=50,choices=STATUS,default='Pending') take_method = models.CharField(max_length=50,choices=METHODS,null=True,blank=True) points_earned = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) address = models.CharField(max_length=350,null=True,blank=True) def __str__(self): return str(self.customer)+'\'s Order' views.py def checkout(request): global cartlist cartlist1 = cartlist total = 0 for unit in cartlist: total += int(unit[3]) grandtotal = total + 100 earnings = int(grandtotal/5) print(grandtotal) if request.method == 'POST': print(type(request.POST.get('customerPayment'))) print(request.POST.get('customerPayment')) print(request.POST.get('customerTakeaway')) customerName = request.POST.get('customerName','') customerID = request.POST.get('customerID','') customerMobile = request.POST.get('customerMobile','') customerEmail = request.POST.get('customerEmail','') customerPayment = request.POST.get('customerPayment'), customerTakeaway = request.POST.get('customerTakeaway'), customerAddress = request.POST.get('customerAddress','') new_order = Order.objects.create( user = User.objects.get(username=request.user), customer = customerName, card_id = customerID, mobile = customerMobile, email = customerEmail, total_price = grandtotal, payment_method = customerPayment, take_method = customerTakeaway, points_earned = earnings, address = customerAddress) account = User.objects.get(username=request.user) checkout.html <tr> <td style="width:160px;text-align:center;"> <strong>付款方式</strong> </td> <td style="width:200px;text-align:center;"> <input type="radio" name="customerPayment" value="VISA" id="customerPayment">VISA <input type="radio" name="customerPayment" value="Master" id="customerPayment">Master<br> <input type="radio" name="customerPayment" value="Octopus" id="customerPayment">Octopus <input type="radio" name="customerPayment" value="Cash" id="customerPayment">Cash </td> </tr> <tr> <td style="width:160px;text-align:center;"> <strong>領取方式</strong> </td> <td style="width:200px;text-align:center;"> <input type="radio" name="customerTakeaway" value="外賣自取" id="customerTakeaway">外賣自取 <input type="radio" … -
How to test downloading a path in a Django unittest?
How do you find the fully qualified URL for a static media file hosted by the test server inside a Django unittest? I'm trying to write a test for a custom process that downloads a media file and does some processing on it. The code must be able to download an arbitrary URL, not hosted by me, but for the sake of the test, I'm simply trying to test the download functionality with a local static file. However, attempts by the requests library to access any URLs allegedly being hosted by the test server return the error: HTTPConnectionPool(host='localhost', port=8082): Max retries exceeded with url: /static/mydata.zip (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fe7a2ff8bb0>: Failed to establish a new connection: [Errno 111] Connection refused')) These answers suggest the URL I use can be http://testserver/static/mydata.zip or http:///localhost:8082/static/mydata.zip, but neither of these work. What am I doing wrong? What URL should I use? If I run the dev server from localhost:8000, then I can confirm the URL http://localhost:8000/static/mydata.zip works. To the file itself is setup to be correctly served. However, that URL is not accessible during the unittest. -
Cannot continue the bash script after creating a virtual environment using pipenv
I'm writing a bash script that automates the process of creating a django project and creating some folders and files that is necessary for a django project. The problem here is, when I create and activate the virtual environment using the pipenv shell command, The virtual environment is created and activated but the next command is not executed. The script just waits to exit the virtual environment and when I exit/deactivate the virtual environment, then the next lines of the bash script gets executed. My next line is pipenv install django. When this line is executed, django is installed in the virtual environment and again it waits for the user to exit the virtual environment and when I exit the environment, the next line is executed. But my next line is django-admin startproject myproject when this line is executed, I'm getting the error command not found. Yes I know why I'm getting this error. The environment is deactivated and it can't recognize the django-admin command. Also, I'm running this script as a superuser. I'm using wsl2. my code: mkdir "django_project" cd "django_project" pipenv shell pipenv install django read -p "Enter your project name: " PROJECT_NAME django-admin startproject "$PROJECT_NAME" cd "$PROJECT_NAME" … -
500 Error when debug=false Django. Works fine when DEBUG=true
also have s3 buckets set up and that works fine when debug=true. Not sure whats going on. allowed hosts are good and i also did python manage.py collectstatic. anyone know th problem?? from dotenv import load_dotenv load_dotenv() import os import dj_database_url from django.conf import settings import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY',) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = bool( os.environ.get('DEBUG', False) ) ALLOWED_HOSTS = ['quickthrift-andregrandon.herokuapp.com', '198.211.99.20', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'home', 'products', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'allauth'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', # required by allauth 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mio.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { … -
Django Queryset order of evaluation
I have some confusion about how this snippet is evaluated class T(models.Model): person = models.CharField(max_length=10) location = models.CharField(max_length=10) error = models.BooleanField() T.objects.bulk_create([ T(person='P1', location='L1', error=False), T(person='P1', location='L1', error=True), T(person='P2', location='L2', error=False), T(person='P2', location='L2', error=False) ]) for t in T.objects.all().values('person', 'location').distinct().annotate(error=Sum('error')): print(t) When I asked about it on this thread: Combine rows on django queryset, It was explained to me that distinct().annotate(error=Sum('error')): is evaluated as its own unit, but I can't find any proof that this is true. To me, I would expect that the queryset is made to have only distinct values, then it is annotated which would have different effects than what I'm looking for. Any documentation that explains the order of evaluation would be appreciated. -
How to set Multi Level Foreign Key field in Django?
I have a model that looks like this # models.py from django.db import models class Level_0(models.Model): Kode = models.CharField(max_length=10, null=False, blank=False, default="") class Level_1(models.Model): Kode = models.CharField(max_length=10, null=False, blank=False, default="") Level_0= models.ForeignKey(Level_0, on_delete=models.CASCADE) class Level_2(models.Model): Kode = models.CharField(max_length=10, null=False, blank=False, default="") Level_1 = models.ForeignKey(Level_1, on_delete=models.CASCADE) # Level_0 = ???????????? # how do I create a connection to Level_0? a field that is automatically filled with Level_0? What I want to have is a field in Level_2 that automatically connects to Level_0 through Level_1. How do I add that field in my Level_2 model? -
How do i use django and python request to make a post request Properly
I am using django and python request to make a post request to this endpoint with the authorization header and body gotten from this website. i want your assist to get this difficulty proper and to make this code work. class RechargeData(models.Model, Main): user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) phone_number = models.CharField(validators=[Main.phone_regex], max_length=10) network = models.CharField(choices=Main.OPERATORS, max_length=15) plan = models.IntegerField(choices=Main.PLANS) amount = models.DecimalField(max_digits=10, decimal_places=2) i have the view.py file that contains the python request as follows import requests import json from .forms import RechargeForm def rechargedata(request): url = "http://127.0.0.1:8000/api/data/" payload = "{\"network\": network_id,\n\"mobile_number\": \"09037346247\",\n\"plan\": plan_id}" headers = {'Authorization': 'Token 5fd60vcdfddfxddsssfddff9a0a8742d','Content-Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=payload) if request.method == "POST": form = RechargeForm(request.POST) if form.is_valid(): phone_number = form.cleaned_data['phone_number'] network = form.cleaned_data['network'] amount = form.cleaned_data['amount'] plan = form.cleaned_data['plan'] form.save context = RequestContext(request, { 'phone_number': responsedata.mobile_number, 'network': response.data.network_id, 'mobile_number': response.data.network_id, 'plan': response.data.plan_id, }) return render(request, 'embeds.html', {'context': context, 'form'; form}) else: form = RechargeForm() return render(request, 'index.html', {'context': context, 'form'; form}) This code is not working and am sure not to be getting something proper here. can someone help me out? -
One review per user in the current title
I am trying to make so that every user could only post one review per title (product). First idea was to do this through UniqueTogether, but it resulted unsuccessful. So now, I thought to complete it by validate in serializer. Right now I am getting the following error: TypeError: Review() got an unexpected keyword argument 'title'. But if you look at my code below I did not pass title argument to Review(). I even tried to make error on purpose to see what arguments I can pass to Review() and title was not there. django.core.exceptions.FieldError: Cannot resolve keyword 'title_d' into field. Choices are: author, author_id, comments, id, pub_date, score, text, title_id, title_id_id serializers.py class ReviewSerializer(serializers.ModelSerializer): author = serializers.SlugRelatedField( slug_field='username', default=serializers.CurrentUserDefault(), read_only=True ) class Meta: model = Review fields = ('id', 'text', 'author', 'score', 'pub_date') def validate(self, data): title_id = self.context['view'].kwargs['title_id'] author = self.context['request'].user if Review.objects.filter(title_id=title_id, author=author).exists(): raise serializers.ValidationError( 'You cannot post second review on same item.' ) return data models.py class Review(models.Model): title_id = models.ForeignKey( Title, on_delete=models.DO_NOTHING, related_name='reviews' ) text = models.TextField( 'Текст отзыва' ) author = models.ForeignKey( User, on_delete=models.DO_NOTHING, verbose_name='Автор', related_name='reviews' ) score = models.IntegerField( choices=SCORES ) pub_date = models.DateTimeField( 'Дата публикации', auto_now_add=True,) class Title(models.Model): name = models.CharField( max_length=255, …