Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django periodic task celery
I'm a newbie in Django and Celery. Help me please, I can't understand, how it work. I want to see in my console "Hello world" every 1 min. tasks.py from celery import Celery from celery.schedules import crontab from celery.task import periodic_task app = Celery('tasks', broker='pyamqp://guest@localhost//') @periodic_task(run_every=(crontab(hour="*", minute=1)), ignore_result=True) def hello_world(): return "Hello World" celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test.settings.local") app = Celery('test') app.config_from_object('celeryconfig') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app celeryconfig.py broker_url = 'redis://localhost:6379' result_backend = 'rpc://' task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] timezone = 'Europe/Oslo' enable_utc = True It's a simple celery settings and code, but doesn't worked =\ celery -A tasks worker -B And nothing happens. Tell me what am I doing wrong? Thank you! -
Incorrect redirect to user profile details
If the user is a staff' member he will see the list of users and their profile details, in addition to his profile details. If not, he will see only his profile details. models.py class UserProfile(AbstractUser): def __str__(self): return self.username def get_absolute_url(self): return reverse("user_details", kwargs={"username":self.username}) views.py def usersList(request): """ The list of all users """ if request.user.is_superuser: users_list = UserProfile.objects.all() elif request.user.is_staff: users_list = UserProfile.objects.filter(is_staff=False) else: raise PermissionDenied template = 'usermanager/users_list.html' context = { 'users': users_list, } return render(request, template, context) def userDetails(request, username): """ User details """ user_details = get_object_or_404(UserProfile, username=username) template = 'usermanager/user_details.html' context = { 'user_details': user_details, } return render(request, template, context) urls.py path('user-list/', views.usersList, name='users'), path('<username>/', views.userDetails, name='user_details'), template.html {% for user in users %} <h1>{{ user.username }}</h1> <p>Name: {{ user.first_name }}</p> <p>Surname: {{ user.last_name }}</p> <p>Email: {{ user.email }}</p> {% if request.user.is_superuser %} {% if user.is_staff %} <button class="btn btn-warning">Staff</button> {% else %} <button class="btn btn-primary">User</button> {% endif %} {% endif %} <a class="btn btn-danger" href="{% url 'user_details' username=userprofile.user.username %}">Details</a> <hr> {% endfor %} I can see correctly the list of all users. Bob is one of my user, if I click on his details I see my personal profile. This happen for all of … -
Security with google maps API key
first post on here. I have a google maps API in a window on my Django site which functions when the API is directly in the script src however for security I have set the API key as an environment variable but I am greatly struggling to set this up into the src link. I have attempted all possible solutions I have found with no luck. Thanks for any suggestion! -
Django REST Framework validation function has different signature than Django models?
I'm developing a reservation system REST api in Django with a relatively simple model that will determine if a user has a valid membership in order for them to reserve a certain item. When creating a reservation, I have a simple validator written like this: def validate_member(value): """ Validator for a user in a reservation. Will throw a ValidationError if the user does not have an updated membership. """ if not valid_membership(value): raise ValidationError("User does not have a valid membership!") This validation is run on the foreign key field in the reservation table, which is written as such: # The gear item in the reservation gear_item = models.ForeignKey(Entry, on_delete=models.SET_NULL, null=True, help_text="The gear item being reserved.", validators=[validate_entry] ) The serializer for this model is written as a ModelSerializer, like such: class ReservationSerializer(serializers.ModelSerializer): class Meta: model = Reservation fields = "__all__" This design works fine for queries in the REST API, but fails for any modifications in the admin console, with the error: 'int' object has no attribute 'rentable' It seems that validating a foreign key in the admin console passes the primary key integer into the value parameter of the validation function, while the REST API passes in the entire object. …