Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Vs code and py charm
Pls can I run my django on pycharm and run my HTML and CSS on vs code to build a web application if yes how do I link them together I tried installing the python extension on my vs code but it didnt work kept given me errors so I opted for pycharm to do my python -
Categories in blog
I need to put a categories in my blog website (python django)... I tried some ways but however I try, I either get error or blogs don't show in their categories Can someone help, what should I do? How to make this work -
Generate QR Code to URL with variable (page/pk_ID)
I am trying to generate a QR code that is unique to the page_id. The aim is to send a user that is not request.user to a specific page (loyalty_card/UserProfile_ID). As an example: site/loyaltycard/UserProfile_1 - would have qr code leading to site/pageID_1 site/loyaltycard/pageID_2 - would have qr code leading to site/pageID_2 here is where I am at. from io import BytesIO from qrcode.image.svg import SvgImage @login_required def venue_loyalty_card(request, userprofile_id): profile = UserProfile.objects.filter(user=userprofile_id) itemised_loyalty_cards = Itemised_Loyatly_Card.objects.filter(user=userprofile_id) factory = qrcode.image.svg.SvgImage stream = BytesIO() qrcode_url = "doopee-doo.herokuapp.com/account/" + str(userprofile_id) + "/" qrcode_img = qrcode.make(qrcode_url, image_factory=factory, box_size=10) qrcode_img.save(stream) return render(request,"main/account/venue_loyalty_card.html", {'itemised_loyalty_cards':itemised_loyalty_cards, 'profile':profile,'qrcode_url':qrcode_url,'qrcode_img':qrcode_img}) template {{qrcode_img|safe}} url path('loyalty_card/<userprofile_id>', views.venue_loyalty_card,name="venue-loyalty-card"), Current error message on console: ValueError: Field 'id' expected a number but got '<qrcode.image.svg.SvgImage'. -
unable to substract two timefeild in django
Hi Team i have models as below. And i am trying to substract out time and in time . class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1,related_name='Attendance') attendance_date = models.DateField(null=True) in_time = models.TimeField(null=True) out_time = models.TimeField(null=True ,blank=True) totaltime = models.TimeField(null=True ,blank=True) def __str__(self): return str(self.employee) + '-' + str(self.attendance_date) @property def totaltime(self): FMT = '%H:%M:%S' currentDate = date.today().strftime('%Y-%m-%d') sub = datetime.strptime('out_time', FMT) - datetime.strptime('in_time', FMT) return sub Still getting and error : ValueError: time data 'out_time' does not match format '%H:%M:%S' Please advise what should i do I am expecting how i will substract two timefeild -
how i can create input location in template django without create field for location
i want to determine location in template django without create field and model for location just show the box location and determine location and input lat & long in text {% elif field.field.field_type == 'location' %} <div class=""> <input type="text" name="{{ field.field.slug }}" maxlength="255" class="textinput textInput form-control" required="" id="{{ field.field.slug }}"> </div> -
auth_user table created alongside accounts_user table in postgres(Django)
Using: class User(AbstractBaseUser): pass #models here I added extra fields to my custom user model. This table is created successfully in postgres with absolutely no issues, however, whilst creating a superuser the credentials gets pushed to auth_user(default django user table) instead of account_user. auth_user shouldn't even be created alongside accounts_user?! Even worse: REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] which I set isn't required at all when creating superuser. It still uses default django configurations/fields. These are in order if you're wondering: AUTH_USER_MODELS = 'accounts.User' and installed 'accounts' in INSTALLED_APPS=[ ]. What is happening? Superuser credentials should be created in accounts_user table not auth_table in postgreSQL. REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] should be requested whilst creating superuser. -
DJANGO 'WSGIRequest' object has no attribute 'get'
I get this error 'WSGIRequest' object has no attribute 'get' in my code Below is my function in views.py def user_attendance(request): # Get the attendance records for the current user attendance_records = Attendance.objects.filter(user=request.user) # Create a form instance form = CompensationRequestForm() # Check if the form has been submitted if request.method == 'POST': # Bind the form with the POST data form = CompensationRequestForm(request.POST) # Check if the form is valid if form.is_valid(): # Save the form data form.save() # Redirect to the user_attendance view return redirect('user_attendance') context = {'attendance_records': attendance_records, 'form': form} # Render the template with the attendance records and form return render(request, 'user_attendance.html', context) and below is my form in forms.py class CompensationRequestForm(forms.Form): date = forms.DateField() reason = forms.CharField(widget=forms.Textarea) def save(self): # Save the form data to the database pass how to fix this? chatgpt didnt help, so i asked here -
Problem with categories on my blog website
I have added categories and everything but I can't see any posts in my categories. When I open for example http://localhost:8000/category/sport/ it is showing no posts... my urls.py : from django.urls import path #from . import views from .views import HomeView , ArticleDetailView, AddPostView, UpdatePostView, DeletePostView, CategoryView urlpatterns = [ #path('', views.home, name="homepage"), path('', HomeView.as_view(), name = 'home'), path('article/<int:pk>', ArticleDetailView.as_view(), name = 'article-details'), path('add_post/', AddPostView.as_view(), name = 'add_post'), path('article/edit/<int:pk>', UpdatePostView.as_view(), name = 'update_post'), path('article/<int:pk>/delete', DeletePostView.as_view(), name = 'delete_post'), path('category/<str:categories>/', CategoryView, name='category'), ] my models.py : from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): #return reverse('article-details', args=(str(self.id))) return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default="YNTN") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return (self.title + " | " + str(self.author)) def get_absolute_url(self): return reverse("home") m y views.py : from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_name = 'home.html' … -
'import jwt' not working in Django views.py though I have PyJwt installed
I'm working with Django and trying to generate jwt tokens in views.py and displaying it in html page. import jwt is throwing No module found error in views.py even though I have PyJwt installed already inside the virtual environment and it is working fine outside the views.py (say, jwttoken.py file) views.py import jwt def generateJWT(portal): key = 'secret' payload = {'iat': time.time(), 'iss' : 'localhost', 'exp': int(time.time()) + (5*365*24 * 60), 'portal': portal} #return payload return jwt.encode(payload, key, algorithm="HS256") Does it mean that I can't make use of jwt module in django? Is there any other way to make it work in Django as it is working outside? -
Celery tasks running multiple times in Django application
For weeks now we have been having issues with tasks running multiple times (always twice actually). I have tried to reproduce this locally and did a lot of testing on our staging and production server, but I can not seem to reproduce it and find the issue. Right now I simply have no clue where to look. -We have recently upgraded from celery v4 to v5, but this was together with many other upgrades. -The issues are only with long running periodic tasks (celery beat) that takeabout 15 min. to complete. -We run celery in a managed kubernetes environment with separate deployments for beat and worker. Both deployments currently have a single pod. One example of a task running twice: @idempotent_notification_task(notification_tag='CREDITS_DIRECTDEBIT_PAYMENT') def create_directdebit_payments_for_credits(): plus_admin_ids = Order.objects.filter( subscription__type=Subscription.PLUS, credits_auto_top_up_amount__gt=0).values_list('administration_id', flat=True) admins = Administration.objects.filter(id__in=plus_admin_ids) for admin in admins: remaining_credits = admin.remaining_credits if remaining_credits < 0: po_exists = PurchaseOrder.objects.filter(administration=admin, created__date=today(), service=PurchaseOrder.SERVICE.CREDITS).exists() if po_exists: print(f"PurchaseOrder for client {admin.title} already exists!") return purchase_order = PurchaseOrder.objects.create( administration=admin, service=PurchaseOrder.SERVICE.CREDITS, credits_amount=admin.order.first().credits_auto_top_up_amount) payment = create_credits_mollie_payment_directdebit(purchase_order) Notification.create_credits_directdebit_payment(purchase_order) In an attempt to create a fix I created a wrapper function to make the task idempotent, but even this did not fix the issue. The wrapper function works as expected during local … -
I am using Django rest framework I want to use random in my views.py can someone help me
I am using Django rest framework I want to use random in my views.py can someone help me I want to make Questions in views.py to be random and here is my code views.py class QuizQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quiz_id=self.kwargs['quiz_id'] quiz=models.Quiz.objects.get(pk=quiz_id) return models.QuizQuetions.objects.filter(quiz=quiz) class QuizChapterQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quizChapter_id=self.kwargs['quizChapter_id'] quizChapter=models.QuizChapter.objects.get(pk=quizChapter_id) return models.QuizQuetions.objects.filter(quizChapter=quizChapter) I want to make both of them to be random to get solutions to my problem -
(Python) how to make change on mysql, can reflect to website too
Main problem: connect exsited mysql and website , that making change on mysql can reflect to website too (ps. the Django way will stock on no way to connect exsist websit and MySQL) tried method A : even though the Django way can connect MySQL and Django, but still not lead to change mysql reflect to website too Demo idea result : (refer to author DC con, his example Concretization my aim) if I update/change the context Nordic as Nike from mySQL, by success connect both, the website part the Nike can replace Nordic as new topic I read through all the relate question, they either not 100% same to mine issue, or that issue don't get solution, or I tried the solution, but not worked , thanks -
How to correctly import and run a trained pytorch model within django application
I have a django website up and running. I would need to import a pytorch trained model (of which I am by no means an expert) I was thinking to make a wheel out of if and importing it as a module within my application. The model is obviously trained outside of the app in its own special environment. Is my approach correct, or is there a better cleaner way to do it? -
How to deal with multipe user role's with only one username in django
I have a django project with 2 types of users (Parent, Child), and using phone number as username How should I define my user model (or project architecture) to able login both parent and child with only one phone number? Currently I think about seperating profile table's and identify user role from the login endpoint, Or microservice this project into 2 smaller project's (Microservice) to do this. -
How can import a serializer module from Django app with in the standalone script in the "scripts" package?
Here is my project setup. ProjectDirectorty AppDirectory model.py serializer.py scripts Directory init.py main.py manage.py I am trying to call external API and get JSON data. Later deserialize it and store in the DB created by App. When I am running main.py using python manage.py runscript main , I get error "Cannot import module 'scripts.main': No module named 'mix.mixapp'" project setup I understand diffrence between Script vs. Module and read Relative imports for the billionth time I got stuck in this part of article "perhaps you don't actually want to run moduleX, you just want to run some other script, say myfile.py, that uses functions inside moduleX. If that is the case, put myfile.py somewhere else – not inside the package directory – and run it. If inside myfile.py you do things like from package.moduleA import spam, it will work fine." It is similar to my case. I am running main.py which is in the "scripts" dir and using function from AppDirectory. It didn't help. Please guide me to solve this problem. -
Django Transaction Rollback on related objects
In django, while in a transaction if an object is deleted its related objects will be deleted(those having one to one and foreignkey with this object) so if the transaction rolls back the deleted object will get rolled back but not its deleted related object. Is there any way with which we can do so? I tried overriding the deleted method and putting everything in a transaction atomic block but this didn't work -
How to get a count of objects in a Queryset
I have a model which which has fields like: class Vehicle(models.Model): car_name = models.CharField(max_length=255) car_color = models.CharField(max_length=255) This model has a lot of duplicate values too, I would like distinct to be shown The queryset gives an output like: <QuerySet [{'car_name': 'Audi', 'car_color': 'Red'}, {car_name': 'BMW', 'car_color': 'white'}]> I want my output Queryset to have another field, which is like a counter for the ouput. If I get two objects out of the query, then a field called ordinal_count also be sent in queryset. For example: <QuerySet [{'car_name': 'Audi', 'car_color': 'Red', 'ordinal_count': 1}, {car_name': 'BMW', 'car_color': 'white', 'ordinal_count': 2}]> This is the query which I wrote: op = (Vehicale.objects.annotate(ordinal_count=Count("car_name", distinct="car_name")).filter(car_color='white', list_display=True).values("car_name","car_color", "ordinal_count")) This is not giving me the desired input and is also messing up the filter. Should I even be using annotate? I have tried using SQl query, but I would like to get a queryset. I have written an output serializer which would easily be able to take input. Or should I get the output without ordinal_count, and later in serializer should I try to get the count output? If yes, then how do I do it? -
Will creating serializer.Serializer fields saves to the database?
When we're not creating models and directly creating the fields inn serializers using serializer.Serializer , will the fields save to database? because we havent migrated to the database? also if i have created one existing database, i'm creating some additional fields in serializers? will that also saves to database? can anyone lighten me up? Im new to django api. here i provide some example. let my Model.Py be like, class Detail(models.Model): fname = models.Charfield(maxlength=20) lname = models.Charfield(maxlength=20) mobile = models.IntergerField(maxlength=20) email = models.EmailField(maxlength=20) let my Serializer.Py be like, class DetailSerializer(serializer.Serializer): created_at = serializer.Charfield is_active = serializer.Booleanfield Will this serializer save in database that i created manually in serializer? another question is if i create serializers without a model, will that save to database? if that saves in database how's it possible without migrating? -
add +=1 to integer in the database
I want to add +=1 in Count_of_all_questions every time the function is executed. How can I do that? views.py def somefunction(request): verify = Statistik.objects.filter(user__exact=request.user) if verify: # i wanna add here on Count_of_all_questions += 1 else: form = Statistik(Count_of_all_questions=total) form.user = request.user form.save() models.py class Statistik(models.Model): Count_of_all_questions = models.IntegerField() #Count_of_all_correct_answer = models.IntegerField() #Count_of_all_wrong_answer = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) Thank you a lot! I want to add +=1 in Count_of_all_questions every time the function is executed. How can I do that? -
My link to a local markdown file does not work correctly
for example when link is: http://127.0.0.1:8000/entries/CSS it throws an error: Page not found (404) “entries/CSS” does not exist But when i put a file format at the end (in this case it is .md) it downloads the file instead of opening it in my browser: <ul> {% for entry in entries %} <li><a href ="./entries/{{entry}}.md">{{ entry }}</li></a> {% endfor %} </ul> link: 127.0.0.1:8000/entries/CSS.md I need to open this pages in browser, how do i fix it? Here is my urls.py file: from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path("", views.index, name="index"), path('newpage/', views.new_page, name = 'newpage'), ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Django Many to Many field dependent on another many to many field
I'm creating two many-to-many fields based on same model in a single model. I would like to show only those instances in second many-to-many field which are selected in first many to many field to further apply selection. Through which approach should i handle this behaviour. class Params(models.Model): name = models.CharField(max_length = 200) comments = Model.TextField() def __str__(self): return self.name class Selection(models.Model): select_params = models.ManyToManyField(Params, blank=True, related_name = "selection_1") edit_selected_params = models.ManyToManyField(Params, blank=True, related_name = "selection_from_selec_params") Thanks and regards -
How this code upload file in django can run the html file?
The code is here I am confused about the html file, it looks like it was never called but it can be run and when I change upload_form.html name to upload.html, it could be an error. So how come? and how to make the program can run upload_form.html file in another name file? This is my first question, so sorry if my question makes you confused >.< I wish I could understand the code -
Display today data and yesterday data of datetime field values using django
Here by default I need to display today data and yesterday data where the date is DateTime field Here is my views.py def completed_quanity_list(request): client = request.user.client production_process = ProductionProcess.objects.filter(client=client,is_deleted=False) today = datetime.date.today() yesterday = today + timedelta(days=-1) completed_quantity = CompletedQuantity.objects.filter(client=client,date__range=[yesterday, today]) return render(request, 'manufacturing/completed_quantity_list.html',locals()) Here is my database records example of CompletedQuantity table id date 1 2023-01-13 18:28:35.045678 2 2023-01-12 18:30:45.056345 3 2023-01-04 10:04:56.086043 4 2023-01-04 10:37:08.349253 5 2023-01-05 04:33:31.109787 6 2023-01-05 04:35:16.852320 I need to display the records of id's 3,4,5,6 in my template -
How to work with an image before saving it in my model?
django How to work with an image before saving it in my model? I have a model where a field exists image=models.ImageField(upload_to='products/') models.py class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200) code_number = models.IntegerField(verbose_name='Bar Code') image = models.ImageField(upload_to='products/') purchase_price = models.DecimalField(max_digits=10, decimal_places=2) sale_price= models.DecimalField(max_digits=10, decimal_places=2) tax = models.ManyToManyField(Tax, blank=True, related_name="tax") pro_quantity =models.DecimalField(max_digits=10, decimal_places=2, default=0) description = models.TextField() branch = models.ForeignKey(Branch, on_delete=models.CASCADE, related_name="branchesp", blank=True, null=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.name views.py class ProductCreate(View): form_class = ProductForm template_name = 'pos/product_form.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) form.instance.user = self.request.user if form.is_valid(): # Procesa la imagen subida image_content = request.FILES['image'].read() image = resize_image_with_aspect(image_content, 800, 600) image_file = tempfile.NamedTemporaryFile(mode='wb', suffix='.webp') image.save(image_file, format="webp", optimize=True, quality=85) image_file = open(image_file.name, 'rb') form.instance.image = image_file.read() image_file = BytesIO(form.instance.image) image_file.seek(0) form.instance.image = File(image_file) product = form.save(commit=False) product.save() image_file.close() return redirect('inventory') else: print(form.errors) return redirect('inventory') utils.py import io from PIL import Image def resize_image_with_aspect(image_content, width, height): image = Image.open(io.BytesIO(image_content)) original_width, original_height = image.size ratio = original_width / original_height if width > height: height = int(width / ratio)manteniendo el ratio … -
Length of variable declaration in Django?
budgeted_cost_sheet_fabric_summary_obj_kg_consumption = 1.123 or def budgeted_cost_sheet_fabric_summary_obj_kg_consumption_update(id): OBJ.update(an_attribute=data) I am going to declare variable or function name like this way. Is it okay to declare in this way in Django? Or it may arise any error in future?