Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Other alternatives for microsoft visual studio for raspberrypi 2
I am using raspberry pi 2. I am fond of working django but installing visual studio is impossible.So if there is any other alternative please leave me the command line codes to nstall it. -
Django pagination count query slow
I have an optimization / performance question around Pagination in Django for querysets that use select_related and annotate ro reduce the number of queries. My actual case has a lot more models, but for the sake of simplicity I am showing a simplified version here. class Product(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_lenth=25) owner = models.ForeignKey(Owner) class Feature(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) class Author(models.Model): name = models.CharField(max_length=100) class Owner(models.Model): name = models.CharField(max_length=100) If I display a list or products with just the name of the product, this will suffice: products = Products.objects.all() And I could paginate by Django built-in pagination: paginator = Paginator(products, 25) page = paginator.get_page(0) # to render the first page. This works as expected and will generate 2 SQL queries. One to count all records and another one to retrieve the first page using LIMIT and OFFSET. The count query looks like this: SELECT COUNT(*) FROM PRODUCT All good. Now when I add some select_related and annotate clauses, the count query becomes (very) inefficient. products = Products.objects.all().select_related("owner") \ .annotate(feature_count=Count('feature__name', filter=Q(feature__author__name='opper'))) This will obviously geneate some LEFT OUTER joins and count/case statements, resulting again in 2 queries Query 1: SELECT COUNT(*) … -
why displayng a video on a Django server using a public computer shows an attribute error?
I'm new to Django server applications, and I've been trying to test displaying several media files on a Django app .. almost all media files like Images, GIFs, and videos can be displayed fine without any problems using the local host. however, acessing the website using a public host doesn't displayed images but no Videos can be displayed. AttributeError: 'NoneType' object has no attribute 'split' In Summary It is not possible to access the video url via a public IP, I can display it without any problems locally or from any computer connected to the same router. Only images and Gifs can be accessed without any problems using public and local IPs here are the codes I've been using to display the test video: .html file {% extends "blog/base.html" %} {% load static %} {% block content %} <video oncontextmenu="return false;" width='320' height= '240' autoplay controls controlsList="nodownload"> <source src="{% static 'videos/test.mp4' type='video/mp4' %}"> Your browser does not support the video tag. </video> {% endblock content %} settings.py static root was defined STATIC_URL = '/static/' MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/ url.py url patterns were adjusted if settings.DEBUG: # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and in the views.py I simply render back the html after … -
Django REST with React: axios POST with FormData _method PATCH still requires a field
I am trying to make a form that edits the user's profile data and uses the patch method to change all the fields except the username because the username is the primary key and only identifier of a specific user. From reading previous questions, I've learned that a normal axios.patch method does not work with FormData and I've followed the instructions of adding: formData.append("_method", "PATCH") and changing the axios method to axios.put, however, I still receive a 400 error which states, in the data section: username: ["This field is required."] Help would be much appreciated. Thank you, kind strangers! Edit Profile Submit: onSubmit = (e) => { e.preventDefault(); const { firstName, lastName, profile } = this.state; const username = localStorage.getItem("username"); formData.append("_method", "PATCH"); formData.append("firstName", firstName); formData.append("lastName", lastName); formData.append("profile_picture", profile); this.props.onUpdate(formData, username); }; Axios Request export const userUpdate = (formData, username) => { axios .post(`http://127.0.0.1:8000/user/api/${username}`, { formData, headers: { "Content-Type": "application/x-www-form-urlencoded" }, }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error.response); }); }; User models.py class User(models.Model): firstName = models.CharField(max_length = 20, blank = True, default='Anonymous') lastName = models.CharField(max_length = 25, blank = True, default='') username = models.CharField(max_length = 50, unique=True, primary_key=True) profile_picture = models.ForeignKey('upload.Profile', on_delete=models.CASCADE, null=True) Profile Picture models.py class … -
Exceptional value:attempt to write a readonly database Centos 8 Apache webserver Python 3.6
Good evening. So I have following problem after correct login in django: Django database read-only error Owner of project and all files is apache Permissions on db.sqlite3 is -rwxrwxrwx Whole folder with project has permission 777 -
Heroku blocks bokeh.js scripts
I have a problem wit heroku - after uploading my app which uses bokeh.js script, these scripts aren't loaded and I have to temporary turn off security in web browser. In this project I use Django. Inspecting network: Including script in html.file: <link href="http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-1.4.0.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.4.0.min.js"></script> In addition when I run it on localhost it works fine. Did anybody have problem with that? -
How To Practice Back-end Dev(Django)
I started with web development using Django been a year now I started of doing both front-end and back-end. I then realized front-end is not my cup of tea, however I know struggle to figure out how am I too practice and improve my back-end skills without me having to first do some front-end work or its not really possible? -
Getting error message - Page not found (404) Request Method: POST, when users try to add comments to posts
When the user presses the POST button, comments are not being added to the back end. The user gets redirected to http://localhost:8000/your-name/ which is a page that didn't exist on my site. I made a page on my site called your-name as a test. And once I did this, the test page did load. But the comments were still not being added to the back end. Each comment can only have one post linked to it. Each post can have many comments linked to it. I think one problem is that the posts have individual URLs. But the comments don't have their own URLs. When I refresh the page, I need to take the URL of the active post. I tried doing comment_form.save(commit=True). I wanted to see if I could get any thing (valid or invalid data) to be added to the back end and it didn't work. views.py def post_detail(request, pk_slug): template_name = 'post_detail.html' if pk_slug.isdigit(): post = Post.objects.filter(id=pk_slug).first() else: post = Post.objects.filter(url=pk_slug).first() comments = Comment.objects.filter(post=post.id ,active=True) #post = Post.objects.get(pk=pk) new_comment = None # Comment posted #comment_form = CommentForm(data=request.POST) #if comment_form.is_valid() and request.method == "POST": if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but … -
ValueError at /change-password/ The view authapp.views.ChangePassword didn't return an HttpResponse object. It returned None instead
The below function I made says the following - ValueError at /change-password/ The view authapp.views.ChangePassword didn't return an HttpResponse object. It returned None instead. please help TIA. def ChangePassword(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() return redirect('profile') else: current_user = request.user form = PasswordChangeForm(user=current_user) -
Is there any method to access media files in django views?
With django 2.7 i was using settings.MEDIA_ROOT + '/' + directory + '/' + filename in my views.py to access files from media but in django 3 it is raising PermissionError. -
Django postgres database connectivity - DLL load failed while importing _psycopg: The specified module could not be found
I have tried many options available however nothing is worked for me. This is my environment OS : Windows 10 Home 64bit Python Version : Python 3.9.0a6 Django Version : 3.0.5 Postgress db Version : 12 This is the method I used to make the connectivity DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxxx', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost' } } Error that I'm receiving (dev-test) F:\Personal\xxxx\Learning\Django\projects\jangoproject\devtest>python manage.py startserver Traceback (most recent call last): File "C:\Users\LENOVO\Envs\dev-test\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in import psycopg2 as Database File "C:\Users\LENOVO\Envs\dev-test\lib\site-packages\psycopg2__init__.py", line 51, in from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: -
extend User Model in django
this is model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='avatar/', null=True, blank=True) password2 = models.CharField(max_length=15) def __str__(self): return self.user.username this is serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('avatar',) def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) profile = Profile.objects.create(user=user, **validated_data) return profile this is view.py @api_view(['GET', 'POST']) def User_view(request): if request.method == "GET": user = Profile.objects.all() serializer = UserSerializer(user, many=True) return Response(serializer.data) elif request.method == "POST": serializer = UserSerializer(data=request.data) print(serializer) if serializer.is_valid(): serializer.save() return Response({'message': serializer.data}, status=status.HTTP_201_CREATED) return Response({'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) I am new in Django I want to build a model to register a user with their profile image and password2 for password confirmation but I did not understand how to extend User model and give a proper message of success and error. -
Two forms in one view when i need id of the first one on second
Henlo. I'm creating some simple web app where you can create your own polls. It is an extention to tutorial app on django site. So i created view where you can see your polls, create poll, login, sign up, etc. The problem is that when you create your poll you have two views. One to create topic of poll and one where you create choices that you want to have in poll. I do this on two views because Choice need to have Question id that is created when you create topic of poll. So here is my question, is there anyway to do this on one page? I tried to just simply add two forms to one view but when i submited forms nothing happened. I tried to use some of the answers that i found on google but i couldn't find one that would work. The problem is that Choice needs to have Question id as foreign key and that's why i do it on two views. But dunno how to do it on one page. I just started my adventure with django so i'm not really sure how to do it. Here is my code. models.py User … -
Nginx, Django - Domain gives 400 (Bad Request) but reaching through IP Adress des work
I added the domain to allowed hosts already like that: ALLOWED_HOSTS = ["161.35.74.202", "*.example.de", "example.de"] This is how my nginx sites available file looks like: server { listen 80; server_name 161.35.74.202 example.de; I now tried adding a "+" to Allowed Hosts (+=), which again did not change anything. I am really frustrated right now because I cant find the mistake here. I tried a lot and would be really really grateful for an advice. Thanks -
DJANGO: How to live filter for loop results?
So I have a for loop in HTML code like this: div class="container-fluid"> <div class="jumbotron bg-dark"> <div class="row"> </div> <div class="row"> </div> </div> {% for institution in all_institutions %} <a href ="{% url 'students:class_chooser' institution.name %}"> <div class="jumbotron"> <div class="jumbotron-background"> <img src="{{ institution.image }}" class="blur"> </div> <div class="container"> <p> {{ institution.name }} </p> </div> </div> </a> {% endfor %} </div> Is it possible to create live filter search for it? Like this one, But for DJANGO Code? I have look on entire DJANGO documentation but I was unable to find it, because I want to avoid normal search? -
How to add a SQL constaint to a custom model field?
Is there a way to add some SQL constraints to a custom model Field? I know in Models you can add a constraints attribute to the Meta class, but I want to be able to reuse the custom model field in other Models. Checking the Field source I can see that there's a db_check method that is not documented, so I don't know if overriding that is the solution. -
my_app.decorators.wrapper_func didn't return an HttpResponse object. It returned None instead
I am creating web app with django. In this app logged user can go to his profile page where he has his own posts. I also made a form where he can add post straight from website but when he submit the form the error show up(my_app.decorators.wrapper_func didn't return an HttpResponse object. It returned None instead.).I was trying to solve this for three days but I still don't know how to fix this. I am grateful for every answer. decoratosr.py: from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(response, *args, **kwargs): if response.user.is_authenticated: return redirect('/') else: return view_func(response, *args, **kwargs) return wrapper_func def authenticated_user(view_func): def wrapper_func(response, *args, **kwargs): if response.user.is_authenticated: return view_func(response, *args, **kwargs) else: return redirect('/') return wrapper_func views.py: @authenticated_user def profilePage(response): user = response.user profile = Profile.objects.get(user=user) all_posts = profile.posts_set.order_by('-created_date') context = {'posts': all_posts, 'user': user} return render(response, "app_nature/profile.html", context) @authenticated_user def AddPost(response): user = response.user profile = Profile.objects.get(user=user) if response.method == "POST": form = UploadPost(response.POST) if form.is_valid(): post_save = posts(author=profile) post_save.save() form.save() return HttpResponseRedirect("/profile") else: form = UploadPost() context = {"form": form} return render(response, "app_nature/add_post_page.html", context) forms.py: class UploadPost(ModelForm): class Meta: model = posts fields = ['image', 'description'] -
Forms.ValidationError Not Working, Django,
from django import forms from django.core import validators class FormName(forms.Form): name = forms.CharField() email = forms.EmailField() verify_email = forms.EmailField(label = "enter your email Again") text = forms.CharField(widget = forms.Textarea) def clean(self): all_clean_data = super().clean() email = all_clean_data['email'] vmail = all_clean_data['verify_email'] if email != vmail: raise forms.ValidationError("Error i Email matching") views.py from django.shortcuts import render from . import form # Create your views here. def index(request): return render(request,'basicapp/index.html') def form_name_view(request): forms = form.FormName() if request.method == "POST": formObject = form.FormName(request.POST) if formObject.is_valid(): print("Sucess!!!!!") print(formObject.cleaned_data['name']) print(formObject.cleaned_data['email']) print(formObject.cleaned_data['text']) return render(request,'basicapp/form_page.html',{'form':forms}) form_page.html <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Forms</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class = "container"> <h1>Fill out the form</h1> <form method="POST"> {{form.as_p}} {% csrf_token %} <input type="submit" class="btn btn-primary" value = "Submit"> </form> </div> </body> </html> I am Not sure What I am missing, I have done everything and had done enough research, But could not find the solution. Am I missing something because of the versioning of django. I am following one udemy course and didn't get response, Thats y I am posting here. Thanks in advance -
Recalling the latest date on views.py
I'm trying to receive the latest date from a Queryset. ''' customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=1000, null=True) stock = models.CharField(max_length=200, null=True) min_stock = models.CharField(max_length=200, null=True) class Meta: get_latest_by = 'date_created' def __str__(self): return self.product.name''' So that I can display on my html, the latest dates of when each customer has made an order and updates itself as each time a order has been made. However when I try this queryset, latest_order = Order.objects.order_by('date_created').last() I receive the name of the product rather than the date_created, is there a way of receiving the latest date_created per customer? -
How cani redirect result requests.get(image) to user in Django?(the image cannot be displayed because it contains errors)
I have a Django app, I want when user enter URL : http://127.0.0.1:8000/flower/h/7/ I get that name image and after some process download that with bellow function and return answer to user, But this not work. def(request,download ): ... do some process ... url = 'http://example.com/img.png' response = requests.get(url) return HttpResponse( response .content , content_type='image/png') Notice :type response.content is byte User response 200 but cant display image and have error : "the image cannot be displayed because it contains errors" I use return HttpResponse(data, content_type='application/octet-stream') too but have same error. -
Understanding django form models
Newbie to django framework here, coming from a Laravel background. I have spent alot of hours trying to understand how django form models work. So far all the documentation and help online only explains how to use form models. However, I'm interested in understanding how django automatically builds the form , i.e. how does it decide which column from the database to use as the "value" of the html input, and which column does it use to populate the "label" of the input. Can someone here help explain to me in detail please? What I know so far How to build a model and define the column data types How to create a form using forms.ModelForm and specifying which field from the model I would to include in the form. What I would like to do with the knowledge above, My end goal is to build a custom select widget and be able to specify data-"attribute" property in the options tag of the select form. The value of the data-attribute should come from one of the fields in the model. For example, if i have the following records from a "fruits" model. { [ "id":"1", "name": "Apple", "color": "red" ], … -
How to send email/phone number verification code in Django?
I'm building a registeration portal for my website. I'm using Django. Any user needs to input unique username and email to register. How to enable email verification? -
how to get objects of the last X hours?
I'm making an app where you can upload images, but I want to let users to post one image per hour so how can I filter Images before one hour? here's the code: if Images.objects.filter(username=request.user).filter(pub_date=LAST HOUR).exists(): messages.info(request, 'you are allowed to post one image per hour.') return redirect('home') -
Django: nested formSet with 3 models in the same form
I use Django with basics and will need for my next project to use nested inlineformset at 3 levels I means, I would like user to be able to register data in 3 differents models in the same form I have seen examples with 2 models but look for example with 3 models and I am a bit lost what would be the easiest way to do that ? model user is parent of model project (one-to-many) model project is parent of model application (one-to-many) --------------------------------------------------------------------------------- | | | user name(model1): | | | --------------------------------------------------------------------------------- | project name(model2): application name (model3): access (model3): | | project name(model2): application name (model3): access (model3): | | | | | --------------------------------------------------------------------------------- ``` -
Rest-auth :Exlamation mark comes before password
I am using rest-auth for authentication. after registration when I try to login it show { "non_field_errors": [ "Unable to log in with provided credentials." ] } and when I saw the user on admin panel an an '!' mark comed before password for example password ='!72wlGF0RiGRraz69sveb63FUrebNkAW9xmOoL16C' please help