Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Server Error (500) when using s3 aws amazon to store media and static fil
I got Server Error (500) when trying to launch any django page with DEBUG=FALSE, even with default admin page. my static files and media files are configured to upload to s3 aws storage Anyone has encountered this problem ? Please give me some advice Many thanks -
How to implement autocomplete user search in React and Django Rest Framework
So basically I'd like to implement a user search system in react which would send an api request to my django backend which would send back the results. This is an easy implementation if I wanted the results once I hit search but I want the results displayed as autocompletes. For example in Twitter it autocompletes what you are searching for. How would I implement this. I am using axios for my requests if that helps. A side note would be that I'd like to wait maybe a second or 2 before sending the request because I would want to send to many requests and slow down the server. Thank you! -
Display User's 'is_active' status in TabularInline Django
I have a Client object that has a User and a Company objects as FKs class Client(models.Model): user = models.OneToOneField(User) company = models.ForeignKey(Company, blank=True, null=True) In my CompanyAdmin, I want a list of all clients as a TabularInline, including the active status of each client (based on user object) class CompanyClients(admin.TabularInline): model = Client fields = ('user', 'master') class CompanyAdmin(admin.ModelAdmin): inlines = [CompanyClients] I want to add a column in my TabularInline to indicate that that user is active or not. I tried using 'user__is_active' to my fields but I get this error: Unknown field(s) (user__is_active) specified for Client I just want an indication even if read-only (which I tried by putting a readonly_fields and it didn't work too), not looking to save/edit each client user's active status value from the Tabular form. How can I approach this? Thanks in advance. -
User avatar not displayed in Django
models.py class Avatar(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, null=True) avatar = models.ImageField(upload_to='user_avatars', null=True) forms.py class UserPhotoForm(forms.ModelForm): class Meta: model = Avatar fields = ('avatar', ) widgets = { 'avatar': forms.FileInput(attrs={'class': 'input'}), } views.py def cabinet(request): user = request.user if request.method == 'POST': form = UserPhotoForm(request.POST, request.FILES, instance=user) if form.is_valid(): form.save() else: form = UserPhotoForm() return render(request, 'account/cabinet/cabinet.html', {'form': form}) cabinet.html <div class="avatar"> {{ request.user.avatar.url }} #there is trying {{ request.user.avatar.avatar.url }} <img src="{{ request.user.avatar.avatar.url }}" alt="" width="80px" height="80px"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" id="file"/> </form> I want to user have a avatar. So I created the model and the form. Image is not displaying on the page. But form saves the image to folder. Where is mistake? request.user.avatar.url doesn't work. Maybe the image is not attached to User? Thanks for the help P.S. djagno-avatar is not good for me. -
autocomplete in django-admin site for every foreign-key field
What could be the way to make every foreign-key field searchable/autocomplete in django-admin site in general? Means whenever I define a foreign-key field in model, i would need nothing more to make it autocomplete. I could not find any such module because the module like https://django-autocomplete-light.readthedocs.io/en/master/gfk.html facilitate with even complicated way, and do not provide a thing like odoo where developer would not need to code for each field to make it autocomplete I have using odoo, where I define a field in any child_model1 like parent_id = fields.Many2one('my_module.parent_model1') I simply get a searchable and autocomplete select list in my child_model1's form, I have nothing to add more anywhere. But in contrast with django when i define a filed on child_model1 like parent_id = models.ForeignKey(ParentModel1) First i would need to define on_delete=?, even I have no option to set anywhere globally that hello django please always restrict on delete until I tell you to make a field on_delete=cascade Then I need that all of my foreign-key fields in any model need to be autocomplete but I always have to write each field in each each child model's admin like autocomplete_fields = ['parent_id'] also I have to give something like search_fields … -
How to use Cross Site Request Forgery protection correctly?
I've only started getting into web programming with Django recently. In order to make my website more secure, I used csrf_token when sending POST request, followed what I saw in https://docs.djangoproject.com/en/3.1/ref/csrf/. However, as I included <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script> in my HTTP file from Javascrip Cookie Library, I can get the csrf_token directly from my browser in Inpsect>console. I am not sure if I did this correctly or not, please give me some pointers. -
Django CSS File Not Working/Not being served
I cannot figure out why my css file is not working. I added my css, html and settings.py files. Can anyone help? I've tried collectstatic but get an error: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'D:\\mysite\\dreamboard\\static\\dreamboard\\style.css' I tried replacing my path in the STATICFILES_DIRS but it still does not work. I'm not sure what to do. It could be the bootstrap? Or something. I want to have a style sheet so I can my form to a popup button. Everything is titled and spelled correctly. Any ideas? Here are my files: {% 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"> {% load crispy_forms_tags %} <link rel="stylesheet" type="text/css" href="{% static 'dreamboard/style.css' %}"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/73cead4581.js" crossorigin="anonymous"></script> <title>Hello, world!</title> </head> <body class="bg-light"> <h1>Hello, world!</h1> <div class="container"> <div class="row bg-dark"> <div class=" col-sm"> <h1 style="color:white">Dreamboard</h1> </div> <div class="col-sm"> <button class="btn-lg btn-primary" type="submit">Add Dream</button> </div> </div> </div> </div> <form class="" action="" method="post" autocomplete="off"> {% csrf_token %} <div class="row"> <div class="col-md-6"> {{form.first_name|as_crispy_field}} </div> <div class="col-md-6"> {{form.last_name|as_crispy_field}} </div> </div> {{form.dreamItem|as_crispy_field}} <br> <button type="submit" class="d-grid gap-2 col-12 btn btn-success">Submit</button> </form> <!-- Optional JavaScript; choose … -
change specific field of an object using POST method django rest api
i'm using djangorestframework. and i want to be able to change specific field of my objects using POST method. can anybody help please?? i have no idea how to do that. here is my model: class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) gender = models.CharField(max_length=10) national_code = models.CharField(max_length=11) personal_code = models.CharField(max_length=15) phone_number = models.CharField(max_length=11) address = models.CharField(max_length=50) married = models.BooleanField() age = models.IntegerField() wage = models.IntegerField() def __str__(self): and i want to be able to for example change one of my employee's wage(with personal code 123)to new wage 500000 using such url: POST /myupdate/123/500000