Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
tr:nth-child(even) not working with xhtml2pdf
I'm trying to add a background color to even rows in a table in HTML. I'm using xhtml2pdf to convert the html to pdf to serve with a django backend. The styles on the even rows don't seem to be working <html> <head> <style type="text/css"> tr:nth-child(even) { background-color: blue; } </style> </head> <body> <main> <table> <thead> <tr> <th>Heading/th> <th>Heading</th> <th>Heading</th> </tr> </thead> <tbody> {% for result in data.results %} <tr> <td>{{result}}</td> <td>{{result}}</td> <td>{{result}}</td> </tr> {% endfor %} </table> </main> </body> </html> -
how to show month fields with Salesmen commission in ordering product
serializer.py[view.py]|(https://i.stack.imgur.com/sSfir.png)[error]|(https://i.stack.imgur.com/UObDc.png) how to show month fields with order -
model form doesn't render form again when form is not valid
I added Min and Max Value validators to my Django model and then when I enter a value out of this range, instead of rendering form again,it raises a value error. ValueError: The view cars_form.views.rental_review didn't return an HttpResponse object. It returned None instead. [14/Jan/2023 21:44:50] "POST /cars_form/rental_review/ HTTP/1.1" 500 74599 It should be HTTP/1.1" 200 This is my Code models.py: from django.db import models from django.core.validators import MinValueValidator,MaxValueValidator class Review(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) forms.py : from django import forms from .models import Review class ReviewForm(forms.ModelForm): class Meta: model = Review fields = "__all__" views.py: from django.shortcuts import render,redirect from django.urls import reverse from .forms import ReviewForm def rental_review(request): if request.method=='POST': form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('cars_form:thank_you')) # my template else: form = ReviewForm() # making an object return render(request,'cars_form/rental_review.html',context={'form':form}) if the form is not valid it must go on else statement but it doesn't and idk why. -
Doesn't "__str__()" work properly in "admin.py" for Django Admin?
For example, I define __str__() in Person model as shown below: # "models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): # Here return self.first_name + " " + self.last_name Then, I define Person admin as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): pass Then, the full name is displayed in the message and list in "Change List" page: But, when I define __str__() in Person admin as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def __str__(self): # Here return self.first_name + " " + self.last_name Or, when I define __str__() then assign it to list_display in Person admin as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ('__str__',) # Here def __str__(self): # Here return self.first_name + " " + self.last_name The full name is not displayed in the message and list in "Change List" page: So, doesn't __str__() work properly in Person admin? -
Django filter by related field with annotating the last added items
I have one model with two foreignkeys my model : class Price(models.Model): part= models.ForeignKey(Part, on_delete=models.CASCADE, null=True, blank=True) seller = models.ForeignKey(Seller, on_delete=models.CASCADE, null=True, blank=True) price = models.FloatField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True, null=True, blank=True) I have 4 vendors [seller], each [item] has an unlimited price history [price\date] that gets added every day individually. I need the right query to get : [Latest price ordered by date for each seller per item] So the query should return only 4 items Example : qs = Price.objects.values('part__name', 'seller__name').annotate(new_price=Max('date')) result : <QuerySet [{'part__name': 'NGK 3951 Pack of 8 Spark Plugs (TR55)', 'seller__name': 'Amazon', 'new_price': datetime.date(2023, 1, 14)}, {'part__name': 'NGK 3951 Pac k of 8 Spark Plugs (TR55)', 'seller__name': 'Carid', 'new_price': datetime.date(2023, 1, 14)}, {'part__name': 'NGK 3951 Pack of 8 Spark Plugs (TR55)', 'seller__nam e': 'Ebay', 'new_price': datetime.date(2023, 1, 14)}, {'part__name': 'NGK 3951 Pack of 8 Spark Plugs (TR55)', 'seller__name': 'Rockauto', 'new_price': datetime.dat e(2023, 1, 14)}]> Is the corrent qs but i can't access [price] field, if you include it in values the qs returns more than 4 results. -
How to deploy a pywebio application using Flask, (so that I can deploy in websites like heroku etc)
I have my pywebio application running on localhost. ` import openai import pyperclip from pywebio.input import * from pywebio.output import * from pywebio.session import * from pywebio.pin import * import pywebio openai.api_key = "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" def home(): put_image('https://upload.wikimedia.org/wikipedia/commons/4/4d/OpenAI_Logo.svg',width='50%',height='50%') evenorodd() def evenorodd(): engines_dict={"text-davinci-003":3200, "text-curie-001":1600, "text-babbage-001":1600, "text-ada-001":1600} myinp=input_group("ASK GPT-3",[ input("", placeholder='Enter any question', required=True,help_text="",name="question"), radio("Choose an engine",name="engine", options=["text-davinci-003", "text-curie-001", "text-babbage-001", "text-ada-001"],required=True)]) put_text(myinp["question"]).style('color: green; font-size: 20px;font-weight: 600; padding-top:20px') with put_loading(shape='grow',color='success'): response = openai.Completion.create( engine=myinp["engine"], prompt=myinp["question"], temperature=0.5, max_tokens=engines_dict[myinp["engine"]], top_p=1, frequency_penalty=0, presence_penalty=0 ) toast("Success") put_button("copy",onclick=lambda:(toast("Copied"),pyperclip.copy(response.choices[0].text)),color='success',outline=True).style('float: right') put_text(response.choices[0].text).style('background-color: rgb(240, 240, 240);padding: 10px;border-radius: 8px;') put_button("Ask another Question",onclick=evenorodd).style('position: relative;bottom: 0') pywebio.start_server(home,port=90, debug=True) ` How to convert this into Flask and deploy ?? I tried to search on net but they are rendering various templates in Flask. Help me with this I tried running on my localhost, but many errors are occurring. Anyone help me with this. -
Can I set a models.imageURL as background image in a html container?
I'm trying to create a blog on Django in my learning process and I was wondering if it's possible to use a models.imageUrl as a background image for a post template. I'm not even sure it's possible to do so, is it? thanks in advance! this is my styles code insinde my html div: <div class="showcase" style="background-image: url(/static/media/image.jpeg); background-size: cover; background-position: center; padding: 140px;"> -
command docker-compose build
how fix this problem docker run as administrator, containers works, but command @docker-compose build@ nope error - acces is denied (i working pycharm) I tried to run Linux through ubuntu and immediately thought that the problem was in the docker, so I surfed the Internet for a long time in search of a solution to the problem, but I did not find it -
Setup multiple private repositories cpanel
How can I setup access for multiple private repositories in Cpanel? I've tried many tutorials and documentation. Here is one of them: https://docs.cpanel.net/knowledge-base/web-services/guide-to-git-set-up-access-to-private-repositories/ But I'm always got this error: Permission denied (publickey). fatal: Could not read from remote repository. It seems like we can only use the default name (id_rsa). I've tried this code: ssh-keygen -t rsa -b 4096 -C "username@example" It works fine. But it will generate the default (which is id_rsa). This means that we can't deploy multiple private repos, right? Because we can only use "id_rsa". So is it possible to create an ssh key without a default name? Also, how to create multiple private repos in Cpanel? -
don't show images in django crud
don't show images in django crud this is the html view and models tanks for help enter image description here <tbody> {% for emp in employees %} <tr> <th scope="row">{{ emp.emp_name }}</th> <td>{{ emp.emp_email }}</td> <td>{{ emp.emp_contact }}</td> <td>{{ emp.emp_role }}</td> <td>{{ emp.emp_salary}}</td> <td> <a style="margin-right: 30px;" href="{% url 'edit-employee' emp.id %}">EDITAR</a> <a href="{% url 'delete-employee' emp.id %}">ELIMINAR</a> </td> <td> {%if venue.venue_image%} {{venue.venue_image.url}} {%endif%} </td> </tr> {% endfor %} </tbody> class Employee(models.Model): emp_name = models.CharField(max_length=200) emp_email = models.EmailField() emp_contact = models.CharField(max_length=20) emp_role = models.CharField(max_length=200) emp_salary = models.IntegerField() venue_image = models.ImageField(null=True, blank=True, upload_to="images/") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.emp_name i want put a image here enter image description here -
The 'image' attribute has no file associated with it. Django serilizer
this is my code class Brand(models.Model): name = models.CharField(max_length=255) logo = models.ImageField(upload_to=generate_filename_brand_image) #over write add_to_explore = models.BooleanField(default=False) def __str__(self): return self.name class Item(models.Model): brand = models.ForeignKey('core.Brand', on_delete=models.CASCADE, null=True ,blank=True) class ItemSerializers(serializers.ModelSerializer): brand_logo = serializers.CharField(source='brand.logo.url') class Meta: model = Item fields = ['id','brand_logo'] if image None I got this erorr The 'image' attribute has no file associated with it. How to handel this erorr -
save file in media folder on server django
so i´ve created a pdf document which should be saved in media/postings. the path is already in the function, but the pdf is not saved there but in the main project folder. what did i overlook here? a little explanation for the def: the post is created and uploaded to the feed, while the image in the post is renamed and put into another folder. Also, a pdf is created, containing the posted material. How do i determine where this pdf goes on the server? i thought it is solved with the path_name and path_file but it doesn't work. thanks in advance. def post_create(request): if request.method == 'POST': form = PostCreateForm(request.POST, request.FILES) if form.is_valid(): form.cleaned_data['num_post'] = Post.objects.count() + 1 Post.objects.create(**form.cleaned_data) else: form = PostCreateForm() return render(request, 'index.html', {'form': form}) def upload(request): if request.method == 'POST': image = request.FILES.get('image_upload') caption = request.POST['caption'] num_post = Post.objects.count()+1 new_post = Post.objects.create(image=image, caption=caption, num_post=num_post) new_post.save() #create pdf buffer = io.BytesIO() x_start = 100 y_start = 10 folder_path = f"media/postings/post{num_post}.pdf" folder_name = os.path.basename(folder_path) print(folder_path) p = canvas.Canvas(folder_name, pagesize=A4,) #p == request.FILES.get('postings') p.drawImage(ImageReader(image.file), x_start, y_start, width=420, preserveAspectRatio=True, mask='auto') p.drawString(150, 650, new_post.caption) p.drawString(100, 650, "caption:") p.drawString(100, 170, str(new_post.created_at)) p.drawString(200, 700, str(num_post)) p.drawString(100, 700, "post no.:") p.drawString(250, 700, "//") … -
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type double precision: "max"
I changed the data type of a field "max" in my model from text to float and I got this error when I run python3 manage.py migrate after makemigrations. What's the solution please? Running migrations: psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type double precision: "max". The above exception was the direct cause of the following exception: django.db.utils.DataError: invalid input syntax for type double precision: "max my original model: class calculation(models.Model): fullname = models.TextField(blank=True, null=True) min = models.TextField(blank=True, null=True) max = models.TextField(blank=True, null=True) unit = models.TextField(blank=True, null=True) my model after the change:: class calculation(models.Model): fullname = models.TextField(blank=True, null=True) min = models.FloatField(blank=True, null=True) max = models.FloatField(blank=True, null=True) unit = models.TextField(blank=True, null=True) -
Django channels websockets. How send notification specific user
Now everything works like this: the sender of the notification goes into the profile of the one to whom the notification will be sent. A button is pressed, a websocket connection is started, a name is obtained from the button or URL, and based on this, a notification is created in the database, after which this notification should be displayed to the one to whom the notification was sent. But I have a problem, the notification is displayed for everyone. I don't understand how to add a recipient to a group. I will be glad to help! consumers.py @database_sync_to_async def get_user(username): try: return User.objects.get(username=username) except: return AnonymousUser() @database_sync_to_async def create_notification(receiver, sender, typeof="task_created", status="unread"): notification_to_create = Notifications.objects.create(user_revoker=receiver, user_sender=sender, type_of_notification=typeof) print('Уведомление создано') return notification_to_create.user_revoker.username, notification_to_create.type_of_notification @database_sync_to_async def create_or_get_group(user_receiver): Group.objects.get_or_create(name='notifications') my_group = Group.objects.get(name='notifications') my_group.user_set.add(user_receiver) class NotificationConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): # self.group_name = f'notifications_for_{self.scope["user"].username}' self.group_name = 'notifications' await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() # @database_sync_to_async async def websocket_receive(self, event): data_to_get = json.loads(event['text']) user_receiver = await get_user(data_to_get['receiver_username']) user_sender = await get_user(data_to_get['sender_username']) get_of = await create_notification(user_receiver, user_sender) channel_layer = get_channel_layer() await create_or_get_group(user_receiver) await self.channel_layer.group_add( self.group_name, self.channel_name, ) await (channel_layer.group_send)( self.group_name, { "type": "send_notification", "value": get_of[0], } ) async def send_notification(self, event): await self.send(json.dumps({ "type": "notifications", "data": … -
Phaser & Django: Place canvas inside div
I'm trying to embed a Phaser game into a Django application, but struggling with the most basic of operations to get started: Making sure the canvas is placed inside a particular div as to center it on the middle of the page. From what I could gather, for this to work, I should simply specify the parent div. However, whenever I specify the parent div, the canvas is nowhere to be found. When I leave out the line again, it reappears, but outside the layout. {% extends "app/layout.html" %} {% block content %} <h2>{{ title }}.</h2> <h3>{{ message }}</h3> <div id='phaser-canvas'></div> {% endblock %} <script> var config = { type: Phaser.AUTO, width: 800, height: 600, parent: 'phaser-canvas', scene: { preload: preload, create: create, update: update } }; var game = new Phaser.Game(config); function preload() { } function create() { } function update() { } </script> What am I not understanding? -
How to display values in multiple lines by indentation in Django Admin?
I put \n between obj.first_name and obj.last_name as shown below to display first name and last name separately in 2 lines by indentation: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ('person',) def person(self, obj): # ↓↓ Here return obj.first_name + "\n" + obj.last_name But, first name and last name were displayed in one line without indentation as shown below: John Smith # One line So, how can I display first name and last name separately in 2 lines by indentation as shown below: John # 1st line Smith # 2nd line -
Django-tables2 with SingleTableMixin fails to retrieve table or queryset
Receiving error "Expected table or queryset, not str" Trying to display queryset as table. But unable to. Views.py class EntriesTableView(LoginRequiredMixin, SingleTableMixin): table_class = entryTable table_data = Entries.objects.annotate(row_number=models.Window( expression=RowNumber(), order_by=[models.F('id').desc()], )).order_by('row_number') # model = Entries context_table_name = "table" paginate_by = 15 def get_template_names(self): if self.request.htmx: template_name = "partials/entries_list.html" else: template_name = "entries.html" return template_name relative tables.py class entryTable(tables.Table): class Meta: model = Entries template_name = 'django_tables2/bootstrap.html' template(entries.html) ............... {% include "partials/accomodations_list.html" %} ............ template (partials/entries_list.html) Error is highlighted in the below template on line 2. {% load render_table from django_tables2 %} {% render_table table %} Django version - 4.1.3 Django-tables2 version - 2.5.1 And the model Entries do have data. -
django.db.utils.DataError: invalid input syntax for type double precision: “max”
I changed the data type of a field "max" in my model from string to float and I got this error when I run python3 manage.py migrate after makemigrations. What's the solution please? django.db.utils.DataError: invalid input syntax for type double precision: "max -
Django translation doesn't create or compile new .po files
I am creating REST API with Django Rest-FrameWork. While working with translation, the command compilemessages doesn't work as docs, it does not create .po files from my local folder, even though I have tried the command makemessages. When I open the locale folders which conatian .po files, the translation does not appear there. But even though after changing local (incorrect folder name) directory in setting.py, it does not hurt the two commands above. And addition how can I find where the actual problem? -
Why does import in Django not work when online. It is highlighted with white, not green, as locally, like it is not recognized
In my urls.py: from . import views The dot and views are white(grey) like it is not recognized. The same problem is in views.py: from .forms import PostForm from .forms import ServiceForm from .forms import BlogForm from .forms import CategoryForm from .models import Post from .models import Service from .models import Blog from .models import Image from .models import Category They are all white/grey, but must be green, when recognized. The forms.py, models.py, views.py and urls.py are located in the same folder. It is an app folder. It has started to be after I uploaded it online. Please let me know what do I do wrong? Thanks. -
How do I check if Django is ruuning with subprocess?
I want to run Django server with subprocess. Here is my code: import subprocess import os def run_BackServer(): current_dir = os.getcwd() target_dir = os.path.join(current_dir, 'marketBack/BackServer') os.chdir(target_dir) process = subprocess.Popen(['python', 'manage.py', 'runserver'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) output, error = process.stdout.read(), process.stderr.read() print(output, error) run_BackServer() I think the Django server is running well. However, when I want to check it, I can't seem to get the output because the process has not finished technically. Is there any way I can check if the server is running? -
Reverse for 'profile/{{user.username}}' not found. 'profile/{{user.username}}' is not a valid view function or pattern name
{% if user.is_authenticated %} <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'profile/{{user.username}}' %}">Profile</a></li> <li><a href="{% url 'settings' %}">Settings</a></li> <li><a href="{% url 'logout' %}">Logout</a></li> {% endif %} <li><a href="{% url 'profile/{{user.username}}' %}">Profile</a></li> Here I can't use this Django format to redirect at user's profile page but if do it like <li><a href='/profile/{{user.username}}'>Profile</a></li> I can use this way. Why I am not able to use Django url? urlpatterns = [ path('', views.index, name='index'), path('home', views.home, name='home'), path('likes', views.likes, name='likes'), path('login', views.login, name='login'), path('follow', views.follow, name='follow'), path('search', views.search, name='search'), path('about', views.aboutus, name='about'), path('signup', views.signup, name='signup'), path('upload', views.upload, name='upload'), path('logout', views.logout, name='logout'), path('settings', views.settings, name='settings'), path('profile/<str:pf>', views.profile, name='profile'), ] here is my url patterns. -
how to link m3u8 file to HTML
I wonder how to link a m3u8 file I downloaded and opened in VLC (its live broadcast). it looks like HTML cannot read this type of files,, its not a link its a file when I opens it it shows a live broadcast for a football match for example... please if anyone can help me just to show the video on html page, aim using a Django framework. I tried to link the video file by {% load static %} from the header then i put the video file inside static/img folders, then i linked the video folder by doing this: -
How can i show error message for the user when using Email already exists
I'm using the Django framework. And I'm attempting to show an error message when the user registers and uses the username and/or email that already exists on a website. But the problem is when a user registers a new username and email, the system is not registered in a database. How can solve this problem? forms.py : class RegisterUserForms(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] widgets = { 'email':forms.EmailInput(attrs = { 'required' : True, 'placeholder' : 'Email@example.com', 'autofocus' : True, 'name':'email', }), 'username':forms.TextInput(attrs = { 'required' : True, }) } def __init__(self, *args, **kwargs): super(RegisterUserForms, self).__init__(*args, **kwargs) self.fields['password1'].widget.attrs={'placeholder': 'Password from numbers and letters of the Latin alphabet'} self.fields['password2'].widget.attrs={'placeholder': 'Password confirmation'} def clean_username(self): username_input = self.cleaned_data.get('username') if User.objects.filter(username=username_input ).exists(): raise forms.ValidationError("username already exists!") def clean_email(self): email_input = self.cleaned_data.get('email') if User.objects.filter(email=email_input).exists(): raise forms.ValidationError("email already exists!") views.py: def registerpage(request): form = RegisterUserForms() if request.method == 'POST': try: form = RegisterUserForms(request.POST) if form .is_valid(): user = form.save() login(request, user) return redirect('login') except Exception as e: print(e) raise context = { # dictionary 'form': form } return render(request, r'user\register.html', context) register.html : <body> <div class="page register-page form" style="text-align: right;" > <h2 class="title">register</h2> <form method="POST" class="register-form"> {% csrf_token %} <div class="fieldWraber"> <label for="{{form.email.id_for_label}}"> Email … -
Django allauth overriding DefaultSocialAdapter
Project's backend and frontend are separate and trying to implement provider login via google. in settings.py LOGIN_REDIRECT_URL = "http://localhost:3000" SOCIALACCOUNT_ADAPTER = "users.adapter.CustomOAuth2Adapter" in adapter.py class CustomOAuth2Adapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form): user = sociallogin.user user.is_active = True user.save() token = Token.objects.create(user=user) response = HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) response.set_cookie('auth_token', token) return response def pre_social_login(self, request, sociallogin): try: user = User.objects.get(email=sociallogin.user.email) user.is_active = True user.save() request.set_cookie('auth_token', request.user.auth_token.key, domain=settings.LOGIN_REDIRECT_URL) # sociallogin.connect(request, user) # return response except: pass there is one main problem here. when login or save has success trying to redirect from backend to frontend. It's using LOGIN_REDIRECT_URL and works. but when it's redirecting I try to set token into cookie. but it doesn't set. # this part of code is not working correctly. request.set_cookie('auth_token', request.user.auth_token.key, domain=settings.LOGIN_REDIRECT_URL) Additionally I tried to set cookie like below. def pre_social_login(self, request, sociallogin): try: user = User.objects.get(email=sociallogin.user.email) user.is_active = True user.save() # sociallogin.connect(request, user) response = HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) response.set_cookie('auth_token', request.user.auth_token.key, domain=settings.LOGIN_REDIRECT_URL) return response except: pass but this doesn't worked either. when backend and frontend are separate how to send token with redirection.