Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django Channels with multiple processes
When deploying a django app to production using gunicorn you're able to specify the number of worker processes by simply appending --workers 4 or defining this in the config file. How would I go about doing this when deploying using Daphne for a project that uses Django Channels? Daphne doesn't appear to support settings and config changes to the extent that gunicorn does. I haven't been able to find much in this regard. FYI, I am using docker-compose with the following services: api: This is the django channels app along with daphne redis: This is used for the channel layer caddy: This is the proxy I am using (Caddy Server) I presume not being able to set the number of processes is by design in daphne but I'm not sure why that is or what I should be doing instead? Is this simply not needed for some reason? -
Replicating Folder Structure inside the existing folder when updating the model Django
I have a model with image compression enabled class Course(models.Model): def upload_location(instance,filename): return "course_images/%s/%s"%(instance.course_name,filename) subject = models.ForeignKey(Subject,on_delete=models.CASCADE,null=True,default=None) course_name = models.CharField(max_length=300,default=None) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) course_description = models.TextField(null=True) course_cover = models.ImageField(null=True,blank=True,upload_to=upload_location,default="course_images/default.png") created_at = models.DateTimeField(default=now) price = models.IntegerField(default=0,null=True,blank=True) duration = models.CharField(max_length=20, null=True, blank=True) is_enrolled = models.BooleanField(default=False) def save(self, *args, **kwargs): new_image = compress(self.course_cover) self.course_cover = new_image super().save(*args, **kwargs) def __str__(self): return self.course_name When I update this model without sending an image from the frontend folder structure gets replicated inside the existing folder. ex:- Course_images/Science/science.jpg is the initial folder structure when creating an object with this model. But after updating the model without the image I can see another Course_images/Science/science.jpg inside Course_images. This starts to happen after adding the compression method. Without overriding the save method this works fine. Also if I change the image folder replication is not happening. View of the updatecourse class UpdateCourse(RetrieveUpdateAPIView): queryset = Course.objects.all() serializer_class = CourseCreateSerializer permission_classes = [IsAuthenticated] Can anyone state a reason for this scenario. Thank you! -
OpenID Connect + Django DRF + React: How to use?
I have a web application made up of two parts: back-end which is implemented using Django + Django Rest Framework (DRF), and front-end which is a React App project. For authentication and authorization, I use Keycloak. For authentication first, the front-end app redirects the user to the Keycloak login page, and after Keycloak receives the correct combination of username and password, redirects the user back to the front-end app and provides the front-end app with an access key and a refresh key pair. Now when the user wants to call any API to the back-end it has the required access key. I decided to put the front-end app in charge of refreshing the access token, too; but I am looking forward to any better solution. Since I need to use authorization in my application, its "Access Type" in Keycloak should be set as "confidential"; thus when my front-end app wants to authenticate, it should provide "client secret". This has no problem when I am in the development stage since I can easily change the client secret in the code. But when I want to build the front-end application for production, I hard-code the client secret from my Keycloak instance in … -
Django-App with Nginx and Gunicorn - Requests get lost?
in our company we use a timetracking system built with django. It is deployed with Nginx as reverse proxy and Gunicorn to run the python code. It is basically a simple system with a button to start the attendance and another button to stop. Sometimes users claim that they pressed start or stop, but the system did not process it. We are now determing if our Gunicorn configuration is not suitable for our use case and requests get lost. So, my question is: Is it possible, that requests get lost when Nginx/Gunicorn is not able to handle the amount of requests? Facts: Worst case amount of about 150 requests at the same time (150 active users of our application, everyone wants to register its stop at the same time. This does acually never happen) Gunicorn runs with the default configuration but 3 workers Any help in this case is appreciated, if you need further information, let me know! -
How to send email with attachment from form?
I've been trying different ways to send an attachment from a submitted form but I'm not able to get it right. my model: from django.db import models class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) views.py from django.shortcuts import render, redirect from django.core.mail import EmailMessage from decouple import config from .forms import ContactForm def contact(request): contact_form = ContactForm() if request.method == "POST": contact_form = ContactForm(request.POST, request.FILES) if contact_form.is_valid(): name = request.POST.get("name") email = request.POST.get("email") subject = request.POST.get("subject") message = request.POST.get("message") upload = request.POST.get("upload") email_content= EmailMessage("Message from django-structure project", f"The user with name {name}, with the email {email}," f" write the following: \n Subject: {subject} \n File{upload} \n\n Message: {message}", "", [config('EMAIL_TO')], reply_to=[email]) try: email_content.send() return redirect("/contact/?valid") except: return redirect("/contact/?invalid") return render(request, "contact.html", {"form": contact_form}) contact.html <div class="row"> <div class="col"> <div class="form-group"> {% if "valid" in request.GET %} <p style="color: blue;">Information sent successfully </p> {% endif %} <form action="" method="POST" enctype="multipart/form-data" style="text-align: center;"> {% csrf_token %} <table style="color: dark; margin:20px auto;">{{form.as_table}}</table> <input type="submit" value="Send" style="width: 150px;"> </form> </div> When I submit the form, I receive the message but in the content of the File, just the following string: "FleNone". (I have attached a pdf) -
Link to an id in html django view with url ```view/<int:id>/<slug:slug>/```
I have a view in django that views product details. In my urlpatterns list it's like the following. urlpatterns = [ ... path('view/<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ... ] Now I want to create a link of the following form mysite.com/view/1/drone/#reviews. I tried this and it doesn't bring me to the reviews section. But for a normal url like the following it works with no problem. urlpatterns = [ ... path('home/', views.home, name='home'), ... ] Can someone help me what's the difference here? Because when it's like this I can access mysite.com/#some_element -
kali linux, python. not beeing able to import
thanks for your time. i've started to work on kali linux and don't know why i'm not beeing able to import files. By using python manage.py every thing works fine, although when trying to run a file by it self i get or : from .models import Player ImportError: attempted relative import with no known parent package``` or from winners.models import Player ``` ModuleNotFoundError: No module named 'winners' I've tried to reset the ambient variable DJANGO_SETTINGS_MODULE DJANGO_SETTINGS_MODULE=olympic.settings tryed to add the path manually trough sys.path, tryed every possible way of import. i guess is something i configured wrong. -
Parsing bytestring into Python dictionary
I have a bytestring like this: b'{\r\n "hello": "world"\r\n}', retrieved from a request in JSON format. I would like to parse it into a Python dictionary so it looks like this: {"hello": "world"}. I have tried with ast.literal_eval() but that throws an error. How would you go about doing it? -
Django getting values from postgres jsonb field
I have a simple model like: class MyModel(models.Model): data = JSONField() The JSONField data is in the following structure: { "name": "Brian", "skills": [ {"id": 4, "name": "First aid"}, {"id": 5, "name": "Second aid"} ] } I'd like to create a query that gets a list of MyModels filtered by the id of the skill inside the data. I've tried a few different avenues here, and can do the work in Python but I'm pretty sure there's a way to do this in Django; I think my SQL isn't good enough to figure it out. Cheers in advance. -
How to get a list of all attributes in model -Django Rest Framework
I am trying to get a list of all names,emails and phones without writing similar class with get() method for each of them. Is there a way to write one general class for this purpose?I used APIView and Serializer(instead of ModelSerializer) consciously. Here is my code. views.py class userInfoList(APIView): def get(self, request, format=None): users = userInfo.objects.all() serializer = userInfoSerializer(users, many=True) return Response(serializer.data) serializers.py from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from .models import userInfo class userInfoSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=50) email = serializers.EmailField(max_length=70) phone = PhoneNumberField() def create(self, validated_data): return userInfo.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.email = validated_data.get('email', instance.email) instance.phone = validated_data.get('phone', instance.phone) instance.save() return instance -
Django Printing Model Output
I made an django app to fill my single html pages. Models look like class Flatpage(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=40) short_description_text = models.TextField(blank=True) content = RichTextField(blank=True, null=True) published_date = models.DateTimeField('Published_Date') meta_keyword = models.CharField(max_length=30) meta_description = models.TextField(blank=True) how can i print my model output according to slug to single page htmls (etc about us , faq ) -
How to browse files on a boto3 space ? NoSuchKey error
I created a s3 space with Digitalocean. I upload files into this one with ckeditor in a django project. I have no problem for uploading files but I meet a problem when I try to browse my server (to see if an image is already present) Here is my code: session = boto3.session.Session() client = session.client('s3', region_name='fra1', endpoint_url=settings.AWS_S3_ENDPOINT_URL, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY ) resp = client.list_objects(Bucket=settings.AWS_STORAGE_BUCKET_NAME) And an error happend the line where I call the function list_objects An error occurred (NoSuchKey) when calling the ListObjects operation: Unknown That's really stranger because I'm sure my settings.AWS_STORAGE_BUCKET_NAME is the correct one. Furthermore I'm sure there is no error in session.client because I use the same for uploading files, which works perfectly. To make sure my bucket is the correct one I go to my AWS_S3_ENDPOINT_URL and got an XML with <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <Name>[MY BUCKET NAME]</Name> <Prefix/> <MaxKeys>1000</MaxKeys> <IsTruncated>false</IsTruncated> And after that begins a list of <Contents> Thank you for your help -
load pytorch pretrained model into Django website or in OpenCV
I had trained an object detection model in Pytorch and now I want to load this pre-trained model into my Django website. In fact I want to using this pytorch model into my web site. If there isn't any way to import to website how can I import my pytorch model into OpenCv? In fact I want to test my pytorch model in to another application but I don't have any idea about this. -
How to get nationalities with django-countries
I am trying to get a nationality with a package called django-countries in Django, forexample if the country is Germany nationality is German, Kenya is Kenyan etc. How can I achieve this with this package -
Django behind Nginx build_absolute_uri returns http://host/
Django's request.build_absolute_uri() function returns http://host/ for my URL pointing to / on localhost and any domain I host it on. Django is behind Nginx and both are docker containers. Here's a docker-compose.yml: version: '2.4' services: django: build: context: . env_file: ./.env volumes: - ./src:/django_project nginx: image: nginx volumes: - ./nginx.conf:/tmp/nginx.conf depends_on: - django links: - django ports: - "3000:80" Django is behind Nginx and the Nginx config is as follows: server { listen 80; client_max_body_size 80M; location / { proxy_pass http://django:8000/; proxy_read_timeout 240s; uwsgi_ignore_client_abort on; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; } } I'm thinking it's definitely Nginx that's the bad gue, but what am I missing? -
Django superuser page not found
If I give superuser status to a user or create a new superuser, that user will not open their own profile page. Get the error page not found, at the same time opens the admin panel. All other functions on the site, such as login and commenting, he also performs without problems, but the user's own page does not open views.py def profiles(request, pk=0): ... profile = Profile.objects.get(id=pk) # users not require ... context = { 'profile':profile, ...} return render(request, 'profiles/account.html', context) models.py class Profile(models.Model): first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=150, blank=True) country = models.CharField(max_length=100, blank=True) about = models.TextField(blank=True, null=True) avatar = models.ImageField(default = 'avatar.svg', upload_to = 'avatars/%Y/%m/%d', blank=True, null=True) friends = models.ManyToManyField(User, blank=True, related_name='friends') update = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user}" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() HTML {% if profile.user == request.user %} <img src="{{user.profile.avatar.url}}" class="img-fluid" width="350px" /> <a href="{% url 'change_avatar' profile.id %}" class="btn btn-sm btn-succes card-body container " type="submit"/> Change avatar</a> <div class="card-body center"> <h5 class="card-title">{{user.username}}</h5> <p class="card-text"> <p>registered {{user.profile.created|date:'Y-m-d'}}</p> <p class="card-text">about: {{user.profile.about}}</p> </p > <a href="#" class="btn btn-primary btn-sm "> Friends </a> <a href="{% url 'postman:inbox' %}" class="btn … -
<Field 'id' expected a number but got 'Vodoinstalater'.> have to fix this?
I am traying to filter data by using and in Django. But always getting an error <Field 'id' expected a number but got 'Vodoinstalater'.> Here is the main models.py file: from django.db import models class TaskCategory(models.Model): category_title = models.CharField(max_length=50) def __str__(self): return self.category_title class Post(models.Model): task_title = models.CharField(max_length=250) task_discription = models.CharField(max_length=250) task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget = models.CharField(max_length=250) def __str__(self): return self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' | ' + self.recommended_tools + ' | ' + self.budget views.py file: from .models import Post, TaskCategory from django.shortcuts import render, get_object_or_404 def is_valid_queryparam(param): return param != '' and param is not None def PostPageView(request): posts = Post.objects.all() category = TaskCategory.objects.all() context = { 'posts': posts, 'category': category, } category = request.GET.get('category') if is_valid_queryparam(category) and category != 'Choose...': posts = posts.filter(task_category=category) category = TaskCategory.objects.all() context = { 'posts': posts, 'category': category, } return render(request, "post_page.html", context) return render(request, "post_page.html", context) urls.py file: from django.urls import path from .views import PostPageView urlpatterns = [ path('PostPage/', PostPageView, name ='post_page'), ] And HTML file: {% for cat in category %} <option value="{{ cat.category_title }}">{{ cat.category_title }}</option> {% endfor %} -
Pagination in django not working for first page
Am currently implementing pagination in django. I have a problem when i try to click a button that is supposed to redirect me back to the first page or even get the content of the first page. views.py else: all_tasks = TaskList.objects.all() paginator = Paginator(all_tasks, 5) page = request.GET.get('pg') all_tasks = paginator.get_page(page) context = { 'all_tasks': all_tasks } return render(request, 'index.html', context) html code <nav aria-label="Page navigation example"> <ul class="pagination justify-content-end"> <li class="page-item"><a class="page-link" href="?pg=1">First</a></li> {% if all_tasks.has_previous %} <li class="page-item"><a class="page-link" href="?pg={{ all_tasks.previous_page_number }}">{{ all_tasks.previous_page_number }}</a></li> {% endif %} <li class="page-item"><a class="page-link" href="?pg={{ all_tasks.number }}">{{ all_tasks.number }}</a></li> {% if all_tasks.has_next %} <li class="page-item"><a class="page-link" href="?pg={{ all_tasks.previous_page_number }}">{{ all_tasks.previous_page_number }}</a></li> {% endif %} <li class="page-item"><a class="page-link" href="?pg={{ all_tasks.paginator.num_pages }}">Last</a></li> </ul> </nav> When i click "first" django throws those errors. Kindly assist. error that django is throwing is this EmptyPage at /task/ That page number is less than 1 Request Method: GET Request URL: http://127.0.0.1:8000/task/ Django Version: 3.1.5 Exception Type: EmptyPage Exception Value: That page number is less than 1 Exception Location: C:\Users\BernardMuendi\.virtualenvs\TaskMate-R1pilZ9L\lib\site-packages\django\core\paginator.py, line 50, in validate_number Python Executable: C:\Users\BernardMuendi\.virtualenvs\TaskMate-R1pilZ9L\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\BernardMuendi\\Desktop\\TaskMate\\taskmate', 'c:\\program files\\python38\\python38.zip', 'c:\\program files\\python38\\DLLs', 'c:\\program files\\python38\\lib', 'c:\\program files\\python38', 'C:\\Users\\BernardMuendi\\.virtualenvs\\TaskMate-R1pilZ9L', 'C:\\Users\\BernardMuendi\\.virtualenvs\\TaskMate-R1pilZ9L\\lib\\site-packages'] Server time: Tue, 16 Feb … -
Send and Recieve Video using API Django
I want to make a API in Django, where I send a video using API and returns a Video as output. -
how to dynamically set visible fields of a django modelform?
I would like the visible fields of a modelform to be determined by the instance of the model class it is built upon. The modelform is built upon the model protocol which has a method (protocol.visiblefields())which returns an array of strings corresponding to the fields to be made visible. forms.py class ListForm(ModelForm): class Meta(): model = protocol fields = [] views.py newProtocol = protocol() form = ListForm(instance=newProtocol) -
django method not allowed (get,post) 405
First, I am not an English user and I am a beginner in django. When i try to send a put, patch, and delete request to api, Method Not Allowed (GET): error occurs. For example, Write down the code below using the patch. views.py class Boardapi_update(View): def patch(self, request, *args, **kwargs): data = { 'pk': self.kwargs['pk'], 'b_title': requests.POST.get['b_title'], 'b_note': requests.POST.get['b_note'] } url = 'http://localhost:8080/boardapi/'+str(data['pk'])+'/update/' bupdate = requests.patch(url, datas=data) # bupdate = requests.put(url, json={'query':data}) print(bupdate) def get_success_url(self): return reverse('board_detail', kwargs={'pk': self.object.board.pk}) html <form action="{% url 'board_update' board_detail.b_no %}" id="frmBoard" method="patch"> {% comment %} {%csrf_token%} {% endcomment %} -
how can i use the djangi river for django workflow management system?
i go through the documentation of django river in github too.But i couldn't understand how to do that in my project.If anyone have the idea about django river for django workflow management system,please give the answer with your comments. Thank you -
Celery & Celery Beat daemons not running tasks
I've set up the celeryd and celerybeat daemon by following this guide. When the daemons start, everything is marked as ok, however Celery simply doesn't run any of the tasks set in my Django application. This is my /etc/default/celeryd file: CELERY_NODES="w1" CELERY_BIN="/home/millez/myproject/venv/bin/celery" CELERY_CHDIR="/home/millez/myproject" CELERY_OPTS="-l info --pool=solo" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERY_CREATE_DIRS=1 and this is my /etc/default/celerybeat: CELERY_BIN="/home/millez/myproject/venv/bin/celery" CELERYBEAT_CHDIR="/home/millez/myproject" CELERYBEAT_OPTS="--schedule=/var/run/celery/celerybeat-schedule" If I manually restart the daemons, (sudo /etc/init.d/celeryd restart and sudo /etc/init.d/celerybeat restart), and then check their statuses, this is the only output I get: celeryd (node celery) (pid 2493) is up... Running the actual celery commands manually works fine, e.g celery -A myproject worker -l info, it seems to be an issue with the way I've set up the daemons. However, I'm not too Linux savvy, so if anyone happens to be able to see some easy oversight I've made, let me know, this is driving me insane. -
Is there anyone know how to use python-eureka-client
I am trying to use python-eureka-client for to connect eureka service discovery with django. And is there any way, please suggests for microservice with django. -
Django Invalid credentials while loggin into the account
I'm trying from a few days to create a login & register system for my WebSite, built with Django. But, every time I try to login to my superuser account, or a testaccount that I've created, I get an error. When I enter my credentials in the form and press the Submit button, the page reloads but I am not logged in as a user and no error is given to me. But if I go to the admin page, i'll see an error saying me that Username or Password is invalid. I set this error to make it appear on the login page when the credentials were wrong, but nevertheless, despite the credentials are right, I am given a mistake, and moreover on the wrong page. Here my code: File: views.py from django.shortcuts import render, redirect from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import CreateUserForm def registerPage(request): if request.user.is_authenticated: return redirect('home') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('home') context = {'form':form} return …