Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"detail": "method \delete\ not allowed" django
I made a view that can use put, delete request using modelviewset and mapped it with url. I have clearly made it possible to request put and delete request to url, but if you send delete request to url, I return 405 error. What's wrong with my code? Here's my code. views.py class UpdateDeletePostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated, IsOwner] queryset = Post.objects.all() def update (self, request, *args, **kwargs) : super().update(request, *args, **kwargs) return Response({'success': '게시물이 수정 되었습니다.'}, status=200) def destroy (self, request, *args, **kwargs) : super().destroy(request, *args, **kwargs) return Response({'success': '게시물이 삭제 되었습니다.'}, status=200) feed\urls.py path('post/<int:pk>', UpdateDeletePostView.as_view({'put': 'update', 'delete': 'destroy'})), server\urls.py path('feed/', include('feed.urls')), and error "detail": "method \delete\ not allowed" -
Hwo to structure css files in django python?
for better overview I created subfolders in the static folder of my django project with css files for each page like this: static --- landing_page -------landing_page.css -------landing_page_mobile.csss If I want to use all the css files I need to import a lot of files in the base.html file like: <link rel="stylesheet" href="{% static '/css/global.css' %}"> <link rel="stylesheet" href="{% static '/css/landing_page/landing_page.css'%}"> <link rel="stylesheet" href="{% static '/css/main_page/main_page.css'%}"> <link rel="stylesheet" href="{% static '/css/landing_page/landing_page_mobile.css'%}"> Is there any other way to keep the css structured without the need of 1000 imports in the base.html ? How are you structuring your projects ? -
gunicorn <HaltServer 'Worker failed to boot.'
I have read the posts with similar tittles and nothing seem to solve my issue. We are running a django app with gunicorn, supervisor and nginx for a few months now without any problems. This morning, out of the nowhere (I repeat out of nowhere!), I get a 502 bad gateway error when trying to access any page of the site. after looking into it, I found that gunicorn was at fault, as shown in this gunicorn.err.log Traceback (most recent call last): File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 209, in run self.sleep() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 357, in sleep ready = select.select([self.PIPE[0]], [], [], 1.0) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/exo/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/app/base.py", line 228, in run super().run() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 229, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 342, in halt self.stop() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop time.sleep(0.1) File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld self.reap_workers() File "/home/ubuntu/exo/lib/python3.6/site-packages/gunicorn/arbiter.py", line … -
Django redirection to specific view only in multi user app
I have an app that have different user roles. I want the user to access only the urls specified in his view only and unable to access others. For example: view1.py a.function1 b.function2 view2.py a. functionA b. functionB I want the user who access all the function in view1.py not to access the function in view2.py. when try to access them the system should redirect to its home page. Note that I am using Function Based View. And idea please -
deploying Vue.js and Django api (DRF) using Nginx
I am trying to deploy a Vue app and a Django REST api using Nginx and uwsgi. I am having issues setting up the reverse proxy in Nginx to route all traffic sent to mysite.com/api to the Django app. I am getting 404 error when I try to access the api and I am also unable to access the Django admin site. Here is my docker-compose file and Nginx config. version: "3" services: web: stdin_open: true tty: true build: context: . volumes: - ./app:/app command: bash -c " python manage.py makemigrations && python manage.py migrate && uwsgi --socket :8000 --master --enable-threads --module settings.wsgi" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db restart: on-failure db: image: postgis/postgis environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword restart: on-failure proxy: build: context: ./nginx ports: - "80:80" depends_on: - web volumes: static_data: Here is the Nginx config file: server { listen 80; location / { root /usr/share/nginx/html; try_files $uri /index.html; } location ^~ /api/ { uwsgi_pass web:8000; include /etc/nginx/uwsgi_params; } } -
How to set the url while passing array from jquery to python function?
How can I pass a parameter from jquery to python method? JQUERY const fruits = ['Apple', 'Mango', 'Orange', 'Grapes'] function sendfruitstoPython() { $.ajax({ url: 'Getfruits', type: "POST", data: { Fruit : fruits } , success: callbackFunc }); function callbackFunc(response) { console.log("demo"); } } PYTHON def Getfruits(request): demo = request.GET.getlist('Fruit') print("this is ", demo) OUTPUT this is [] URL PATTERN : path('Getfruits', views.Getfruits, name='Getfruits') It tried this as well... JQUERY function sendfruitstoPython() { $.ajax({ url: 'Getfruits'+ fruits , type: "POST", success: callbackFunc }); PYTHON def def Getfruits(request, fruits : demo = request.POST.getlist('fruits') print("this is ", demo) URL PATTERN path(r'^Getfruits/(?P<Fruit>\w+)/$', views.Getfruits, name='Fruit'), It gives me error he current path, Extractor/Getfruits[object set] , didn't match any of these. -
Unable to install r package inside django docker container
I'm developing a web service by cookie-cutter django For some reason, I have to call R-script to response user requests. So, at first, I tried to add a R's Dockerfile into local.yml. (in the last section) version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile image: webservice_local_django container_name: django depends_on: - postgres - mailhog volumes: - .:/app:z env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: webservice_production_postgres container_name: postgres volumes: - local_postgres_data:/var/lib/postgresql/data:Z - local_postgres_data_backups:/backups:z env_file: - ./.envs/.local/.postgres docs: image: webservice_local_docs container_name: docs build: context: . dockerfile: ./compose/local/docs/Dockerfile env_file: - ./.envs/.local/.django volumes: - ./docs:/docs:z - ./config:/app/config:z - ./webservice:/app/webservice:z ports: - "7000:7000" mailhog: image: mailhog/mailhog:v1.0.0 container_name: mailhog ports: - "8025:8025" redis: image: redis:5.0 container_name: redis celeryworker: <<: *django image: webservice_local_celeryworker container_name: celeryworker depends_on: - redis - postgres - mailhog ports: [] command: /start-celeryworker celerybeat: <<: *django image: webservice_local_celerybeat container_name: celerybeat depends_on: - redis - postgres - mailhog ports: [] command: /start-celerybeat flower: <<: *django image: webservice_local_flower container_name: flower ports: - "5555:5555" command: /start-flower R: image: r_local container_name: r_local build: context: . dockerfile: ./compose/local/R/Dockerfile And here is the ./compose/local/R/Dockerfile FROM r-base WORKDIR /app ADD . /app RUN Rscript -e … -
Serve TLS certificate dynamically per Django view instead of via nginx/gunicorn
I'm using Django's request.get_host() in the view code to differentiate between a dynamic number of domains. For example, if a request comes from www.domaina.com, that domain is looked up in a table and content related to it is returned. I'm running certbot programmatically to generate the LetsEncrypt certificate (including acme challenge via Django). I store the cert files as base64 strings in PostgreSQL. That works perfectly fine, but I can't figure out how to 'apply' the certificate on a dynamic per-domain basis. I know that this is normally done using TLS termination, nginx or even in gunicorn. But that's not dynamic enough for my use-case. The same goes for wildcard or SAN certificates (not dynamic enough) So the question is: Given I have valid LetsEncrypt certs, can I use them to secure Django views at runtime? -
How to do location based query with simple Django filter?
I've saved user's coordinates in the User model. Post model has latitude, longitude and radius field. Only the users in that vicinity(of Post) will be able to see that post. I don't know how to use filter() here so I used the following approach: post=Posts.objects.all() for a in post: distance= geopy.distance.geodesic((lat1,lng1), (a.latitude, a.longitude)).km print(distance) if distance < a.radius: p.append(a) else: continue Here, lat1 and lng1 are the coordinates of current User. Suggest if there is any better way as this seems very inefficient. -
Annotate with django: send form with ajax, render div with new item and restart
I want to create a simple annotation web app, where I want the user to see one item, annotate with a simple radio form, submit the form, see the next item, annotate, and so on. I'm using Django but I'm not able to make it work. The problem is that it works with first submission but with the second one gives the error: Forbidden (403) CSRF verification failed. Request aborted. This is what I have for testing: An app called anotar with the following urls.py: app_name = 'anotar' urlpatterns = [ path('',views.dashboard,name = 'dashboard'), ] in views.py: def dashboard(request): template = 'anotar/dashboard.html' tweet_id = '1323646485200850945' if request.is_ajax(): print("AJAX") # I will save the anotation here and pass the another id for new anotation template = 'anotar/tweet.html' tweet_id = '1324423455002005505' html = render_to_string(template,{'tweet_id':tweet_id}) return JsonResponse({'html':html},safe=False) return render(request, template, {'tweet_id':tweet_id}) Then, the dashboard.html: {% extends 'base.html' %} {% load static %} <div id="teste-include"> {% include "anotar/tweet.html" %} </div> {% block domready %} $('#post-form').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check save_anotation(); }); function save_anotation() { console.log("create post is working!") // sanity check console.log($('.form-check-input:checked').val()) $.ajax({ url :'{% url "anotar:dashboard" %}', // the endpoint type : "POST", // http method data : { option … -
Django multiple boolean fields on ForeignKey model in form as checkboxes
I have a Django app that has the following models: class ProductNotification(models.Model): question_asked = models.BooleanField(default=False, help_text='Receive messages when a question is added') question_delete = models.BooleanField(default=False, help_text='Receive messages when question is deleted') # There are more boolean fields in here class Product(models.Model): name = models.CharField(max_length=255, unique=True) #... product_notification = models.ForeignKey(ProductNotification, on_delete=models.CASCADE, default=True) Each Product should have its own notification setting. My forms: class ProductNotificationForm(forms.ModelForm): question_added = forms.BooleanField(help_text='Receive messages when question is added.', required=False) question_delete = forms.BooleanField(help_text='Receive messages when question is deleted.', required=False) # same fields to come as in the model class Meta: model = ProductNotification fields = ['question_added', 'question_delete', ...] class ProductForm(forms.ModelForm): name = forms.CharField(max_length=50, required=True) # ... product_notification = forms.ModelChoiceField(queryset=ProductNotification.objects.all(), required=False) The problem is: The form adds the new "sub form" product notifications, but instead of a bunch if checkboxes for all the boolean fields, there is only one drop-down menu. I have tried ModelMultipleChoiceField too, without success. Can someone help me to get all the checkboxes displayed instead of one drop-down menu? Thanks a lot :) -
Django - how to order queryset for varying query?
I have this issue where I want to order my queryset according to a compute value based on a query in descending order. Query: ?fruit=Apple&?fruit=Pear In this case: Num. Apples + Num. Pears + (Num. Apples * Num. Pears) models.py class Costumer(BaseModel): name = models.CharField('name'), max_length=255, blank=True fruits = models.JsonField('fruit'), null=True, blank=True, default=dict) My Costumer.fruits looks something like this: fruits = {name: Apple, count: 10}, {name: Pear, count:4}, {name: Cherry, count: 1}, {name: Avocado, count: 2} views.py def get_queryset(self): fruits = dict(self.request.GET).get('fruit', []) queryset = Costumers.objects.all() if fruits: queryset = sorted(queryset, reverse = True, key=lambda costumer: self.calculate_order(costumer, fruits)) return queryset def calculate_order(self, costumer, fruits): value_list = [fruit['count'] for fruit in costumer.fruits if fruit['name'] in fruits] return sum(value_list) + (reduce((lambda x, y: x*y), value_list)) if value_list else 0 This seems to be ordering the data correctly from what I have tested so far, however doesn't seem like the best way to do it. Is there a better way using Django Queryset API for ordering this data? Since the way it's ordering now is a bit time consuming since I have to iterate on all the records on the database. -
django - on model save method, determine if field value is set explicitly, or a default value is being used
With following model; class MyModel(models.Model): my_field = models.CharField(max_length=32, default='default_value') def __init__(self, *args, **kwargs): self.my_field is not None # True def save(self, *args, **kwargs): self.my_field is not None # True MyModel.objects.save(a=1, b=2) # Not setting my_field here Here, in the two methods above (or somewhere else), is there a way to determine of my_field value was set expliclitly, or the model is using the default value here? Checks return True when I don't set a value explicitly for the model field, and has 'default_value' value. -
How to override existing Permission model __str__ method() in django?
By default Permission model str method returns objects as '%s | %s' % (self.content_type, self.name).I want to display only self.name.Is there any way to do this? I tried this but it is not working. from django.contrib.auth.models import Permission class Permission(Permission): def __str__(self): return '%s' % (self.name) -
Exception in django: Query set have no attribute user
Here i am simply using User model from django.contrib.auth.models import User and I have a custom userprofile model where user foreign key in that django built in User model , well i have created an email_address field which can manually update by a user, and there is an other email field which is built in inside django User model , I want to update that email field as userprofile email_address field update. I am simply getting user object which username and try to get email of that user object but getting an error : 'QuerySet' object has no attribute 'email' models.py def save(self,*args, **kwargs): user_obj = User.objects.filter(username=self.user.username) print(user_obj,'user object') print(user_obj.email,'email have a user') email = self.email_address user_obj.email = self.email_address print(user_obj.email,'email have a user') user_obj.save(user_obj.email) super(UserProfile,self).save(*args, **kwargs) -
How to update a list of objects with checkboxes in Django
I have a page that displays a list of messages that each have a checkbox. I want to be able to select one or more of them and toggle their unread status. I have a Message model: class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) sender = models.ForeignKey(Profile, on_delete=models.CASCADE) message = models.TextField(blank=True) unread = models.BooleanField(default=True) And my messages.html looks like this: <ul> <li><a href="{% url 'users:read_message' %}">Mark as read</a></li> <li><a href="{% url 'users:unread_message' %}">Mark as unread</a></li> </ul> {% for msg in messages %} <input type="checkbox" name="message" value="{{ msg.id }}"> <p>{{ msg.message }}</p> {% endfor %} Here are my urls: path('read-message/', MessageRead.as_view(), name='read_message'), path('unread-message/', MessageUnRead.as_view(), name='unread_message'), What I am struggling with is how to pass the selected messages to the view. Here is what I have attempted so far: class MessageRead(UpdateView): model = Message template_name = 'users/messages.html' success_url = 'users/messages.html' def get_queryset(self): message = self.request.GET.getlist('message').values_list('pk', flat=True) message.update(unread=False) return message class MessageUnRead(UpdateView): model = Message template_name = 'users/messages.html' success_url = 'users/messages.html' def get_queryset(self): message = self.request.GET.getlist('message').values_list('pk', flat=True) message.update(unread=True) return message This brings up an AttributeError 'list' object has no attribute 'values_list' Can someone please explain what I'm doing wrong? -
Ho can I post an object data into Django test Client post request?
I'm writing a test to see if form data is validating on post request trying to create a Post object. Here is the code: def setUp(self): user = User.objects.create_user(email='test@gmail.com', password='test', name='test') Post.objects.create(user=user, body='hi') self.post = Post.objects.get(body='hi') self.user = User.objects.get(email='test@gmail.com') self.client.login(email=user.email, password=user.password) @tag('fast') def test_index(self): client = Client() response = client.get('/home/', {}, True) r = client.post(reverse('index'), data={'user': self.user, 'body': 'Test'}, follow=True) print(r, self.user) self.assertTrue(Post.objects.filter(body='Test').exists()) self.assertEqual(response.status_code, 200) but the test fails implying that the object with body "Test" was not created. I already tried encoding data with urlencode but it did not help. Here is what print statement shows: <TemplateResponse status_code=200, "text/html; charset=utf-8"> test -
Prevent unauthorized user from accessing PDF file
I have a web application that allows users to download PDF files. The users are supposed to login or register (if not already registered) and after verification of credentials are allowed to view or download PDFs. Hence, only authorized users are able to access the PDFs. My question is, is there a way in which I can prevent the authorized users from sharing the PDFs with other unauthorized users? I have read about password encryption, digital certificates and Digital Rights Management. I also know that we can hide the toolbar in the browser using embed tag and prevent users from downloading the files. I have also read so many posts saying that preventing users from sharing the PDFs after it has been downloaded is simply not possible. But I just wanna know if it is possible to somehow embed a key with the PDF when it is being downloaded and invoke a script (preferably Python) to verify the user, when the user tries to open the PDF? Any help will be appreciated. Thanks. -
Cannot update a module with pip due to file not found, and cannot delete said module with pip due to file not found
I have taken over a django website, and I need to update the django-fobi module. I cd into the main folder of the project I activate the venv with source ~/Projets/XYZ/venv-dfs/bin/activate I attempt an update with pip install django-fobi --upgrade I get the error : ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/me/Projets/XYZ/venv-dfs/lib/python3.8/site-packages/django_fobi-0.12.3.dist-info/RECORD So, instead of updating, I try to delete first, to then do a clean re-install, using pip uninstall django-fobi I get FileNotFoundError: [Errno 2] No such file or directory: '/home/me/Projets/XYZ/venv-dfs/lib/python3.8/site-packages/django_fobi-0.12.3.dist-info/RECORD' This is my first time working with venv and pip, is there a workaround for this? -
Django QuerySet API check if is unique for this id
This is how my model looks like: class Catalog(models.Model): global_id = models.IntegerField(unique=True) name = models.CharField(max_length=30) short_name = models.CharField(max_length=10) description = models.CharField(max_length=200, blank=True) version = models.CharField(max_length=10) class Meta: constraints = [ models.CheckConstraint( check=models.Q( // CHECK IF VERSION IS UNIQUE FOR THIS PARTICULAR GLOBAL_ID // ), name="%(app_label)s_%(class)s_unique_version", ) ] As you can see, I need to make sure that version models are unique for a particular global_id, I just don't know how. Help. -
I can't activate my virtual environment in pycharm
I just made a virtual environment but trying to open it with mypython\Scripts\activate Can anybody tell me why this is not working? The execution of the command -
django-import-export how to skip import some rows based on current user login?
Actually started using django-import-export latest version. Wanted to know where exactly we can override to skip certain rows of the csv from being imported based on current user or the domains from a list of domains he can import data from the csv. How exactly to customize which of the methods to override and how? In my ModelResource, I have created the list of domains for the current user, and which method of the import-export do I check this and skip the rows from being imported? class MailboxResource(resources.ModelResource): mdomain_list = [] def before_import(self, *args, **kwargs): # make changes to csv super(MailboxResource, self).before_import(*args, **kwargs) muser_id = kwargs['user'].id muser = kwargs['user'] # import for all domains if muser.is_superuser: pass # import for domains belonging to the hierarchy elif muser is not None: exist = muser.groups.filter(name='customers').exists() self.mdomain_list.append(Domain.objects.filter( customer__in=Customer.objects.filter( email=muser))) Hence customer should be able to import data from the CSV only for domains that belong to him and skip all other rows from the CSV, which don't exist in the list. CSV: id,name,email,domain, 1,ABC pvt.ltd,abc@zinn.com,zinn.com, 2,XTD,xtd@ggg.com,ggg.co.in, 3,RTG,tiger@goa.com,goa.com If customer doesn't own ggg.com domain, only 1st and 3rd row should get added to the table via import. How can this be achieved? Using python … -
Why the Data of Patient and Doctor are not registred in the database?
when I register the patient or the doctor on the registration platform (sign up),I don't know why the data of the Doctor and Patient are not registred in the database (MySQL)?, I need your helpe please. I have the following code in bas_app\views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import login, authenticate from .forms import MedForm, PatForm, ContactForm from .models import Patient, Médecin, User def accueil(request): return render(request, 'base_app/accueil.html') def inscription(request): if request.method == 'GET': dict_inscription_form = {'form': UserCreationForm()} return render(request, 'base_app/inscription.html', dict_inscription_form) else: # Creer un nouveau compte if request.POST['password1'] == request.POST['password2']: try: # Enregistrer ses données user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() # Se Connecter directement login(request, user) return render(request, 'base_app/apres-inscription.html') except IntegrityError: dict_form_error = {'form': UserCreationForm(), 'error': "Ce nom d'utilisateur existe déjà"} return render(request, 'base_app/inscription.html', dict_form_error) else: # Probléme dans le mot de passe dict_form_error = {'form': UserCreationForm(), 'error': 'Le mot de passe ne correspond pas'} return render(request, 'base_app/inscription.html', dict_form_error) # apres Connection page def apres_inscription(request): return render(request, 'base_app/apres-inscription.html') def apres_connection_medecin(request): return render(request, 'base_app/apres_connection_medecin') # se connecter def se_connecter(request): if request.method == 'GET': return render(request, 'base_app/connection.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['username'],first_name=request.POST['nom'],last_name=request.POST['prénom'],password=request.POST['password']) if … -
Setup Unity mobile app login using Django OAuth2
I built the backend for a Django REST API on mydomain.com and have set up email authorisation and OAuth2 for google and facebook. I am a newbie to Unity (and Django before setting it up). I have a Unity mobile app for iOS and Android(that I obv did not develop myself) that I need to connect to Django for authentication to create users on the app. I've seen this post, but being completely new to JSON and Unity I wouldn't know how to begin implementing anything mentioned. Are there any tutorials with guided steps? Could you provide me with some basic information? The documentation dives straight into the deep end but is still not informative enough for me to use it for oauth. Closest youtube video I've found is for a fitbit and I don't know how to apply anything form there to my case. Literally any help would be greatly appreciated! (please :(( ) -
Upload many images django rest framework
I try to upload many images to one post. I try to achive this: When I post data i get this: What is wrong with my code ?