Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PermissionError: [Errno 13] Permission denied: '/usr/bin/sudo' when collecting static files
I've been trying all day to deploy my django app to heroku but I keep running into issues with the collection of static files when I run python manage.py collectstatic I went through numerous threads on similar problems and my code matches the recommendations. However, I keep getting an error like this: PermissionError: [Errno 13] Permission denied: '/usr/bin/sudo' Static files part in my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static') ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') My folder structure - project_folder - folder1 - settings.py - wsgi.py - urls.py - folder2 - static folder - css folder - templates folder - views.py etc. - staticfiles manage.py How can I solve this issue? Nothing I tried so far works. -
Static folder in the wrong subdirectory
I am new to Django and I am trying to setup a static folder for my project. I am trying to place the static files in the following folder: /portfolio-project/portfolio/static I have made the following additions to settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'portfolio/static/'), ] STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATIC_URL = '/static/' However, after running 'collectstatic' the static folder is created in: /portfolio-project/ What am I doing wrong? Thanks in advance. -
Redirect Logged In users from authentication routes in Django 2
I'm following this guide to build a user authentication system using Django's built-in django.contrib.auth.urls Everything seems to work well, except that the already-logged-in users are still able to access authentication URLs like login, password_reset, etc. I searched for the solution and found out a solution that recommends using redirect_authenticated_user on individual class-based views. Another solution mentioned using request.user.is_authenticate on custom views. Is there a clean way of using it on with django.contrib.auth.urls without specifying individual class-based views? Something like this: urlpatterns = [ # Redirection is not working this way path('accounts/', include('django.contrib.auth.urls', {'redirect_authenticated_user': True})), ] All I need is that if a logged-in user tries to access any URL of django.contrib.auth.urls, he should be redirected automatically to some inner-page. Most of the solutions mention creating individual URLs to implement this redirection. Is there something I can apply collectively for django.contrib.auth.urls? -
Django CSRF verification failed on form validation after login with Ajax
My context, I fill my form, I have the possiblity to save the values in the database if I am log in. When I click on the Log in button, I open a bootstrap modal form to log in and I use Ajax/Jquery for the log in process. I understood that the CSRF token change after login, that's why when I validate my form (POST), I have the message: "Forbidden (403) CSRF verification failed. Request aborted." because I didn't refresh my page. What I can't figure out, is how can I refresh this token without loosing all the datas I already filled in my form? -
How to fix the GeoDjango Tutorial?
I'm trying to do the GeoDjango Tutorial using Sqlite as described here. When I call the load.py script it stops showing the error: Failed to save the feature (id: 206) into the model with the keyword arguments: {'fips': 'UK', 'iso2': 'GB', 'iso3': 'GBR', 'un': 826, 'name': 'United Kingdom' ... sqlite3.IntegrityError: NOT NULL constraint failed: world_worldborder.mpoly ... django.db.utils.IntegrityError: NOT NULL constraint failed: world_worldborder.mpoly Has anyone know this problem's cause? And a way to Django manage the geometry well importing all the data including 'United Kingdom' record? I'm using: Ubuntu 18.04 Python 3.6.8 Django==2.2.7 pkg-resources==0.0.0 pytz==2019.3 spatialite==0.0.3 sqlparse==0.3.0 libgeos-dev==3.6.2-1build2 binutils==2.30-21ubuntu1~18.04.2 libproj-dev==4.9.3-2 gdal-bin==2.2.3+dfsg-2 libgdal-dev==2.2.3+dfsg-2 python3-gdal==2.2.3+dfsg-2 -
How can we detect if new day as occured in Django?
I am creating a product page(10 products) in Django, wherein I need to add dummy views to each product and I need to make changes in dummyView every day for each product My question is how exactly I know that Day 1, Day 2 has occurred so I need to change Y and how exactly I can increase my views at some rate per minute? I need to update views as user refreshes page. I made a viewCount and dateuploaded(DateField) column for each product in my models.py. Help me completing newDayOccured() and increaseViews() My home function in views.py(shortened) is: def home(request): products = Products.objects.all() for product in products: delta=(datetime.date.today()-product.dateUploaded) N = delta.day if newDayOccured(): updateY_Array() DummyViewRatePerMinute = this_function_gives_me_DummyViewRatePerMinute() increaseViews(){ #change product.views at a rate of DummyViewPerMinute product.save() } return render(request, '../templates/home.html',{'Products':products}) -
How to put more info in django through model?
The purchaser bought one product type (including serveral products) each time from a supplier. I don't known how to add the procurement records in django admin, which including the bought date, the supplier name, the product type, the products name and their quantities. class ProductType(models.Model): product_type = models.CharField(max_length=50, unique=True, verbose_name="product type") class Product(models.Model): product_name = models.CharField(max_length=50, unique=True, verbose_name="product name") product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, verbose_name="product type") class ProductSupplier(models.Model): product_supplier = models.CharField(max_length=50, unique=True, verbose_name="product supplier") product_types = models.ManyToManyField(ProductType, through='BuyProducts') class BuyProducts(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) product_supplier = models.ForeignKey(ProductSupplier, on_delete=models.CASCADE) date_bought = models.DateField() I can add or edit the procurement records in django admin, which including the bought date, the supplier name and the product type. However, I cannot add or edit the products name and their quantities. Any suggestion is very welcome. -
How to add values to sqlite database in Django
I have a Django model as follows: from django.db import models class Vehicle(models.Model): reference = models.CharField(max_length=100, blank=False, null=False) make = models.CharField(max_length=100, blank=False, null=False) model = models.CharField(max_length=100, blank=False, null=False) And I want to add some data to db.sqlite3 file. I have simple function as follows: def get_vehicles(): try: fetched_vehicles = [.....] for vehicle in fetched_vehicles: n_vehicle = Vehicle() n_vehicle.reference = "123456", n_vehicle.make = "SKODA", n_vehicle.model = "Octavia SW", n_vehicle.save() return "Success" except Exception as e: print(str(e)) And when I execute this function in the database I see tuples instead of values as on the photo: Any idea? -
How to use Django model in an external python script within the project?
I want to use a Django model in an external python script. This python script is placed within the root directory of my project and I also created an init.py module for easy importing. Can anyone please instruct on what is the most secure and efficient way of importing a Django model into the python script? I would also appreciate it if someone could advise me whether or not it is accurate to place an init.py module within the root directory. If not, what is the best way of doing this? -
Test a redirect (and checking messages) in django
I have a view that redirect and I want to check for the messages. I found other questions like this and I read I should use follow=True. I'm a begginner so maybe I miss something but I'm not testing using client so I can't use follow (or anyway I don't know where to use it). So I have the doubt If I'm doing the things in the right way and if so how I can test the messagges. Here my code to test # my view def ImportName(request): if request.method == 'POST': # code else: messages.add_message(request, messages.ERROR, _('Form non valida.'), extra_tags='import_name') return redirect('lists:addname') # my test def test_importname(self): self.request = RequestFactory(spec=NameForm) # test a not POST call self.request.method = 'GET' self.request._messages = Mock() resposte = ImportName(self.request) resposte.client = Client() self.assertEqual(resposte.status_code, 302) self.assertRedirects(resposte, reverse('lists:addname')) Like you can see I need to definite the attributes _messages and .client so probabily there are better ways to do but I tested all my views like this (with RequestFactory()) and until I meet the message it worked fine. The response doesn't have a context, so I don't know where to check the messagges. Advices, opinions, solutions? Thank you -
How to filter by dare range in django-rest?
I'd like to filter my data by date range typed in browser, all other filtering are working. views.py class BookView(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializers filter_backends = [filters.SearchFilter] search_fields = ['title', 'language', 'authors', 'date'] -
My selection field is not getting populated
//I am rendering a page by sending a list of numbers from 0 to 99. I am trying to show it in a selection field but that dropdown is not showing anything. view.py I am rendering a page by sending a list of numbers from 0 to 99. I am trying to show it in a selection field but that dropdown is not showing anything. Below is the view function from which members is the list. def kitty_member1(request,code): url_name = request.resolver_match.url_name print(url_name) customers = customer.objects.all().distinct('mobile') kittys = kitty.objects.all() kittys = kittys.filter(code=code) for i in kittys: totalmembers = i.totalmembers members = [] for j in range(totalmembers): members.append(j) ctx = {'customer': customers, 'kitty': kittys, 'members':members} # return HttpResponse(ctx) return render(request, 'kitty_member/kitty_member.html',ctx) //Below is the template where i am not able to get the dropdown <div class="mb-3"> <select class="custom-select center-block" name="slot" id="slot" required > <option value="">Select slot</option> {% for j in members %} <option value="{{ j }}" > {{ j }} </option> {% endfor %} </select> <div class="invalid-feedback"> Please select a valid Slot. </div> </div> //There is no error but the dropdown is not showing any value. -
how to return json response contain Arabic word and encode it to be readable [duplicate]
This question already has an answer here: Creating UTF-8 JsonResponse in Django 4 answers how to return a json response contain Arabic word and make it readable not like this '\u062a\u0648\u0641\u064a\u0642' a=Staff_contracts.objects.all() list=[] for x in a: list.append({'project':x.ProjectName.Name,'employee':x.EmployeeName.ArabicName}) return JsonResponse(list,content_type="application/json",safe=False) -
How to add index to already built database on the server?
How do I add indexes to a database that is already created? I'm a newbie to MYSQL and built a DB without any indexes in Django that is really really slow. I'm trying to add indexes. The problem is that I need to filter by a foreign key Here is my Django code: #large db (Product) filtered by foreign key (another__id) Product.objects.filter(another__id='x') Should I put an index on the "id" in the another table or the "another" column in the product table? Do I create an index like this: CREATE INDEX "another" ON Product Since this is on the server, what kind of lock should I do? -
Not able to log in in Django Administation
After my improvement of the registration form on the site using the django-user-accounts module (I added a field with an e-mail address and sending confirmation letters), I could not log in django administation. Please enter a valid account username and password. Both fields can be case sensitive. I created a new superuser, I saw a message: Superuser created successfully. Then did the >python manage.py makemigrations Migrations for 'my_apps': my_apps\migrations\0003_group.py - Create model Group >python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, silk_bookmarks, sites Running migrations: Applying my_apps.0003_group... OK But the result remained the same. -
Celery beat_schedule using wrong timezone
I am trying to run a daily task as part of my Django web application using celery beat, which calls a function with a date string argument. The beat schedule works fine and calls the function at the right time each day, but the date string inputted to the function is always one day behind. I assume this is because the timezone setting is wrong, but I think I have configured Django and celery correctly so I can't see where the problem is. Relevant settings in ./settings.py: TIME_ZONE = 'Europe/London' USE_TZ = True CELERY_ENABLE_UTC = False CELERY_TIMEZONE = TIME_ZONE My celery config in ./my_project/celery.py: from django.utils import timezone from celery import Celery from celery.schedules import crontab app = Celery('my_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # Configure daily tasks app.conf.beat_schedule = { # Executes `my_task` every day at 10:00am 'do-my-task': { 'task': 'tasks.tasks.my_task', 'schedule': crontab(minute=0, hour=10), 'args': (timezone.now().strftime('%d/%m/%Y'), ), }, } Any ideas why this should be inputting the wrong date string as the argument to my_task? -
Django: list index out of range
I have the following MultilingualQuerySet: super_guest = self.request.event.surveys.get_super_guests() Out of this, I filter a variable that I return as a context variable. (There are several different context variables.) context["reason_for_attending"] = list(filter( lambda question: question.focus == QuestionFocus.REASON_FOR_ATTENDING, super_guest ))[0] Now it all works great as long there is an entry in the database. However, it can happen, that there are no "responses" yet. Then I get a list index out of range error. The reason is the [0]. Here my current solution. However, I feel like it is over-engineered. Do you have a more simple solution? context["reason_for_attending"] = next(iter(list( filter( lambda question: question.focus == QuestionFocus.REASON_FOR_ATTENDING, super_guest, ), None) )) -
DRF validator doesn't return false on uniqueness check
I have a user serializer in DRF that looks like this: class UserSerializer(serializers.ModelSerializer): class Meta: # password should exist only if POST model = User fields = ['first_name', 'last_name', 'password', 'email', 'username'] write_only_fields = ['password'] And this is what it looks like when I checked the shell. UserSerializer(): first_name = CharField(allow_blank=True, max_length=30, required=False) last_name = CharField(allow_blank=True, max_length=150, required=False) password = CharField(max_length=128) email = EmailField(allow_blank=True, label='Email address', max_length=254, required=False) username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>]) In my view if I check is_valid() on a serializer with data that already exists in the database, the function returns True when it should return False and then a django error is raised: django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=(myrandomusername) already exists. Why is this happening? -
Django: URL to specific request method
I'm working with Django and I'M using class-based views with urls. So, in mu classes I have the methods: post, get, put and delete. Example: class MyClassView(View): def get(self, request, id=None): return HttpResponse('GET request') def post(self, request): return HttpResponse('POST request') def put(self, request, id): return HttpResponse('PUT request') def delete(self, request, id): return HttpResponse('DELETE request') So in my URLs i have something like: from django.urls import path from . import views urlpatterns =[ path('my-class/', views.MyClassView.as_view()), path('my-class/<int:id>/', views.MyClassView.as_view()), path('my-class/create/', views.MyClassView.as_view()), path('my-class/update/<int:id>/', views.MyClassView.as_view()), path('my-class/delete/<int:id>/', views.MyClassView.as_view()), ] This works fine! When I send a GET request to /my-class I get "GET request" and when a I send a POST request to /my-class/create I get "POST request" the same for others URLs. The problem is, when I send a POST request to /my-class/ I get "POST request" and when I send a GET request to /my-class/creare I get "GET request" I need the URL to work only for a specific request method. That is, url /my-class/create should only work for the POST method, url /my-class/update should only work for the PUT method and so on. How can I do this? I've researched a lot, in the documentation and even right here but found no solution. -
How to overwrite validation in Django Rest Framework Serializer?
In Django Rest Framework I've got a Serializer. I receive some data, of which one called categories is an array of strings: { "name": "John", "age": 25, "categories": ["ADC", "HJD", "RTP"] } I want to serialize the array into a comma separated string ("ADC,HJD,RTP") so that I can put it in a CharField. So I created a validate_categories() method in my Serializer as follows: class DeviceSerializer(HALSerializer): # here some other stuff categories = serializers.SerializerMethodField() class Meta: model = Device fields = ( '_links', 'id', 'name', 'age', 'categories', ) def get_categories(self, obj): if obj.categories is None: return [] return [ obj.categories.choices[key.upper()] for key in obj.categories ] def validate_categories(self, categories): print("IN THE VALIDATOR") # WE NEVER REACH THIS POINT print(categories) return categories def create(self, validated_data): # here some custom creation code device = Device.objects.create(**validated_data) return device When I post the JSON the object is created but the validator never gets called. Does anybody know what I'm doing wrong here? -
Show data from related tables (Django)
Here is my ApiRest Project: Model.py class Movimientos(models.Model): Id = models.AutoField(primary_key=True) Total = models.IntegerField() Modo_Stock = models.IntegerField() Modo_Ventas = models.IntegerField() Fecha = models.DateField() Hora = models.CharField(max_length=60) Cantidad = models.IntegerField() Importe = models.IntegerField() Descripcion = models.CharField(max_length=255) Prod = models.ManyToManyField(Productos) # Caja = models.ForeignKey(Cajas, on_delete=models.CASCADE) class Meta: ordering = ('Fecha',) Serializers class ProductosSerializer(serializers.ModelSerializer): class Meta: model = Productos fields = '__all__' class MovimientosSerializer(serializers.ModelSerializer): Prod = ProductosSerializer(many=True) class Meta: model = Movimientos fields = '__all__' def create(self, validated_data): Prod_data = validated_data.pop('Prod') mov = Movimientos.objects.create(**validated_data) for pro_data in Prod_data: Productos.objects.create(mov=mov, **pro_data) return mov And the: Views - Urls POST - Error I want to show the json like the documentation, but i can´t do the POST. I think is the .create() function what is causing problems. -
Django: Filter for specific object
The type of questions_and_answers is <class 'modeltrans.manager.MultilingualQuerySet'>. I wrote the following code and wonder if there is a better/shorter way. I was looking into this here: filtered_dict = {k: v for k, v in questions_and_answers.items() if v.focus == QuestionFocus.FEELING_ABOUT_ATTENDING_AGAIN} but I always get back 'MultilingualQuerySet' object has no attribute 'items' questions_and_answers = self.request.event.surveys.get_results(settings.SURVEY_POST_EVENT) for question in questions_and_answers: if question.focus == QuestionFocus.FEELING_ABOUT_ATTENDING_AGAIN: context["feeling_about_attending_again"] = question -
Can't update Django ArrayField
I have a class in my model.py as class Views(models.Model): X = ArrayField(models.IntegerField(blank = True)) Y = ArrayField(models.DecimalField(blank = True,max_digits=2, decimal_places=2)) I entered the default value of X and Y as [0,0,0,0,0,0,0,0,0,0]. But when I try to update the value of X or Y array, it doesn't really get updated. shell commands are: >>> from productsHome.models import Views >>> x = Views.objects.all() >>> x <QuerySet [<Views: Views object (5)>]> >>> x[0] <Views: Views object (5)> >>> x[0].X [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> x[0].X = [1,2,2,1] >>> x[0].X [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> Why isn't my x[0].X is getting updated? -
custom OTP Login in Django
I have been doing some research but so far could not find a package that work only with OTP and no password auth. So I have trying to write using native javascript and python. I am creating two forms getotp and login that have Auth and Login buttons respectively and will plans to handle sending out OTP and checking if OTP is valid below otplogin.html <div id="otplogin"> <form class="form-horizontal" id="getotp" > {% csrf_token %} <div class="control-group"> <label class="control-label" for="username">Username</label> <div class="controls"> <input type="text" id="username" name="username" placeholder="Username"> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" name='auth' class="btn">Auth</button> <!-- <input onclick="this.form.submited=this.value;" type="submit" value="Auth" /> --> </div> </div> </form> <form class="form-horizontal" id="login" > <div class="control-group"> <label class="control-label" for="otp">OTP</label> <div class="controls"> <input type="otp" name="otp" id="otp" placeholder="OTP"> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" name='login' class="btn">Login</button> <!-- <input onclick="this.form.submited=this.value;" type="submit" value="Login" /> --> </div> </div> </form> </div> <script> $(document).on('submit','#getotp',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/getotp2', data:{ username:$('#username').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, })}); </script> views.py def getotp2(request): logout(request) username = otp = '' if request.POST: username = request.POST['username'] otp = pyotp.TOTP('base32secret3232').now() OTPEmail('You Auth',username,[],'Your auth is '+otp) print ('POST'+username) print ('POST'+otp) return JsonResponse(json.dumps({'username':username,'otp':otp})) def otplogin(request): if request.POST: otpentered=request.POST['otp'] if otpentered==otp: return redirect('/test3') return render(request,'esearch/otplogin.html') But I get directed to … -
Django nested list from two related tables
I have two models in Django models.py with one-to-many relationship: class Parcel(models.Model): farmer = models.CharField(max_length=200) name = models.CharField(max_length=200) area = models.FloatField() class Crop(models.Model): parcel = ForeignKey(Parcel, on_delete=models.CASCADE) code = models.CharField(max_length=20) date_planted = models.DateTimeField() date_harvested = models.DateTimeField() On one parcel, there are multiple crops planted over multiple years. Crop is related to Parcel via ForeignKey. Now, I need to display a nested list of all parcels and crops from a selected farmer, something like: [{ name: "parcel one", area: 22.2, crops: [{"code": "wheat", planted: "2017-01-01", harvested: "2018-09-12"}, {"code": "maize", planted: "2019-04-03", harvested: "2019-09-09"}] }, { name: "parcel two", area: 11.7, crops: [{"code": "wheat", planted: "2017-01-01", harvested: "2018-09-12"}, {"code": "maize", planted: "2019-04-03", harvested: "2019-09-09"}, {"code": "wheat", planted: "2019-09-19", harvested: None}] }] Right now I am using the following loop to retrieve a list of all parcels and crops for a selected farmer: from django.forms.models import model_to_dict from .models import Parcel from .models import Crop parcel_queryset = Parcel.objects.filter(farmer="John Smith") filtered_parcel_list = [] for parcel in parcel_queryset: parcel_dict = model_to_dict(parcel) parcel_dict["crops"] = list(parcel.crop_set.all().values()) filtered_parcel_list.append(parcel_dict) However, my query seems to be rather slow if there are many parcels. I suspect that Django is sending a new query to the database with each parcel.crop_set.all().values() statement in …