Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to give access to only specific group of user for login - django
I'm struggling with login for users from specific django group , unfortunately any group user is able to login without knowing whether he belongs to a group or not. def loginstaff(request): if not request.user.is_authenticated: if request.method == "POST": fm= AuthenticationForm(request=request, data=request.POST) if fm.is_valid(): uname= fm.cleaned_data['username'] upass= fm.cleaned_data['password'] User = authenticate(username=uname,password=upass) if User is not None: login(request,User) messages.success(request,'Logged in Successfully..!') return HttpResponseRedirect('/staffprofile/') else: fm=AuthenticationForm() return render(request,'loginstaff.html',{'form':fm}) else: return HttpResponseRedirect('/staffprofile/') I created only two groups. help me with my code guys, but in brief:) bcz im just learning. thanks -
Zabo create_user api
I'm trying to use the Zabo rest api for create user which can be found here: https://zabo.com/docs/?shell#create-a-user The api says to do this (copied and pasted here): curl "https://api.zabo.com/sandbox-v1/users" \ -X POST \ -H "X-Zabo-Key: adminApiKey-established-in-dash" \ -H "X-Zabo-Sig: signature-of-request-using-paired-secret-key" \ -H "X-Zabo-Timestamp: 1420069800000" \ -d '{ "id": "8b0a037f-67cb-44b7-ac2a-18e7a54561a8", "token": "zabosession-abcdef1234567890" }' I'm doing this in Python: def _get_signature_and_time(self, url, body, secret): mtime = round(time.time() * 1000) json_body = json.dumps(body) logger.info(mtime) logger.info(url) logger.info(secret) logger.info(json_body) text_value = "%d%s%s" % (mtime, url, json_body) logger.info(text_value) signature = hmac.new(bytes(secret, "UTF-8"), bytes(text_value, "UTF-8"), hashlib.sha256).hexdigest() return signature, mtime I keep getting a different signature than what their library (currently only available in nodeJS) is providing. However, I'm doing it as per documentation. Is there something im missing here? -
Appending parameters to a form
Let's say I have the following: form = MyForm(request.POST or None, request.FILES or None, instance=instance) One the form variable has been established, how would I append the following to it initial = {'my_id': my_id} initial can't be added to the form declaration for various reasons that are specific to my project. THanks! -
django for professionals book
I am currently on page 241 of the "Django for professionals" book. Adding command gunicorn config.wsgi -b 0.0.0.0:8000 to docker-compose-prod.yml made it impossible to rebuild docker image with docker-compose up -d --build command, error is yaml.scanner.ScannerError appears : mapping values are not allowed here in ". \ docker-compose.yml", line 7, column 12. Is this a bug of the author of the book? version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn config.wsgi -b 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - "DJANGO_SECRET_KEY=ldBHq0YGYxBzaMJnLVOiNG7hruE8WKzGG2zGpYxoTNmphB0mdBo" db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: -
Django Model Field Inline
In Django, you can use inline to make new instances of models by just clicking the add instance button on the bottom of the admin site. Is there a way to do this for a model field inside a model. For example, if you were cataloging a book and you want to capture all the chapters in each books name. Every book has a different number of chapters so you could not just do chapter1 = CharField(max_length = 200) chapter2 = CharField(max_length = 200) and so on. Like the picture below but not for model instances for model fields. -
request.user.is_authenticated is false on certain HTML on certain pages but not in views
Most pages on this website I'm creating for practice {% if request.user.is_authenticated %} go through as true. But there is one page that always returns this as false (i've pasted that section of code below)... Even though in views.py the function that controls that page, show when I run print(request.user.is_authenticated) outputs: true html: {% extends "page0/layout.html" %} {% load static %} {% block body %} <h2>{{ listing.listingTitle }}</h2> {% ifequal listing.validURL listing.valid %} <img src="{{listing.picture}}" alt="picture!" style="width:150px"> {% else %} <img src="https://www.drupal.org/files/issues/2018-07-26/no%20thumbnail%20found%20suggestion.png" alt="no picture!" style="width:150px"> <p>NOTE: no image provided</p> {% endifequal %} <p>{{bidPrice}} $</p> {% if user.is_authenticated %} <form action="{% url 'bid' listing.listingTitle %}" method = "post"> {% csrf_token %} {{form2}} <input class="btn btn-primary" type="submit" value="button"> </form> {% else %} Not signed in. <a href = "\register">Sign in or create an account </a> {% endif %} </div> {% endblock %} views.py: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from markdown import Markdown from django.contrib.messages.api import success from django.contrib import messages import os.path from .models import User import datetime import time import validators import requests from django.http import HttpResponseBadRequest, HttpResponseRedirect, Http404 from django import forms … -
django custom template tag, pass multiple arguments
I need to be able to pass multiple parameters to a custom template tag. I dont know how to do it but I've seen an example like this somewhere. If you got the idea, is it possible to do it in some way? template {% for right in people_rights|user_available_rights:rooms, user.id %} {{right.room}} {% endfor %} template tag def user_available_rights(rights, rooms, user_id): available_rights = [] user_rooms = [] for right in rights: if right.user.id == user_id: user_rooms.append(right.room) for room in rooms: for ur in user_rooms: if room.id != ur.id: available_rights.append(room) return available_rights -
Adding parameters into formset declaration
I'm building a formset based on a few variables FormSet = eval("modelformset_factory(TemplateModel, form=%s, extra=extra, max_num=max_forms, can_delete=True)" % formname) I want to pass some perameters into this FormSet variable so that I can pick them up in my forms.py form_kwargs={'user': user} How would I add these forms_kwargs perameters into the first line of code? -
Whenever user signs up smtp authentication error is thrown in django
While signing in smtp error is thrown.I have On the less secure apps still the error is thrown Smtp Error on the Screen -
How to update folium map with javascript
I have a map generated by folium with python. The hml and JavaScrip code are in the snippet. I have added a drop down list. I would like to change the color of line when selecting 'Lanes (input)' value. For example here : all lines with number of lanes = 1 will be colored in green all lines with number of lanes = 2 will be color in blue etc How can I do that ? Here is the ouput generated by folium <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script> L_NO_TOUCH = false; L_DISABLE_3D = false; </script> <style>html, body {width: 100%;height: 100%;margin: 0;padding: 0;}</style> <style>#map {position:absolute;top:0;bottom:0;right:0;left:0;}</style> <script src="https://cdn.jsdelivr.net/npm/leaflet@1.6.0/dist/leaflet.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.6.0/dist/leaflet.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/python-visualization/folium/folium/templates/leaflet.awesome.rotate.min.css"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <style> #map_8a24bb442b2741ed8240d6265f6ae4a8 { position: relative; width: 100.0%; height: 100.0%; left: 0.0%; top: 0.0%; } </style> </head> <body> <div class="folium-map" id="map_8a24bb442b2741ed8240d6265f6ae4a8" ></div> </body> <script> var map_8a24bb442b2741ed8240d6265f6ae4a8 = L.map( "map_8a24bb442b2741ed8240d6265f6ae4a8", { center: [0, 0], crs: L.CRS.EPSG3857, zoom: 1, zoomControl: true, preferCanvas: true, } ); function geo_json_b105cf0f04474ba9b67fc8685c26a8ae_styler(feature) { switch(feature.id) { case "(1, 2)": case "(1, 3)": case "(1, 4)": case "(1, 5)": … -
How to add different domain to a URL path in django-rest-frame-work?
My endpoints and front end domain names are different. I've an email-verify endpoint which has a url https://test.com/email-verify?token=TOKEN. My front end url is https://trial.com. Currently, I'm sending an email to user with test url. I want to change it to https://trial.com/email-verify?token=TOKEN. I'm a bit stuck to come up with a way to do it. urls.py: from authentication import views from django.urls import path from rest_framework_simplejwt.views import ( TokenRefreshView, ) urlpatterns = [ ... path("email-verify", views.VerifyEmail.as_view(), name="email-verify"), ... ] view.py: ... class VerifyEmail(views.APIView): serializer_class = EmailVerificationSerializer token_param_config = openapi.Parameter( "token", in_=openapi.IN_QUERY, description="Description", type=openapi.TYPE_STRING, ) @swagger_auto_schema(manual_parameters=[token_param_config]) def get(self, request): token = request.GET.get("token") try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"]) user = User.objects.get(id=payload["user_id"]) if not user.email_verified: user.email_verified = True user.save() return response.Response( {"email": "Successfully activated"}, status=status.HTTP_200_OK ) except jwt.ExpiredSignatureError as identifier: return response.Response( {"error": "Activation Expired"}, status=status.HTTP_400_BAD_REQUEST ) except jwt.exceptions.DecodeError as identifier: return response.Response( {"error": "Invalid Token"}, status=status.HTTP_400_BAD_REQUEST ) ... -
Adding Nodejs to Django
I hope this post doesn't get removed for not being specific enough but I am trying to get regular barcodes read in a Django project and I am not finding a way to do it that matches my ability to implement it in the time that I have allotted. I see a lot of ways to do it using Nodejs and I really don't want to add another framework for just this one function but I am not seeing any other way to do it that has good browser support. My specific question is: is this a bad route to take or is it common practice to add another framework like this? -
Monkeypatch in a Django TestCase
I want to test a view which call an API and to do this, I need to use monkeypatch, but the method only take 1 positionnal argument : "self", what should I do ? (What I want to do should be pretty clear on my code) class SearchCompanyTestCase(TestCase): def setUp(self): user = User.objects.create_user('temporarySC', 'temporarySC@gmail.com', 'temporarySC') user_info = UserInfos.objects.create(user=user, address='address', latitude='45.7595253', longitude='45.7595253') test_rome_code = RomeCode.objects.create(code='ABC24') TradeToRomeCode.objects.create(job_name='test', job_code=test_rome_code) user_info.job_code = test_rome_code user = authenticate(username='temporarySC', password='temporarySC') def test_api_valid_token(self, monkeypatch): class Token: status_code = 200 content = json.dumps({ "access_token": "wehqh8238eg2q8ge8" }).encode() data = json.dumps({ "companies": [{ "distance": 2, "headcount_text": "6 à 9 salariés", "lat": 48.97609, "city": "PAGNY-SUR-MOSELLE", "naf": "4711D", "name": "LIDL", "naf_text": "Supermarchés", "lon": 5.99792, "siret": "34326262214546" }], "companies_count": 1}).encode() def mockreturnToken(request): return Token def mockreturnData(request): return data monkeypatch.setattr(requests, 'post', mockreturnToken) monkeypatch.setattr(requests, 'get', mockreturnData) response = self.client.post(reverse('main_platform:searchCompany')) self.assertEqual(response.context['companies'], [{'distance': 2, 'headcount_text': '6 à 9 salariés', 'lat': 48.97609, 'city': 'PAGNY-SUR-MOSELLE', 'naf': '4711D', 'name': 'LIDL', 'naf_text': 'Supermarchés', 'lon': 5.99792, 'siret': '34326262214546'}]) self.assertEqual(response.context['companies_count'], 1) -
Is it better to make separate django models, or add various foreign keys to one model?
I have a model to capture comments from a user, DocumentComment. The comments are tied to a particular document in the database, and created/edited/displayed on the page that displays that particular document: class DocumentComment(Model): """ Captures a user's comment about a document """ document_id = models.ForeignKey(Document, on_delete=models.CASCADE, verbose_name="document file name", related_name='document') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField('comment', blank=True) moderated = models.BooleanField(default=False) added_to_description = models.BooleanField(default=False) marked_for_deletion = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name="date created") updated = models.DateTimeField(auto_now=True, editable=False, verbose_name="last update") I now find I need to record comments based on other objects displayed on different pages in the site, e.g. albums (collections of document) is a page and word clouds (derived from all the words in various documents) is another page. Since these new comments are not tied to one document, but a collection of documents, I don't think they should be added to the DocumentComment model for every document_id in the collection. I wouldn't necessarily want the comments on a collection to be displayed on the page with one of the documents in that collection. Which approach is better (django-yy or pythonic or idiomatic or by whatever standard you choose): create separate models as above for each display object … -
Is it possible to recreate an app in django with only the migrations?
I have a set of Django migrations without the models of a Django app. Is it possible to recreate the models automatically with the migrations? -
Autofill my author field with foreign key
I am trying to autofill my user foreign key in my note project with authentication in django. I tried, but it's not working and asking that owner is required field. Please, help! Thanks in an advance. views.py @login_required(login_url='login') def index(request): tasks = Task.objects.filter(owner=request.user) form = TaskForm() if request.method=='POST': form = TaskForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.owner = request.user instance.save() context = { 'tasks':tasks, 'form':form, } return render(request, 'list.html',context) models.py class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.title -
What is _set.all() in Django?
I'm going through one Django tutorial and in the Serializer _set.all() was used and I can't seem to figure out what does it do exactly. Here is the code snippet for this serializer: class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = '__all__' class OrderSerializer(serializers.ModelSerializer): orders = serializers.SerializerMethodField(read_only=True) class Meta: model = Order fields = '__all__' def get_orders(self, obj): items = obj.orderitem_set.all() serializer = OrderItemSerializer(items, many=True) return serializer.data -
Problem with deleting cache in localized page
I have pages to view posts. Also I have header with option to switch language and when I switch language, it changes on all pages, except pages with cache. There language changes only when I reboot the server. I need to understand, how I can delete cache, when I change language. Views.py: class DetailPostView(generic.DetailView): def get(self, request, *args, **kwargs): pk = kwargs['pk'] post = Post.objects.get(pk=pk) comments = Comment.objects.filter(post=post) form = CommentForm() context = { "post": post, 'comments': comments, 'form': form, } return render(request, "detail_post.html", context) def post(self, request, pk): post = Post.objects.get(pk=pk) comments = Comment.objects.filter(post=post) form = CommentForm(request.POST) if form.is_valid(): author = self.check_user_authenticated(request, form) comment = Comment( author=author, body=form.cleaned_data['body'], image=form.cleaned_data['image'] if 'image' in form.cleaned_data else None, post=post, user=request.user if isinstance(request.user, User) else None ) comment.save() context = {'post': post, 'comments': comments, 'form': form} return render(request, "detail_post.html", context) def check_user_authenticated(self, request, form): if request.user.is_authenticated: author = request.user.profile.name elif form.cleaned_data['author']: author = form.cleaned_data['author'] else: author = 'Anonim' return author Models.py: class Post(models.Model): title = models.CharField(max_length=25) body = models.TextField() image = models.ImageField(blank=True, upload_to=post_directory_path) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts', blank=True) profile = models.ForeignKey('Profile', verbose_name='User', on_delete=models.CASCADE, related_name='profile') def __str__(self): return self.title @receiver(post_save, sender=Post, dispatch_uid="clear_cache_post") def update_post(sender, **kwargs): key = make_template_fragment_key('post', … -
Celery Worker Not Running Tasks When Scheduled(Using Supervisor)
I have configured by VPS server with Django and I am running a scheduled task for that I am using CELERY. I am using supervisor to run celery. When I directly run the celery command all the things work great and my schedule jobs also work(also if I click on run task button the tasks start quickly). But when I configured celery using supervisor it never runs the tasks (when scheduled) and also the run task did not work at the first time(when I try 4-5 times the tasks start it runs). This is my supervisor file- ; ================================== ; celery worker supervisor example ; ================================== ; the name of your supervisord program [program:ip_tambola] #Set full path to celery program if using virtualenv command=/home/django/venv/bin/celery -A Tambola worker --beat --scheduler django_celery_beat.schedulers:DatabaseScheduler --loglevel=debug #The directory to your Django project directory=/home/django/ip_tambola/Tambola #If supervisord is run as the root user, switch users to this UNIX user account before doing any pr user=root #Supervisor will start as many instances of this program as named by numprocs numprocs=1 #Put process stdout output in this file stdout_logfile=/home/django/ip_tambola/celery_out.log #Put process stderr output in this file stderr_logfile=/home/django/ip_tambola/celery_err.log #If true, this program will start automatically when supervisord is started autostart=true … -
Failed to import mp3 file using mutagen in Django
I'm trying to get the length of an mp3 file using mutagen in django. (Finding the length of an mp3 file) I saw and followed the post above. I installed mutagen with pip and wrote the code like this: def music_player(request, id): song = Song.objects.get(id=id) audio = MP3(song.song) print(audio.info.length) There was an error loading the mp3 file. error code: FileNotFoundError: [Errno 2] No such file or directory: '/Users/<username>/django/note/media/media/song/butter.mp3' The file path is incorrect. 'Media/Media'. It seems that the media path was added automatically once more. (song.song has a built-in 'media/song/butter.mp3'.) How can I solve this? -
How i can pass value of html element to model.py in django?
How i can get value of checkbox from customize html in model.py or admin.py? # model.py class Geo(models.Model): locations = models.TextField(blank = True, null = True) location_as_text = models.TextField(blank = True, null = True) def save(self, *args, **kwargs): answer = value_of_check_box_in_custom_html if answer = true: func1() else: func2() super(taxon, self).save(*args, **kwargs) I have custom_change_form.html in admin templates # admin/personal/custom_change_form.html {% extends "../change_form.html" %} {% load i18n admin_urls static admin_modify %} {% block submit_buttons_bottom %} <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckChecked" checked name="locationcheck"/> <label class="form-check-label" for="flexSwitchCheckChecked">Checked switch checkbox input</label> </div> {% submit_row %} {% endblock %} My admin.py # admin.py @admin.register(models.geo) class geoAdmin(admin.ModelAdmin): change_form_template = 'admin/personal/custom_change_form.html' def get_osm_info(self): # ... pass def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['osm_data'] = self.get_osm_info() return super().change_view( request, object_id, form_url, extra_context=extra_context, ) How do I check whether a checkbox is checked in customize html? -
App not compatible with buildpack: Django + Python
When I click deployed button on heroku, I get some error, I have deployed this project for a certain period of time, and this time I deployed this error: -----> Building on the Heroku-18 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I already have requirnments.txt, runtime.txt, Procfile, I already added buildpack(heroku/python) in setting, requirnments.txt asgiref==3.2.10 beautifulsoup4==4.9.3 dj-database-url==0.5.0 dj-static==0.0.6 Django==3.1.1 gunicorn==20.0.4 Pillow==8.1.2 psycopg2-binary==2.8.6 pytz==2020.1 soupsieve==2.2.1 sqlparse==0.3.1 static3==0.7.0 runtime.txt python-3.7.3 Procfile web: gunicorn APP_NAME.wsgi --log-file - Any help or explanation is welcome! Thank you. -
There is a way to {% extends '' %} parent html from alternative folder in template?
My project has several customers. Each app has html files that need to be specific for that customer, althogh has the same name. My approach to solve this was a variable which holds the folder's name with customer's html files, before the template's path, with this: {% extends {{FOLDER_NAME}}'account/form/base.html' %} instead this: {% extends 'account/form/base.html' %}, off course this d'ont work and I was wondering if there is a way to solve this. Thanks in advance. -
django static files are not being found and loaded
Using django v2.2.1 I have a given project dir. structure: In root project dir. there are some static files in static dir. In base.html file, {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- favicon --> <link rel="shortcut icon" href="{% static 'favicon.ico' %}" /> <!-- Dropzone js --> <link rel="stylesheet" href="{% static 'dropzone.css' %}"> <script src="{% static 'dropzone.js' %}" defer></script> <!-- Custom js & css --> <link rel="stylesheet" href="{% static 'style.css' %}"> . . This is settings.py file: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'sales', 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') But I've been getting this error I have restarted the server many times. -
how to capture logged in user's name in django?
class logEngine: def logger(request): t1 = time.time() params = {'user': request.user.username, 'ip_address': socket.gethostbyname(socket.gethostname()), 'process_time': time.time() - t1, } return params when I uses request.user.username (which is given in most of the examples in the internet), I get the below error, AttributeError: 'logEngine' object has no attribute 'user' Please suggest any other method