Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Default UserCreationForm does not show error if the passwords do not match
Using Default UserCreationForm from django.contrib.auth.forms does not show error if the passwords do not match. I do not want to create a custom model. Here is the code from my views.py file from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render # Create your views here. def register(response): if response.method == "POST": print(response.POST) form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: print(form.errors) form = UserCreationForm() return render(response,"register/register.html",{"form":form}) register.html code <html> <head> <title>Register </title> </head> <body> <h1>This is the Registration page</h1> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> </body> </html> I thought the message would be automatically displayed. Am I missing something? Edit: None of the error message are being displayed like password length < 8, all numeric passwords, etc. -
Can't access to public IP of django docker container
I can access the container with these curl commands: curl http://localhost:8000/api/health/ curl http://127.0.0.1:8000/api/health/ But I can't access it with public IP address: curl http://xx.xxx.xxx.xxx:8000/api/health/ curl: (7) Failed to connect to xx.xx.xxx.xxx port 8000 after 0 ms: Connection refused I used this command to run the container: docker container run -d --network=host -p 8000:8000 my-central-api Dockerfile has this line: CMD [ "python3", "manage.py", "runserver", "0.0.0.0:8000"] I am running this container on an EC2 instance. I set up the security group and NACL. So I think it is related to docker configuration. Why I can't access to port 8000 with public IP? -
When I make migrations I get this error, what could be the reason?
I cloned the repository. Then I added several fields to the model and wanted to add them to an existing database. I ran the makemigrations command and got this error -
Heroku adds whitespace characters to django template javascript code
I'm trying to combine python and javascript code in django template to update page after every keyup event (like in a browser). I have a list of teachers with name and surname which I want to display if it matches pattern given by the user. While everything is fine on localhost, after deploying on heroku there is a syntax error: Uncaught SyntaxError: Invalid or unexpected token Here is a fragment of my teacher.html file, where python teachers is QuerySet passed from views.py during rendering and str is a pattern taken from entry, earlier in javascript function get_names(str){ let teachers = []; {% for teacher in teachers %} var name = "{{teacher.name}}"; if (name.includes(str)) { teachers.push("{{teacher|safe}}"); } {% endfor %} return teachers; } Here is output of my localhost js code var name = "John"; if (name.includes(str)) { teachers.push("John Kowalski"); } And here is output of heroku server var name = "John"; if (name.includes(str)){ teachers.push("John Kowalski <-- Error occurs here "); } More interesting is the fact, that for some names it works, but mostly it doesn't. I needed to reset the database and uploaded the same data once again using heroku run python manage.py shell. Before that everything was fine, … -
How to add two form fields (one shown and one not) to a model field
I have a Spent model class that holds the name of where the user spent money at, how much, the reason as to why they spent, and a total amount spent. The total amount spent does not show up on the form in the template just the name, place and how much was spent (no need for the total amount to be shown). I'm having trouble figuring out how to update the total amount spent. I would like to have the total amount spent keep track of how much the user has spent in total. modles.py from django.db import models from django.contrib.auth.models import User class Bills(models.Model): name = models.CharField(max_length=25) amount = models.FloatField() due_date = models.DateField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Budget(models.Model): income = models.FloatField(default=0.00) budget = models.FloatField(default=0.00) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Spent(models.Model): name = models.CharField(max_length=25) amount = models.FloatField(default=0.00) reason = models.TextField(default="") total_spent = models.FloatField(default=0.00) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user.username forms.py from django import forms from .models import Bills, Budget, Spent class DateInput(forms.DateInput): input_type = 'date' class AddBillForm(forms.ModelForm): class Meta: model = Bills fields = ['name', 'amount', 'due_date'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter bill name'}), 'amount': … -
Django User does not update when saved?
I cannot get the default User model or my created Agent model to update. Below is my admin.py, forms.py, models.py, urls.py, views.py, and my edit_profile.html. I know it must be silly, but I've got three good days working on this. The HTML page tries to edit both the "EditProfileForm" and the "MoreInfoForm." The EditProfileForm uses the built-in User model, while the MoreInfoForm is my model that extends the built-in User model. As a note, the MoreInfoForm also contains an Image that I want to be able to update. When I submit the form, I get a POST request, but when I view the profile, it doesn't contain any changes. admin.py class AgentInline(admin.StackedInline): model = Agent can_delete = False verbose_name_plural = 'agent' class UserAdmin(BaseUserAdmin): inlines = (AgentInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) forms.py class RegisterUserForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) def __init__(self, *args, **kwargs): super(RegisterUserForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' class MoreInfoForm(forms.ModelForm): agent_phone_num = forms.CharField(max_length=10, required=True, help_text='Enter a 10 digit # without spaces or dashes', widget=forms.TextInput( attrs={'class': 'form-control'})) agent_mls = forms.CharField(max_length=6, required=True, help_text='Enter your 6 … -
Django - "return render(...)" doesn't work in a view that interacts with an ajax request
I want to solve this task: I click a button on the first page and after that my view creates a chat room and redirects me to the chat page. I decided to use ajax request for this task, but I have a problem, my view works until line return render(request, 'chat/chatroom.html'), the chat room is created, but the chat/chatroom.html page doesn't open, I don't understand why. I have no errors, the return render(request, 'chat/chatroom.html') line does nothing. My code: html <button type="submit" id="chat-button" value="{{advertisement.author.id}}">Write to the author</button> <script> $(document).on('click', '#chat-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "main_app:create-chat" %}', data: { send_to_id: $('#chat-button').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { }, error: function (xhr, errmsg, err) { } }); }) </script> views.py from django.contrib.auth import get_user_model from django.shortcuts import render, redirect, get_object_or_404 from django.db.models import Q from django.utils.decorators import method_decorator from django.views import View from django.views.decorators.csrf import csrf_exempt from chat.models import Thread User = get_user_model() @method_decorator(csrf_exempt, name='dispatch') class CreateChat(View): def post(self, request): send_to_id = int(request.POST.get('send_to_id')) send_to = User.objects.get(id=send_to_id) auth_user = request.user final_q = Q(Q(first_person=send_to) & Q(second_person=auth_user)) \ | Q(Q(first_person=auth_user) & Q(second_person=send_to)) thread = Thread.objects.filter(final_q) if not thread: Thread.objects.create(first_person=auth_user, second_person=send_to) return render(request, 'chat/chatroom.html') urls.py app_name … -
How do I can implement Follow/Unfollow system with CBV in Django?
I did a lot of attempts to create a following system. Who can describe in details how to implement this? My code shows a lot of errors. In AddFollower() and Remove follower() I get a profile I'm on and a current profile (my) and add or remove in database. But these functions don't work. Help me to find a solution, please urls.py path('add-follower/<int:id>/', AddFollower.as_view(), name='add_follower'), path('remove-follower/<int:id>/', RemoveFollower.as_view(), name='remove_follower') views.py class AddFollower(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): user = self.kwargs.get('user') profile = Profile.objects.get(user=user) profile.subscribers.add(request.user) return redirect('user-posts', id=profile.id) class RemoveFollower(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): user = self.kwargs.get('user') profile = Profile.objects.get(user=user) profile.subscribers.remove(request.user) return redirect('user-posts', id=profile.id) class GetUserProfile(ListView): model = Question template_name = 'blog/profile.html' queryset = Question.objects.all() def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Question.objects.filter(user=user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) profile = Profile.objects.get(user=user) followers = profile.subscribers.all() if self.request.user in followers: is_following = True else: is_following = False context['question_count'] = Question.objects.filter(user=user) context['post_count'] = Post.objects.filter(author=user) context['answer_count'] = Answer.objects.filter(user=user) context['profile_user'] = User.objects.get(username=user) context['is_following'] = is_following return context profile.html {% if profile_user.id == request.user.id %} <div class="buttons mt-3"> <a class="btn btn-dark px-4 ms-3" href="{% url 'profile' %}">Редактировать</a> </div> {% else %} {% if is_following %} <form action="{% url 'remove_follower' user.id … -
Django DateTimeField default not affecting Time
I am following an online tutorial on Django. Below is my Models script: from django.db import models from datetime import datetime class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published', default=datetime.now) def __str__(self): return self.tutorial_title and here is my admin script: from django.contrib import admin from .models import Tutorial # Register your models here. class TutorialAdmin(admin.ModelAdmin): fieldsets = [ ("Title/date",{"fields":["tutorial_title","tutorial_published"]}), ("Content", {"fields":['tutorial_content']}) ] admin.site.register(Tutorial, TutorialAdmin) My issue is that DateTimeField(default=) is just not working. I am absolutely unable to change the default time in tutorial published. No matter what I put in default, nothing changes. It's always 16:39:02. This isn't a time zone difference. I have no clue what is causing this. Any help would be greatly appreciated. -
random "relation "client_machine" does not exist" message
I have a big issue with my Django application. The application return an error 500 randomly. ProgrammingError at /dashboard/ relation "client_machine" does not exist LINE 1: ...t", "client_machine"."receive_publicity" FROM "client_ma... ^ I can spam any request, sometimes it's works, sometimes not. -
Forbidden (CSRF token missing or incorrect.) how to send CSRF token from frontend to backend?
I have a Django project, where I need to send a date string from frontend to backend. At frontend I am using the javascript fetch method async function getCustomerInDeliveryDate(deliveryDate : String) { const response = await fetch('getCustomerInTripDate', { method : 'POST', headers : { 'Content-Type' : 'application/json', }, body: JSON.stringify({ deliveryDate : deliveryDate }), }); return response } From Django backend I currently implemented a simple method that returns a string back to frontend class GetCustomerInTripDate(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): print('Backend received call from front end!!!!!!!!!!!!!') return JsonResponse({'data': ['hello', 'world']}, status = 200) The error that I receive when I try to send to backend is Forbidden (CSRF token missing or incorrect.): /staff/getCustomerInTripDate I am not sure how to send the csrf token. The research I have done so far all indicated that credentials should be set as "same-origin", and I have tried it but still get the same error. -
How do I create a user area system in Django? [closed]
I want to create a user area system so that each person can add a certain amount of users to their collection by purchasing a plan. For example, a user can add 10 people to their collection by purchasing a $10 plan. The user has the ability to display the people in his group -
custom pagination of limit and page in Django Rest Framework
I wanted to create custom paginations for this get_queryset. get_queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True).order_by('-created_on')[offset:offset+limit] I want to change the offset value whenever the page_no updates. Suppose someone enters page_no=1, so offset must be 0, and when enters 2, so offset should be 10, and so on. Every time page_no updates, it should update the offset value accordingly. like ?page_no=3: get_queryset = Comments.objects.filter(language_post_id=post_in_lang_id,is_post_comment=True).order_by('-created_on')[offset:offset+limit] # [ 20 : 20 + 10 ] -
How to display image file from sftp remote server in django template?
We have 2 servers. One of them is for media files and the other one is for django project server(ngnx+gunicorne). Our media server is local(internal). We want to access to media server from inside the project with sftp storage package which includes paramiko. we don't want to access media server via URL (http,https). HttpResponse(file, content_type=type) can display the image file as a big picture but we want to pass the image file to django template for display in html file like <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a> We know HttpResponse is not a good solution but we use it below code for explained our problem. # view def coursesPageView(request): courses = Course.objects.filter(is_published=True) image_data =[imageRespone(data) for data in courses] data = { 'published_courses_list':courses, 'images' : image_data } return render(request, 'pages/course2.html', data) def imageRespone(valid_image): if sfs.exists(valid_image.image.name): file = sfs._read(valid_image.image.name) type, encoding = mimetypes.guess_type(valid_image.image.name) response = HttpResponse(file, content_type=type) return response else: return HttpResponse('404 Not Found') #course2.html <a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a> -
Python was not found cmd
!one day before python manage.py runserver command successfully executed & give the IP address of Server]1 -
How can you omit empty django-filter params in url?
I am using django-filters to filter my queryset, I am wondering whether it is possible for the library to omit empty fields when generating a filtered URl. My URl would look like this: /?price=&producer=&price__gte=4&price__lte=&producer__name=&category__name=&o=-price And I want to achieve a cleaner one, using only non-empty filters: /?price__gte=4&o=-price filters.py class ProductFilter(django_filters.FilterSet): # price = django_filters.NumberFilter() price__gte = django_filters.NumberFilter(field_name="price", lookup_expr="gte") price__lte = django_filters.NumberFilter(field_name="price", lookup_expr="lte") vendor__name = django_filters.CharFilter(lookup_expr="icontains") category__name = django_filters.CharFilter(lookup_expr="icontains") o = django_filters.OrderingFilter( # tuple-mapping retains order fields=(("price", "price"),), # labels do not need to retain order ) class Meta: model = Product fields = ["price", "category", "vendor"] views.py class ProductListView(LoginRequiredMixin, ListView): model = Product ordering = ["-created_at"] def get_ordering(self): ordering = self.request.GET.get("ordering", "-created_at") return ordering def get_queryset(self, **kwargs): qs = Product.objects.exclude(status="HID").all() return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) f = ProductFilter(self.request.GET, queryset=self.get_queryset()) context["filter"] = f return context -
Trying to restrict items to a specific user in a Django Class Based View query set
I have the following models: class AccountManager(models.Model): account_manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return str(self.account_manager) class Client(models.Model): account_manager = models.ForeignKey(AccountManager, on_delete=models.CASCADE, related_name='account_manager_clients') client = models.CharField(max_length=255) def __str__(self): return self.client class Contract(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client_contracts') site_name = models.CharField(max_length=255) def __str__(self): return self.site_name I can restrict the clients to the specific account managers by using the following view class ClientListView(LoginRequiredMixin, ListView): model = Client template_name = "clients/list.html" def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(account_manager__account_manager=self.request.user) ) However I can't seem to restrict the contracts to the account manager with the following view: class AMContractDetailView(LoginRequiredMixin, DetailView): model = Contract template_name = 'contracts/am_contract_detail.html' def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(client__account_manager=self.request.user.id) ) This allows account managers to see all the clients not just their own. I know I am doing something fundamentally wrong but have got a bit lost! Any help would be appreciated. -
Run local NGINX web app on HTTPS without domain name
I'm developing a django web app which runs on a gunicorn-nginx local server. I've followed this digitalocean guide to setup the web app but I don't understand how to create a ssl certificate and use it without having a domain name. I've found a lot of guides but none of them specify how to enable HTTPS without a domain and using a local IP. How can I make this happen? -
why Django showing object has no attribute?
Hope you are doing well, i am beginner to the django and python, encountered the error while practicing which is on REST API FRAMEWORK of DictField . i took an example on DictField. I have posted a code below please have a look. feel free to ask if you have any questions. please solve the issue. Thanks a lot for your help. app1/serializers.py from rest_framework import serializers class Geeks(object): def __init__(self, dictionary): self.dict = dictionary class GeeksSerializer(serializers.Serializer): dictionary = serializers.DictField() child = serializers.CharField() python manage.py shell >>> demo = {} >>> demo['name'] = "Naveen" >>> demo['age'] = 21 >>> obj = Geeks(demo) >>> serializer = GeeksSerializer(obj) >>> serializer.data Error: Traceback (most recent call last): File "rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "rest_framework\fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'Geeks' object has no attribute 'dictionary' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "rest_framework\serializers.py", line 555, in data ret = super().data File "rest_framework\serializers.py", line 253, in data self._data = self.to_representation(self.instance) File "rest_framework\serializers.py", line 509, in to_representation attribute = field.get_attribute(instance) File "rest_framework\fields.py", line 490, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting … -
Add group and permission to group with migration django
i have problem with groups and permission in django. I want to create a group of users and admin. In django panel admin i see permission which i need: app | user | Can add user app | user | Can change user app | user | Can delete user app | user | Can view user I need create group "user" and "admin" then add perm to user "Can view user" and to admin all this perms and this is need to do with migration. My already code i suposed is totally stupid # Generated by Django 4.0.3 on 2022-09-11 10:33 from django.db import migrations, transaction from django.contrib.auth.models import Group, Permission def add_group_permissions(a,b): group, created = Group.objects.get_or_create(name='user') try: with transaction.atomic(): group.permissions.add(can_view_user) group.save() except InterruptedError: group.delete() class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.RunPython(add_group_permissions), ] If anyone can help, i need that. -
How can I add uuid to url in urls.py django?
I have django app with authentication in it and email verification. When user is created activation email is sent with link inside of it, when user clicks this link is doesn't take him nowhere. views.py class customer_register(CreateView): model = User form_class = CustomerSignUpForm template_name = 'authentication/customer_register.html' def form_valid(self, form): user = form.save() user.token = str(uuid.uuid4()) subject = 'Verify your account | Zane' message = f"http://127.0.0.1:8000/accounts/verify/{user.token}/" recipient_list = [user.email] send_mail( subject, message, 'from@example.com', ['to@example.com'], fail_silently=False, ) return redirect('/') def activate(request, token): try: obj = models.User.objects.get(email_token = token) obj.signup_confirmation = True obj.save() return HttpResponse('Your account is verified') except Exception as e: return HttpResponse('Invalid token') urls.py path('verify/<uuid:pk>/', views.activate, name='activate'), models.py ... token = models.CharField(max_length=200, blank=True) signup_confirmation = models.BooleanField(default=False) I wonder what do I need to put in my url to trigger my function? -
Django serializer test post of file with user information
I try to test a file upload like this: def test_this(self, api_client, login_as): user = login_as('quality-controller') url = reverse('icsr-list') organization = Organization(name="test") organization.save() data = { "organization": organization.id, "import_file": FileGenerator.generate_text_file('txt'), "user": { "id": user.id, "username": user.username, } } response = api_client.post(url, data, format='json') But I receive the following error message: b'{"import_file": ["The submitted data was not a file. Check the encoding type on the form."]}' I also tried to use: format='multipart' but then I receive the following error: AssertionError: Test data contained a dictionary value for key 'user', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. How can I solve this? -
django.urls.exceptions.NoReverseMatch: Reverse for 'login_otp' not found. 'login_otp' is not a valid view function or pattern name
I have created a Django application where I have created a custom user model and using login through otp. I want to send the otp on email. I am geeting the error - "django.urls.exceptions.NoReverseMatch: Reverse for 'login_otp' not found. 'login_otp' is not a valid view function or pattern name." Not able to solve this one. Following is my model-: User = get_user_model() class S_Society_Association_Master(AbstractBaseUser): member_id = models.CharField(verbose_name = "Member_ID", primary_key=True, max_length=100, unique=True) member_name = models.CharField(verbose_name = "Member Name", max_length=100) password = models.CharField(verbose_name = "Password", default=NULL, max_length = 100, null=True, blank=True) member_contact_number = models.CharField(verbose_name="Phone Number", max_length=15) otp = models.CharField(max_length=6, blank=False, default=0) # For HOTP Verification member_role = models.CharField(verbose_name="Member's Role", max_length=100, choices=[("P", "President"), ("T", "Treasurer"), ("S", "Secretary"), ("EC", "EC members"), ("O", "Other members")]) member_email_id = models.EmailField(verbose_name = "Member's Email", max_length=100) member_from_date = models.DateField(verbose_name = "Member From", auto_now_add=True) member_to_date = models.DateField(verbose_name="Member To") created_date = models.DateField(verbose_name = "Created Date", auto_now_add = True, blank=True, null=True) created_by = models.ForeignKey(User, to_field='id', related_name = "assoc_created_by", on_delete = models.SET_NULL, verbose_name="Created By", max_length=100, blank=True, null=True) last_updated_date = models.DateField(verbose_name = "Updated Date", auto_now = True, blank=True, null=True) last_updated_by = models.ForeignKey(User, to_field='id', related_name = "assoc_updated_by", on_delete = models.SET_NULL, verbose_name="Last Updated By", max_length=100, blank=True, null=True) USERNAME_FIELD = 'member_email_id' Following is my views.py-: def … -
Django raise BadRequestError(msg) razorpay.errors.BadRequestError: The amount must be an integer. while refund
When I try to print it, it appears as an integer, but I get an error saying "The amount must be an integer." when I run the project if str(Payments).__contains__("pay"): paymentId = Payments.payment_id amount = int(Payments.amount_paid) refund_amount = int(amount) * 100 reamount = int(refund_amount) print(reamount) print(type(reamount)) client = razorpay.Client(auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) client.payment.refund( paymentId, { "amount": reamount, "speed": "optimum", }, ) # addning stock in product order_items = OrderProduct.objects.filter(order=order) for item in order_items: product = Product.objects.get(id=item.product_id) product.stock += item.quantity product.save() -
Not able to install viewflow-pro
i want to work with viewflow rest. I have my requirements.txt as django==2.2.25 djangorestframework==3.11.2 django-rest-swagger==2.2.0 django-viewflow-pro==1.4.1 django-material-pro==1.4.1 pyaml==20.4.0 celery==5.2.2 coreapi==2.3.3 I ran pip install -r requirements.txt. But it gives me error ERROR: Could not find a version that satisfies the requirement django-viewflow-pro==1.4.1 (from versions: none) ERROR: No matching distribution found for django-viewflow-pro==1.4.1 How can i use viewflow.rest package in my prject?