Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get the `pk` from the endpoint while doing object level validation?
I have an endpoint as api/v1/controller/{pk}/device Now I want to add a device to the controller object while I am doing the object level validation by acquiring the {pk} of the controller object:- def validate(self, data): data['device'] = self.(do something to get the PK present in the endpoint) data.full_clean() return data Is there any way I can get the pk/id from the endpoint while doing an object level validation for performing a create operation under the controller resource. -
How to use data posted for one view into another view in django rest
I am working on a project in which user enters some ranges like (starting_date, ending_date, starting_roll_num, ending_roll_num, and subject) and it queries the DB and returns a csv file but i want to add another feature which enables the user to also get the remaining data after he has entered the ranges and downloaded the first file but for this I have to make an other function, the problem is how will I use the data posted on the first function. Here is my code: serializer.py class DatasetGeneratorSerializer(serializers.Serializer): start_roll = serializers.IntegerField() end_roll = serializers.IntegerField() start_date = serializers.DateField() end_date = serializers.DateField() subject = serializers.IntegerField() def create(self, validated_data): pass views.py @api_view(['POST']) @authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def attendance_datasetgenerator(request): serializer = DatasetGeneratorSerializer(request.data) start_roll = serializer.data['start_roll'] end_roll = serializer.data['end_roll'] start_date = serializer.data['start_date'] end_date = serializer.data['end_date'] subject = serializer.data['subject'] att= Attendance.objects.filter(date__range=(start_date,end_date), student__pk__range=(start_roll,end_roll), subject__exact=subject) df1 = DataFrame(att.values()) path = 'attendance_dataset.csv' csv1 = df1.to_csv('attendance_dataset.csv') response = HttpResponse(csv1, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=file1.csv' return response -
Can't have a slug with the word `media` in it. Django
Setup I have a very simple app where the main page display a list of items and if you click on an item you go the the item detail. Here is a part the model for such item: # projects/models.py class Project(models.Model): ... title = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from="website_title", always_update=True) ... As you see the slug for the item is determined based on the name (it removes spaces, special characters, etc.) Now, in my urls.py I have the following: # projects/urls.py urlpatterns = [ path("", ProjectListView.as_view(), name="home"), path("<slug:slug>", ProjectDetailView.as_view(), name="project"), ] Problem The problem is that if a project name contains the word media in it (in the beginning) then the resulting path will return an error. For example, if a project is called MediaCMS then the server will try the following url https://builtwithdjango.com/mediacms, but it will return an error (below). The work around I found is to add underscore to the name of the project (i.e. _MediaCMS). The issue is obviously due to some sort of mix and match between the project slug and the MEDIA_URL, which for me is the following: # builtwithdjango/settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media/") Note Interestingly, this is not an issue, … -
Django Querset Extract PKs
I have the following code. queryset = Registry.objects.filter( epas_id__contains=uuid_obj_id ).values_list('pk', flat=True) Based on my data, this correctly returns the following: <QuerySet [UUID('d9a0977c-5bc0-4667-af24-5e95b83761d4'), UUID('b2d0f086-0a55-44cc-b1ba-3ebf598d24ae')]> But what I want to do is extract just the values of pk in a list, so something like this: ['d9a0977c-5bc0-4667-af24-5e95b83761d4', 'b2d0f086-0a55-44cc-b1ba-3ebf598d24ae'] Any thoughts and help on how I can achieve this would be appreciated. -
deployment with apache collecting statics already 24hours
Im worried about collecting my staticfiles. When I was trying to deploy my project and I put command "python manage.py collectstatic" its asked me something like "Am I sure that im runing this command in virtual environment ?" I typed "yes " because I had acivated it, and then I think started to loading statics but it takes already about 24h and screen didnt changed since that time. Is it ok ? I have quite advanced frontpage from template but i dont think that much... Console looks like this and keep scrolling down with "new Y" Y Y Y Y Y[] Can hear very well my fan from CPU and ubuntu consol keep scrolling down itselfs all the time which is indicating me that isn't frozen. Should I cancel it or wait untill its will finish? -
Whenever I run command "python maanage.py runserver" It shows me OSError: [WinError 123]
Whenever I run command python manage.py runserver this errors are showing OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' and I don't know why that code is not working I think it is because of the version?. This is a traceback error. I don't know what it is. Can someone explain to me why is this error is occurring? (venv) C:\python\Work\Project\45.MULTIFACTOR OPINION MININGMULTIFACTOR OPINION MINING\MULTIFACTOR OPINION MININGMULTIFACTOR OPINION MINING\MULTIFACTOR OPINION MININGMULTIFACTOR OPINION MINING\CODE\opinion mining\opinionmining>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\user\appdata\local\programs\python\python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\user\Envs\venv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\user\Envs\venv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\user\Envs\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Envs\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\Envs\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\users\user\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load … -
Adding a Token to Django request
Could anybody help me add an api AUTH token to my request, I'm unsure how to add non Django AUTH token to the request, I want to be able to insert the AUTH token into my request that way every time I use the website I wont have to constantly respond to the SMS message the api makes me do. Here is the code I have so far from robin_stocks import robinhood as RH @login_required def home(request: HttpRequest, *args, **kwargs): """ The landing page for the user, after they log in should contain a bunch of deets """ if (request.COOKIES['ul.token']): positions = RH.account.get_all_positions() print(positions) else: token = RH.authentication.login(username=env.RHemail, password = env.RHpassword) request.COOKIES['ul.token'] = token.access_token context = {'positions' : positions} return render(request, 'home.html', context) I saved it as ul.token because when I logged into my robin hood account that's what the tokens name was in my cookies. I probably missed the mark on this one as well PS: This right now is a personal project just for fun, so that explains my docstring (which is what I think """ """ is called) -
Django querysets. How to prefetch only unique?
Models: class House(Model) class Flat(Model): house = ForeignKey(House, related_name="houses") owner = ForeignKey(User) class User(Model) queryset: queryset = User.objects.prefetch_related( Prefetch("flats", queryset=Flat.objects.select_related("houses")) And then flats: {% for flat in user.flats.all %} <p>№ {{ flat.number }}, {{ flat.house.name }}</p> {% endfor %} It's fine. But for houses I need only unique ones {% for flat in user.flats.all %} <p>House {{ flat.house.name }}</p> {% endfor %} But this template gives me ALL houses, with duplicates. How can I avoid duplicates, any ideas? I tried .distinct() but it's dosen't work, looks like I using distinct() wrong or etc. -
Django models.DateTimeField invalid format
I'm trying to import database rows into Django models. The date format in the database I'm using is '%Y/%m/%d %H:%M:%S', and this is the error I get when I try to import the data: . . . File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1406, in get_prep_value value = super().get_prep_value(value) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1266, in get_prep_value return self.to_python(value) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1388, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“2013/01/01 07:57:25.689” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I have this line my settings.py: DATETIME_FORMAT = '%Y/%m/%d %H:%M:%S' How do I change the default format to be the same format as my data? Thank you! -
How to manage User Related operations on client servers which are Authenticated by A Central Auth Server in Django
I developed a Central Authentication Server with SimpleJWT for a company which have multiple websites and the users of all the websites will be authenticate through the Central Authentication Server. Now, here is the scenario- The Auth Server will have the User Table with UUID, phone/email and Password which will be used for authentication. On the other hand, suppose an ecommerce site have database tables Products, transactions etc. Now, how can I implement the user related operations like buy, sell, transactions etc. on the ecommerce site as I don't have any user table here. -
How to set specific conditions in models.py while entering data in admin panel?
room_category = models.ForeignKey(Cat, on_delete=models.CASCADE) number = models.IntegerField(unique=True) people = models.IntegerField() picture = models.ImageField(upload_to = 'room/', null=True, blank=True) actual_price = models.IntegerField() offer_price = models.IntegerField() def __str__(self): return '%d : %s with People : %d' % (self.number, self.room_category, self.people) I want to set a condition in offer_price table that offer_price < actual_price. It should show an error while entering data in the admin panel itself. -
Wrong size in bytes being displayed using BytesIO in Django
I am trying to validate images before they are uploaded to the database using django , but cant seem to get accurate size of images no matter what I do view.py: def upload_image(request): #used to upload images in document_upload c = main.objects.get(username = request.session['username']) unq_id = c.unq_id if request.method == 'POST': images = request.FILES.getlist('image') name = request.POST['name'] for x in images: img = Image.open(x) img_file = BytesIO() img.save(img_file, 'jpeg') image_file_size = img.tell() if image_file_size > 150 * 1024: print(image_file_size) failure = "image needs to be lesser dimenstion than 150kb" return render(request, 'Main/document_upload.html', {'failure':failure}) else: print(image_file_size) fs = FileSystemStorage() filename = fs.save(x.name, x) Doc1 = Doc(user_id = unq_id, upload = x, name = name) Doc1.save() success = "You have successfully added documents, proceed to 'My documents' to see your documents" return render(request, 'Main/document_upload.html', {'success':success}) While printing print(image_file_size) I seem to be getting a much lesser value , than the size shown in it's properties example print(image_file_size) shows 1295 while in reality the size is 8537 How do I solve this ? thank you -
django orm multiple filter on same many to many fields
class Book(models.Model): title = models.CharField(max_length=50) authors = models.ManyToManyField(Author) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) I want to find Books containing atleast the authors with first_name and last_name in the below list without using for loop(mentioned below) or raw query. authors = [{ 'first_name' : 'Test', 'last_name' : 'user1', }, {'first_name' : 'Tester', 'last_name': 'user2' } ] queryset = Book,objects.all() for i in authors: queryset = queryset.filter(authors__first_name=i.get('first_name',None), authors__last_name=i.get('last_name',None)) -
with this model structure how to calculate the total quantity for each product and view it in the product table in admin site?
Each order has one or more lineItem and each lineItem has product where its quantity is defined How to get the total quantity for each product from all the orders? class Product(models.Model): name = models.CharField(max_length=50) SKU = models.CharField(max_length=50) description = models.CharField(max_length=300) price = MoneyField(max_digits=19,decimal_places=4,default_currency='USD') def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.RESTRICT, null=True) image = models.ImageField() class Order(models.Model): date = models.DateField(auto_now_add=True) user = User.name class LineItem(models.Model): quantity = models.IntegerField() product = models.OneToOneField( Product, on_delete=models.CASCADE, primary_key=True, ) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return self.product.name -
how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework
how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework Here is how i set my defaultpermissions in my settings.py : REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # <-- And here ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } and i need to use AllowAny on the signUp method : @permission_classes([AllowAny,]) @api_view(["POST", ]) def add_new_user(request): if request.method == "POST": lang = request.data["lang"] .......... ......... ....... Still, it returns Authentication credentials were not provided. .. I mainly need to have permissions with a token with every request but not the register and login request. how to do it ?? -
Django hosted on Azure - file not found when using fpdf
I am running following code in my django project that works perfectly fine on localhost from fpdf import FPDF pdf = FPDF() pdf.add_page() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filepath = BASE_DIR + '/polls/static/polls/DejaVuSansCondensed.ttf' pdf.add_font('DejaVu', '', filepath, uni=True) pdf.set_font("DejaVu", size = 20) pdf.multi_cell(190,10,"Some nice text",0,0) test_string = pdf.output(dest = 's').encode('latin-1') Code breaks down in the last line with pdf.output after being uploaded for Azure App Service giving following error: [Errno 2] No such file or directory: 'polls\\static\\polls\\DejaVuSansCondensed.ttf' -
Why method "prepopulated_fields" doesn't work after saving object in Django admin?
I have described a model where a slug field fills in values from another field automatically, but after saving the object, the slug stops working. I would like the slug field to work as expected every time the object is saved. models.py: class Product(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) admin.py: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): save_as = True prepopulated_fields = {'slug': ('name',)} The documentation says that this is done on purpose. I would be glad if someone could share their experience on solving this problem. -
Getting Error Forbidden, you don't have permission to access this resource, when hosting my website with apache2 on port 443
my django website hosted on AWS EC2 apache ubuntu has ssl certificate obtained and setup through certbot but it is not opening on port 443(HTTPS).It is showing error Forbidden 403.There might be some permission issues.Kindly help me out -
Struggling w django-filter NoReverseMatch multiple fields
After days I'm relenting to ask this question on SO - my first post! I'm using django-filter, it was working a few weeks ago but spontaneously broke. I'm fighting complete defeat and 100% appreciate help. I've read the docs dozens of times and think I'm following them to the T... what am I doing wrong? The error is the dreaded: NoReverseMatch at /test_page/ Reverse for '' not found. '' is not a valid view function or pattern name." # location of error @ traceback return render(request, 'IW_Home/test_page.html', {'filter': f}) … ▼ Local vars Variable Value f <IW_Home.filters.testFilter object at 0x7f5ac5a80ba8> params 1 request <WSGIRequest: GET '/test_page/?connect_attributes__attribute_full__icontains=piano'> Much thanks. Code snippets below. % filters.py import django_filters from django_filters import CharFilter from .models import sampleModel class testFilter(django_filters.FilterSet): class Meta: model = IW00010Agencygeneral fields = { 'connect_attributes__attribute_full' : ['icontains'], } % urls.py from django.urls import include, path from django.conf.urls import url from .views import index,test_page urlpatterns = [ path('', index, name='index'), # Unclear here on whether to use path or url. # Also, when it worked previously I didn't need ^list$ path('test_page/', test_page, name='test_page'), url(r'test_page/^list$', test_page, name='test_page') ] % views def test_page(request): # Check how many parameters are completed. params = len(parse_qs(request.META['QUERY_STRING'])) # … -
Cookies persisted only with React proxy
Situation I am using a cookie-based authentication system in my project - a React frontend application and a Django backend. Django runs on localhost:8000 and React on localhost:3000. According to React Security Fundamentals I needed to set proxy inside package.json to be able to make my cookies unaccessible via JavaScript. In Django I simply set_cookie with the tokens I require (httponly set to True and max_age according to the token). Everything works up to this point. Recently I've started using Cypress for frontend testing and the proxy option inside package.json makes it impossible to mock requests. Because of that I removed the proxy option. Problem I am no longer getting the cookies saved in the browser. Removing httponly flag doesn't fix it. The cookies are still being sent normally as I can still see them in Postman. The only notable Django response header I can see in Postman is X-Frame-Options: SAMEORIGIN (seems not related). There are no CORS headers specified whatsoever. What is the reason that the cookies are ignored by the browser? What is the most optimal way of storing session without React proxy? -
Why do I have a differente hour data in Django Admin Panel and when I retrieve it from database
Maybe I´m just missing some step to be done before a retrieve the hour data. Im using the auto_now_add function for saving the time when a new record is created in Django. When I check that information I got the hour correctly, for example: July 5, 2021, 8:48 a.m. But when I retrieve that information for creating a JSON object, I got a differente result; for July 5, 2021, 8:48 a.m. I receive 2021-07-05 13:48:48.987675+00:00 What is the reason of this behavior ?. Note: I really don´t care about the date format, my main issue is the fact that in Django panel is showing 8:48 a.m. and when I retrieve the time field data from database I got 13:48 Note 2: I'm using this code in Django settings.py for setting up the server hour LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Mexico_City' USE_I18N = True USE_L10N = True USE_TZ = True And for retrieving the time data to json im using str(spcObject.expedition_time) I need to use str parsing cause in another way, Django will tell me that datatime is not JSON serializable -
Django 'migrate' command suggesting errors related to packages
I am new to Django and python and am presently taking a course on full stack web development, after following the course exactly the way it shows I have typed the following code within the models.py file: from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() def __str__(self): return str(self.date) And have tried to execute the command: python manage.py migrate The following is the error I get when calling this command: Traceback (most recent call last): File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 22, in <module> main() File "C:\Users\Naseem\desktop\my_django_stuff\first_project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\Naseem\anaconda3\envs\MyDjangoEnv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked -
Does Django Rest Framework stores data in binary format when we serialise it, if yes then how do we exclude particular fields from serializing?
I want to exclude some fields from serializing but as I do so, the endpoint won't allow me to take an input for it, is there a roundabout for this query? -
Django: using __str__ with a foreignkey in order to return an item
I am simply trying to override the str method to return something from a foreign key. A snippet of my models is as follows: class Product(models.Model): name = models.CharField(max_length=120) shortened_name = models.CharField(max_length=50) date_of_creation = models.CharField(max_length=20, null=True) history = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) style = models.CharField(max_length=50) artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images', null=True) slug = models.SlugField() def get_absolute_url(self): return reverse('product', args=[self.slug]) def save(self, *args, **kwargs): self.slug = slugify(self.shortened_name) super().save(*args, **kwargs) def get_add_to_cart_url(self): return reverse('add_to_cart', kwargs={ 'slug': self.slug }) class ShoppingCartOrderItem(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return self.product.name After adding the item to my shopping cart, in the admin panel when trying to view the specific item I get an AttributeError: 'ShoppingCartOrderItem' object has no attribute 'product'. Based on my googling so far I don't see why this isn't working. I have even tried str(self.product.name) but still the same error produces. I am unsure what I am doing wrong. Any help or suggestions is greatly appreciated! -
why django field form doesn't save fields from ajax query?
I have ajax query to fields django form. But when I try to save it - it is got me error "Make the right choice" This is my code: views.py class CountryCreateView(CountryViewMixin, core.CreateView): permission_classes = [IsAdmin] form_class = CountryForm template_name = 'country/create.html' success_url = reverse_lazy('countries:country-list') I have forms.py with fields: class CountryForm(core.ModelForm): class Meta: model = Country fields = ( 'name', 'latitude', 'longitude', 'area', 'region', 'settlement', 'district', ) def __init__(self, *args, **kwargs): super(CountryForm, self).__init__(*args, **kwargs) self.fields['area'].queryset = World.objects.all() self.fields['region'].queryset = World.objects.none() # self.fields['region'].widget.attrs['disabled'] = True self.fields['settlement'].queryset = World.objects.none() # self.fields['settlement'].widget.attrs['disabled'] = True self.fields['district'].queryset = World.objects.none() # self.fields['district'].widget.attrs['disabled'] = True and AJAX QUERY on 4 fields, which are serializing from the model World(I think that is a problem) world.js import $ from 'jquery'; import { choicesRegistry } from './choices'; $(() => { const $area = $('#id_area'); const $region = $('#id_region'); const $settlement = $('#id_settlement'); const $district = $('#id_district'); const area_choices = choicesRegistry['id_area']; const region_choices = choicesRegistry['id_region']; const settlement_choices = choicesRegistry['id_settlement']; const district_choices = choicesRegistry['id_district']; var $crf_token = $('[name="csrfmiddlewaretoken"]').attr('value'); region_choices.disable(); district_choices.disable(); settlement_choices.disable(); $area.on('change', function () { if(this.value === '') { region_choices.disable(); } else { $.ajax({ method: 'get', url: '/world', data: { level_1: this.value, level: 2, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: (data) => { …