Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Display uploaded images in HTML - DJANGO
I am trying to display images that are upload by the user in my HTML. I'd set the following: Settings: MEDIA_URL = '/media/' MEDIAFILES_DIRS = [] MEDIA_ROOT = os.path.join(BASE_DIR, "media") Upload files within the model to directory: class Artikel(models.Model): artikel_pic = models.ImageField(upload_to='assortiment/images/', blank=True, verbose_name="Afbeelding") urls: urlpatterns = [ path(r'', include('main.urls')), path(r'', include('assortiment.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url that is given when i open the image in the admin panel: http://127.0.0.1:8000/media/assortiment/images/choco_ijs.jpg It displays correctly over here. html code that needs to diplay the image: <img class="card-img-top" src="{{MEDIA_URL}}/images/{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> I get a not found (304) error: "GET /media/assortiment/images/choco_ijs.jpg HTTP/1.1" 304 It looks like everything is going fine. Can't figure out what is going wrong though. I tried to change the src within the html file to: <img class="card-img-top" src="{{ artikel_pic }}" alt="{{art.artikel_naam}}"> <img class="card-img-top" src="{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> <img class="card-img-top" src="/images/{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> <img class="card-img-top" src="{{MEDIA_URL}}{{ artikel_pic.url }}" alt="{{art.artikel_naam}}"> Does anyone have some suggestions how to do this correctly? Thank you in advance! Sincerely, Rick P.S. Learned coding by doing, do not have any coding background. Just Stack, Google and Youtube :) -
what is the correct django version of my environment? ( is "python -m django --version" wrong ?)
why python -m django --version shows 3.0 (it may wrong), while django-admin --version show 2.2.5 in my project in setting.py file Generated by 'django-admin startproject' using Django 2.2.5. (django3+) C:\>python -m django --version 3.0 (django3+) C:\>django-admin --version 2.2.5 -
How to retrieve data from an input radio button in Django and send it to a view?
I have made a ToDoList app using Django a few months ago. Now, I want to add another feature called TaskLists. Like shopping lists or something like that. So previously, in my app home page there was one text field (which was a Django form of course) and user could enter a task and then add it. Now, I want to add more buttons to show the user a list of available Lists that they have created. Like if they have "Shopping" list and a "Movies to watch" list, I want to display two radio buttons (using Bootstrap) which a user could click on to indicate that they want this task to be under that list and then add it. I have done all these and got my List radio buttons to work and show up. But the main issue that I have ran into is that how can I pass this data, the list which the user wants this task to be in, to my Django view functions for processing? This is my code: <div class="content section"> <form method="POST" name="add_form"> {% csrf_token %} <fieldset class="form-group dark-mode-assist"> <legend class="border-bottom mb-4">New ToDo!</legend> {{ add_form|crispy }} <div class="form-group"> <div class="btn-group btn-group-toggle" data-toggle="buttons"> … -
I want to use variable in django template ,how can i use it .//
<a href="{% static {{i.pdf}} %}"> </a> i want to use like this ( variable in template tag )but cant please help thank you -
authorize api keys in django
How to verify the api keys in django? im using rapidapi and they have this key and how do i authorize it with the url views.py def thanks(request): url = "https://webknox-trivia-knowledge-facts-v1.p.rapidapi.com/trivia/random" headers = { 'x-rapidapi-host': "webknox-trivia-knowledge-facts-v1.p.rapidapi.com", 'x-rapidapi-key': "2b01c1685cmsh18f385b26cfee59p164749jsn3684ad96eaca" } r = requests.get(url) json_data = json.loads(r.text) print(json_data) return render(request,'portofolio/thankyou.html',headers) The print returns "{'message': 'Missing RapidAPI application key. Go to https://docs.rapidapi.com/docs/keys to learn how to get your API application key.'}" I have a key and how do i authorize it? and use it in my django template! Thanks in advance :) -
Django ContentTypes convert uuid field to integer field
I have a situation where object_id for ForeignKey accepts a PositiveIntegerField but all id's of my models are set as uuid . I looked up the documentation and found that i should use get_prep_value(value) or get_db_prep_value(value, connection, prepared=False)¶ The question is how should i exactly do it? Here is the code of model that contains the foreignRelation target_ct = models.ForeignKey(ContentType, blank=True, null=True, related_name='target_obj', on_delete=models.CASCADE) target_id = models.PositiveIntegerField(null=True, blank=True, db_index=True) target = GenericForeignKey('target_ct', 'target_id') created_at = models.DateTimeField(auto_now_add=True, db_index=True) Field from all other models id = models.UUIDField(default=uuid4, primary_key=True, editable=False) -
In the django templating language how to count the number of items of same type
I am trying to build a table that lists items that can be categorized by type. I can list out all the items and their types which are returned from my database in a table with no problems. That is in fact what I would like to do. Since these items can be categorized by type I see no reason to list the same type multiple times. The table is listed in order by category type so all items of the same type are already grouped together. In effect what I have is something along the lines of: /________________/ /|item A | category A|/ /|item B | category A|/ /|item C | category A|/ /|item D | category B|/ /|item E | category B|/ /|item F | category B|/ /------------------------/ what I actually would like see is /________________/ /|item A |```````````````|/ /|item B | category A|/ /|item C |_________|/ /|item D |``````````````|/ /|item E | category B|/ /|item F |_________|/ /-------------------------/ This can be done easily enough with a rowspan in the html. My issue the amount of rows to 'rowspan' is not known ahead. What I have in the Django template is: <table class="table table-sm"> <thead> <tr> <td scope="col">Col …