Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) => { … -
what should I put in the views.py so that a specific user can add new complaints in a complaint management system
I have the model created for complaints. I tried a few methods to help a user create the complaint, but nothing works so I have given up and I just want to understand what to add in the views.py so that I can do that. The system basically has multiple users and I want the users to send in their complaints to the admin panel, so that they can be viewed, edited or deleted as per use on the dashboard. Right now my form does get created but it does not save the complaints in the admin panel. models.py: class Complaints(models.Model): user = models.ForeignKey(User, on_delete= CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.BooleanField(default=False) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title what to add in the views.py? I've tried various things but I don't know what to do to make it work. this if my views.py but I feel like the entire thing is wrong so I want an entirely new views: class ComplaintCreate(CreateView): model = Complaints form = ComplaintForm fields = '__all__' success_url = reverse_lazy('New') template_name = 'new.html' I want the final page to look like this: -
best practises for role based permissions using django groups
currently I am working on my first ever website and I have recently started tackling the RBAC permission system. The goal of my website is that companies will register on my website, their company owner will create groups that are unique to the company and effectively will act as job roles. The group model that the company owner can add/remove permissions and user to is from django.contrib.auth.models. This as an example means that companies can hide/remove access to certain components on the front end from the user. The current user then absorbs the permissions from the groups it is in, using get_all_permissions() I obtain the current user's active permissions and send this to the React frontend to only show specific components. Question 1, is this the right way to go about implementing method of hiding components from users? Question 2 is, what would be the best way to ensure that these permissions are actively followed on the views/models? I saw that DjangoModelPermissions only works where querySet() are used, but I have views where that isnt used at all. Such as: class CompanyView(viewsets.ViewSet): permission_classes = [permissions.AllowAny] def create(self, request): try: company_name = request.data['company_name'] company_orders = request.data['company_orders'] company_owner = request.data['company_owner'] company_owner_obj = … -
DRF: UpdateAPI > 'int' object has no attribute 'save'
I am trying to create an UpdateAPI to update my model. I need to comply with this API schema. I have tried the following: api.py class AlarmstichworteUpdateApi(ApiErrorsMixin, APIView): permission_classes = [IsAuthenticated] class InputSerializer(serializers.ModelSerializer): updated = serializers.DateTimeField() name = serializers.CharField(max_length=100) class Meta: model = AlarmstichworteConfig fields = ( '__all__' ) def put(self, request, id, *args, **kwargs): serializer = self.InputSerializer(data=request.data) serializer.is_valid(raise_exception=True) update_alarmstichwort(id=id, **serializer.validated_data) return Response(status=status.HTTP_200_OK) services.py def update_alarmstichwort( *, id: int, updated: datetime, name: str, ) -> AlarmstichworteConfig: alarmstichwort = alarmstichwort_by_id(id=id).update( name=name, updated=updated, ) # alarmstichwort.full_clean() alarmstichwort.save() return alarmstichwort selector.py def alarmstichwort_by_id(*, id, filters=None): return AlarmstichworteConfig.objects.filter(id=id) However, I have the problem that this does not work. When I do it this way, I get the error: File "D:\04-Dev\project\{...}\services.py", line 48, in update_alarmstichwort alarmstichwort.save() AttributeError: 'int' object has no attribute 'save' Can you help me or tell me what the error is? Thank you in advance. -
Testing django geoodel with PointField results in TypeError
I have the following model: from django.contrib.gis.db import models as geo_model class UserAddress(geo_model.Model): user = geo_model.OneToOneField( User, on_delete=models.CASCADE, related_name="user_address" ) coordinates = geo_model.PointField() address = geo_model.CharField(max_length=255) city = geo_model.CharField(max_length=20) country = geo_model.CharField(max_length=20) def __str__(self): return self.name Now, I am trying to unit-test this model with pytest: @pytest.mark.django_db class test_seeker_address(): seeker_address = SeekerAddress( seeker=Seeker(), address="my address", city="Oran", country="Algeria", coordinates=(7.15, 35.0) ) seeker_address.save() But, this is resulting in the following error: TypeError: Cannot set SeekerAddress SpatialProxy (POINT) with value of type: <class 'tuple'> How should I pass datatype in coordinates? -
This backend doesn't support absolute paths
I have django website deployed on heroku and using aws s3. When i login into admin page i get this message This backend doesn't support absolute paths enter image description here -
serializer for the nested Json in Django
I have the following JSON. which I get from the api and i want to write a serializer for this JSON in Django, someone has any idea how to write it, I just wrote it down but it gives me "error invalid data or expected directory and got a list "etc. anyhelp will be highly appreciated { "artikelNr1": 254160, "groessenCode": 6, "groessen": [ { "artikelNr1": 254160, "artikelNr2": 0, "artikelGr": 3, "groessenText": "EU36", "sku": "254160.00.03", "istZl": 1, "verkPeriode": -1 }, { "artikelNr1": 254160, "artikelNr2": 0, "artikelGr": 4, "groessenText": "EU37", "sku": "254160.00.04", "istZl": 2, "verkPeriode": -4 }, ], "zlQty": 7, "productId": 152060, "published": true, "categories": [ { "categoryRoots": [ { "id": 1, "name": "Damen", "parentCategoryId": 0 }, { "id": 5, "name": "Schuhe", "parentCategoryId": 1 } ], "id": 128, "name": "Hohe Sandalen", "parentCategoryId": 67 } ], "productName": "Sandalen" } -
Django : link Twich and Discord in user profile after Steam login
I am very new in Django. Recently I am developing a project with django , in this project I implemented social login with steam by the help of social-auth-app-django,a django package. It successfully login and redirects to profile, but now I want to link twich and discord in profile, so that I can store twich user name and discord username related to specific steam account . please tell me how can I implement it . Help will be highly appreciated !! Screen shot of profile page -
How to Count on annotated field that is concatenated in Django
I need help figuring out how to Count an annotated field (farm_key in this case) that is a concatenation of multiple fields. My Query is as follows staff_visits = FMS.Userdetails.objects.using('fmslegacy').filter( Q(userid__userrole__roleid__in=(3, 6, 7, 8)), Q(FieldVisitDetails_by_userid__createdon__gte=todaydate) ).order_by('userid').annotate( name=Concat(F('firstname'),Value(' '),F('lastname')), role=F('userid__userrole__roleid__role'), farm_key=Concat(F('FieldVisitDetails_by_userid__farmercode'), Value('_'), F('FieldVisitDetails_by_userid__landid'), Value('_'), F('FieldVisitDetails_by_userid__visitno'), output_field=CharField()), ).values('name', 'userid', 'role', 'farm_key').annotate(farm_visits=Count('farm_key', distinct=True)) but it gives the following error, ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'UserDetails.FirstName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. (8120) (SQLExecDirectW)") Here is a glimpse of the output that is currently working (except for the count of farm key part) { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011021_41636_3" }, { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011031_55858_1" }, { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011036_51460_2" }, { "userid": 173, "name": "Shiva Rama", "role": "Field Assistant", "farm_key": "1125011042_55850_2" }, My goal is to replace farm_key with count of distinct farm_keys for each User object. in this case it will be one user with 4 as count of farm_keys. I have tried adding a property method to the model, but apparently that doesnt work … -
Best way to get date information from web-scraped CSV (Django)
I would like to scrape CSVs containing satellite data that is produced daily into a Django database, including the date information. However, from what I can tell the only place that has the date info is in the filename, and on the website download page, as in the date isn't in the CSV itself. What is the best way to read the date information into the database? If relevant, the database I'm interested in is the VIIRS nightfire data from Earth Observation Group. Thank you! -
Django primary key issue
I have a current model in Django app like below class BasicInfo(models.Model): review_id = models.IntegerField(primary_key=True) owner = models.CharField(max_length=100, null=True, blank=True) I want to add one more column named sever and want to make review_id + server a composite key class BasicInfo(models.Model): id = models.AutoField(primary_key=True) review_id = models.IntegerField(null=False, blank=False) server = models.IntegerField(default=1) owner = models.CharField(max_length=100, null=True, blank=True) class Meta: unique_together = (('review_id', 'server'),) when I am trying to apply the migrations I am getting this error **$ python manage.py makemigrations review You are trying to add a non-nullable field 'id' to basicinfo without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option:** I have also tried to add a default value as 1 in the 'id' field but that doesn't work. Is there any way to overcome this issue? -
Django-Select2 doesn't work with many-to-many through fields
I have 3 models: Person, Company and they have many-to-many relationship through the Membership model with through fields When I create form for Person creation you have a possibility to add many Companies for this Person. But I wanna create autocomplete field (not just ModelChoiceField) when adding Company for Person. I go through the Django-Select2 tutorial, but widget displayed like this: Here is my form: class CompanyWidget(s2forms.ModelSelect2Widget): search_fields = [ "company_name__icontains", ] class MembershipForm(forms.ModelForm): person = forms.ModelMultipleChoiceField( queryset=Person.objects.all(), widget=forms.CheckboxSelectMultiple, help_text='Add existing persons from this company', required=False) # company = forms.ModelChoiceField( # queryset=Company.objects.all().order_by('company_name'), # required=False, # ) date_joined = forms.DateField() date_leaved = forms.DateField() class Meta: model = Membership fields = '__all__' widgets = { "company": CompanyWidget, } -
how to make Django recognize javascript variables and don't raise: VariableDoesNotExist?
I created a custom filter for the Django template and now I need to make filtering by queryset in Django like so: @register.filter def get_data(value, arg): return [value.get(id=arg).error_type, value.get(id=arg).student.student] now by this query, I need to show it when the user hovering one of images but of course, this filter use id to get the specific data filter so, I get this id from dataset attribute from HTML so, the code will look like that now in script: <script> elem_hovers.hover(function () { let data_pk = $(this).data('pk'); console.log(data_pk); // will return correct id number console.log("{{ resp|get_data:data_pk|safe }}") // variable does not exist }) </script> in the last line above will raise the next error: variable does not exist however, if I used the real number which is not coming from a variable which is: 12219 and that is the id number and I used it like so: console.log("{{ resp|get_data:12219|safe }}") then I will get an expected result from filter. so the general question now how can I make Django recognize the javascript variable dynamically without any error occurs? -
Celery worker broadcast thread doesn't have os.cwd()?
I broadcast a command to all celery workers with: app.control.broadcast("run_check") in run_check on the worker, I have: print(f"cwd: {os.getcwd()}") And I get the error: File "/execute/workerTasks.py", line 401, in run_check print(f"cwd: {os.getcwd()}") FileNotFoundError: [Errno 2] No such file or directory I'm a bit stuck - I need to use the filesystem (and I need to run curl and get the response) when my worker gets this command, but anything to do with the filesystem isn't working... what am I doing wrong?