Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Aggregation on date field
Hi I have two following models class Store(models.Model): store_name = models.CharField(max_length=100) class Meta: db_table = 'stores' class Sales(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, related_field='sales') product_id = models.BigInteger() sale_date = models.DateTimeField() total_mrp = models.FloatField() I am trying to fetch sum(total_mrp) of each store day wise but seem to unable to group by date col in my Sales Table I am using django_rest_framework I tried to do above using following serializers class SalesSerializer(serializers.RelatedField): queryset = Sales.objects.all() def to_representation(self, value): data = self.queryset.annotate(day=functions.ExtractWeekDay('sale_date'), total_sale=Sum('total_mrp')) return data.values('day', 'total_mrp') class StoreSerializer(serializers.ModelSerializer): primary_sales = SalesSerializer(many=False) class Meta: model = Store exclude = ['id'] The output result doesn't get grouped as I expect. Instead I get same data for primary sales for each store. -
Django - Pass Form data in URL
I want to pass the forms data to another view (if possibleby GET params) def post(self, request): form = SomeForm(request.POST) if form.is_valid(): response = HttpResponse(reverse('page_to_go')) How can I accomplish that? -
Android app problem: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 207: invalid start byte
So I have two ubuntu servers stage and dev, and one single API for android, IOS and web front on reactjs. I get this error when I try to upload a photo to my server from ANDROID app, basically I can upload the same photo to DEV server from Postman and IOS, but I keep getting this error when I try uploading from android. But from the same android app I can upload this exact photo to stage server and prod server, so basically nothing wrong with android app, but something is wrong on the server, even tho it correctly works with IOS and postman and web app. I believe that the code and settings are almost the same on both servers, so I have no idea where is the problem... Traceback (most recent call last): File "/home/project/.local/share/virtualenvs/blabla_backend-B039YcMy/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/project/blabla_backend/dating/middleware.py", line 144, in call body_repl = str(request.body, 'utf-8').replace('\n', '') if request.body else 'null' UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 207: invalid start byte Uploading a photo from android just like from other apps, but it just dissapears and I get this error in django logs. But still same android app … -
Setting permissions by group in Django
I am working with a Django project that requires user, group, and permission management to be done only through the admin panel. So I used Django's user system and created a login with this view.py # Django from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from django.contrib import messages def LoginView(request): """ Login Se utiliza el modulo de usuarios de Django """ template_name = "login.html" if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) if request.user.groups.filter(name="administradores").exists(): return redirect('inicio') else: return redirect('listarS') else: messages.error(request, 'Error en el ingreso') else: messages.error(request, 'Error en CUIT o contraseña') context = {} return render(request, 'login.html', context) def LogoutView(request): """ Logout de Django """ template_name = "login.html" context = {} logout(request) return redirect(request, 'login.html', context) Groups are administradores and operadores. Users from operadores group only have permissions on specific model group permissions But when I add a user to this group: user group When logging in, this user can do anything (add, modify, delete or list) in any model of the application. How should I do so that the users of the operadores group only have the permissions of that … -
Adding values to cells in a specific column in HTML
I am creating a very basic table in HTML for my Django project. I got some help from Here to learn how to pass a list from my Django app to my HTML and generate rows for my values. My question this time is: how can I target the second, third, or any particular column for my list? For example, suppose I have a list of values and want to add all of them to Column 3 of my table. Here is the code I tried to use where i wanted to have {{ name }} values added to column two, but it keeps adding the cells to the first column <html> <body> <table border="1" cellpadding = "5" cellspacing="5"> <tr> <th> IDs </th> <th> Names </th> <th> Heights </th> </tr> {% for id in myIDs %} <tr> <td>{{ id }}</td> </tr> {% endfor %} <tr> {% for name in myNames %} <td> <tr> <td>{{ name }}</td> </tr> </td> {% endfor %} </tr> </table> </body> </html> -
image post feed with django does not display images
Currently working on a very simple social media and since yesterday the images in the post feed either disappear or i get a value error: ValueError at / The 'image' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.16 Exception Type: ValueError Exception Value: The 'image' attribute has no file associated with it. Exception Location: C:\Users\Render_2\PycharmProjects\djangoProject\venv\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file Python Executable: C:\Users\Render_2\PycharmProjects\djangoProject\venv\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\Users\Render_2\PycharmProjects\djangoProject', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Render_2\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Render_2\PycharmProjects\djangoProject\venv', 'C:\Users\Render_2\PycharmProjects\djangoProject\venv\lib\site-packages'] Server time: Thu, 05 Jan 2023 12:14:48 +0000 I have honestly no idea why it is messed up now, since it was running just fine yesterday morning. Please help me out to understand this issue. Here is the rest of the code. the index.html: {% for post in posts reversed %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/user.png' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> <span class="block capitalize font-semibold "><a href="/profile/{{ post.user }}">@{{ post.user }} </a></span> </div> <div> <a href="#"> <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full p-2 transition -mr-1 "></i> </a> <div … -
TemplateSyntaxError Could not parse the remainder: '"{%' from '"{%'
I have TemplateSyntaxError Could not parse the remainder: '"{%' from '"{%' and I don't know how to write the code in a different way. I tried JS but it also didn't work. <ul> {% for key1, value1 in menu.items %} <li><a href="{% url key1.slug %}" {% if request.path == "{% url key1.slug %}" %} class="active" {% endif %}>{{ key1 }}</a></li> {% endfor %} </ul> Highlighted in TemplateSyntaxError: {% if request.path == "{% url key1.slug %} jQuery(function($) { var path = window.location.href; $('a').each(function() { if (this.href === path) { $(this).addClass('active'); } }); }); -
Django q process does not get cleared from memory
I have integrated Django Q in my project and i'm running a task from django q but after task ran successfully i can still see the process is in memory is there any way to clear the process from memory after it has finished the job. Here is the django q settings Q_CLUSTER = { 'name': 'my_app', 'workers': 8, 'recycle': 500, 'compress': True, 'save_limit': 250, 'queue_limit': 500, 'cpu_affinity': 1, 'label': 'Django Q', 'max_attempts': 1, 'attempt_count': 1, 'catch_up': False, 'redis': { 'host': '127.0.0.1', 'port': 6379, 'db': 0, }} -
Sum and Annotate does not returns a decimal field Sum as a decimal
I am writing a query in which I want to Sum amount using annotate and Sum decimal field in a foreign key relationship. The field is summed correctly but it returns the Sum field in integer instead of decimal. In the database the field is in decimal format. The query is like... **models.objects.filter(SourceDeletedFlat=False).annotate(TotalAmount=Sum("RequestOrderList__PurchaseOrderAmount")).all(). I do not want to use aggregate because I don't need overall column sum. -
How do I format a nested python dictionary and write it to a json file?
I am looking to run a calculation in my Django view and then write it to a json file. However I am struggling to get the formatting right. I need the output json file to look something like this: { "dates": { "year": { "total": 1586266, "upDown": 9.8, "data": { "labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "income": [2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 18000, 20000, 22000, 24000], "expenses": [6000, 12000, 18000, 24000, 30000, 36000, 42000, 48000, 54000, 60000, 66000, 72000] } } } } Here is what I have in my view: def generateGraph(): income = [{'income':['2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000','2000']}] expenses = [{'expenses':['1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000','1000']}] labels = [{'labels':['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']}] total = 1586266 upDown = 9.8 data = [labels, income, expenses] year = [total,upDown,data] dates = [year] with open( "static/graph.json") as f:json.dump(dates, f) return HttpResponse(open("static/graph.json", 'r'), content_type = 'application/json; charset=utf8') However, the output I currently get in my json file is: [[1586266, 9.8, [[{"labels": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]}], [{"income": ["2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000", "2000"]}], [{"expenses": ["1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000", "1000"]}]]]] Thanks! -
django html5 video plugin doesn't show in editor
i copied html5video in plugins folder and write 'html5video' in settings.py . video uploading icon doesn't show in editor, how can i fix this problem ? my configs ckeditor in settings.py : CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': ['Find', 'Replace', '-', 'SelectAll']}, {'name': 'forms', 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']}, '/', {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, {'name': 'tools', 'items': ['Maximize', 'ShowBlocks']}, {'name': 'about', 'items': ['About']}, '/', # put this to force next toolbar on new line {'name': 'yourcustomtools', 'items': [ # put the name of your editor.ui.addButton here 'Preview', 'Maximize', ]}, ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here # 'toolbarGroups': … -
Django Rest Framework: Delete multiple Cookies with same name but different domain?
I have an application running on different shards and each shard has a different domain. I am setting that domain as a domain for our cookies for respective environments. And the problem I am facing is that sometimes cookies from previous sessions (might be from different environments) are present in the browser. So When I try to perform certain actions then a cookie from the different session is used and validation failed. So now I want to delete those cookies with the same name. What I am doing is response.delete_cookie('profileActionId') But after this the cookies was something like this: profileActionID: 'cookie_value' :: domain: 'usa.example.com/' profileActionID: '' :: domain: 'example.com/' So this doesn't delete cookies with the same name which have a different domain and I don't have a way to access that different domain from the code and also can't hardcode it as It will change according to different environments. Also I can't change the domain for cookies for different environments. So Is there a way in Django by which we can delete all cookies with the same name irrespective of there domains or paths? -
Do I need to use a inline formset? Or am I over complicating my models?
I’m trying to create an app that stores golf round scores. This will have things like the course being played, which tees being used, etc. what’s causing me problems is this could have 1-4 players. I would like to use 1 model for this, but I don’t think it would be possible because I need one instance of the course criteria, while 1-4 instances for the players. Am I overthinking my models? Or does this sound correct. Based on the models.py below I would do a inline formset with Golf_Round and Round_player` from django.db import models from django import template from django.urls import reverse from Courses.models import Golf_Course from accounts.models import Golfer from django.utils.timezone import now class Golf_Round(models.Model): Tee= models.ForeignKey(Golf_Tee, on_delete=models.CASCADE) round_create_date = models.DateTimeField(default=now()) is_active_round = models.BooleanField(default=False) def _str_(self): return "{}.{}.{}".format(self.round_create_date, self.course,self.pk) class Round_Player(models.Model): player = models.ForeignKey(Golfer, on_delete=models.CASCADE, default='Please_Select',blank=False) round = models.ForeignKey(Golf_Round, on_delete=models.CASCADE) hole_1_score = models.IntegerField() hole_2_score = models.IntegerField() hole_3_score = models.IntegerField() hole_4_score = models.IntegerField() hole_5_score = models.IntegerField() hole_6_score = models.IntegerField() hole_7_score = models.IntegerField() hole_8_score = models.IntegerField() hole_9_score = models.IntegerField() hole_10_score = models.IntegerField() hole_11_score = models.IntegerField() hole_12_score = models.IntegerField() hole_13_score = models.IntegerField() hole_14_score = models.IntegerField() hole_15_score = models.IntegerField() hole_16_score = models.IntegerField() hole_17_score = models.IntegerField() hole_18_score = models.IntegerField() create_date = models.DateTimeField(default=now()) … -
How can I put the elements of a form horizontally?
This is the layout and I would like the form elements to be horizontal instead of vertical This is my view code def requerimientos(request): form_procesos = forms.procesos form_impuesto = forms.impuestos return render(request, 'requerimientos.html',{"proceso" : form_procesos,"impuesto" : form_impuesto,"value": 2}) This is my HTML code <div class="col-12 col-md-6 offset-md-3"> <div class="card"> <div class="card-body"> {% if value == 1 %} <h5 style="font-family: 'Ubuntu', sans-serif;">Proceso:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy proceso %} </form> {% else %} <h5 style="font-family: 'Ubuntu', sans-serif;">Proceso:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy proceso %} </form> <h5 style="font-family: 'Ubuntu', sans-serif;">Impuesto:</h5> <form action="{% url 'contacto' %}" method="POST"> {% csrf_token %} {% crispy impuesto %} </form> {% endif %} </div> </div> <!-- Boton de enviar --> <br> <div class="d-flex justify-content-end"> <button type="submit" class="btn btn-primary">Enviar</button> </div> </div> This is my form code from django.forms import ModelForm from django import forms from crispy_forms.helper import FormHelper, Layout class procesos(forms.Form): mora = forms.BooleanField(required=False) deuda_atrasada = forms.BooleanField(required=False) class impuestos(forms.Form): inmobiliario = forms.BooleanField(required=False) baldio = forms.BooleanField(required=False) rural = forms.BooleanField(required=False) edificado = forms.BooleanField(required=False) automotor = forms.BooleanField(required=False) embarcaciones = forms.BooleanField(required=False) complementario = forms.BooleanField(required=False) I have another question, I created two forms because I needed to describe what each element was, … -
html - Add bullet piont as place holder django forms
I am using django-forms to render out my signup page and i want to add a bullet point as placholder for password field by passing the &bull; character entity from the widgets in django-forms but it doesn't work. is how it is rendered out in browser. forms.py class Signup(forms.ModelForm): class Meta: model = User fields = ["username", "email", "password", "password2", "library_no", "first_name", "last_name",] help_texts = { "username":None, } labels = { } widgets = { "username": forms.TextInput(attrs={ "id":"input_46", "name":"q46_typeA46", "data-type":"input-textbox", "class":"form-textbox validate[required]", "size":"310", "data-component":"textbox", "aria-labelledby":"label_46", "placeholder":"180591001" }), "first_name":forms.TextInput(attrs={ "id":"first_4", "name":"q4_name[first]", "class":"form-textbox validate[required]", "autoComplete":"section-input_4 given-name", "data-component":"first", "aria-labelledby":"label_4 sublabel_4_first", "required":True, "placeholder":"Chinedu" }), "last_name":forms.TextInput(attrs={ "id":"last_4", "name":"q4_name[last]", "class":"form-textbox validate[required]", "autoComplete":"section-input_4 family-name", "data-component":"last", "aria-labelledby":"label_4 sublabel_4_last", "required":True, "placeholder":"Oladapo Dikko" }), "email":forms.EmailInput(attrs={ "id=":"input_10", "name":"q10_email10", "class":"form-textbox validate[required, Email]", "placeholder":"ex: myname@example.com", "data-component":"email", "aria-labelledby":"label_10 sublabel_input_10", "required":True }), "password": forms.PasswordInput(attrs={ "id":"first_50", "name":"q50_name50[first]", "class":"form-textbox", "autoComplete":"section-input_50 given-name", "data-component":"first", "aria-labelledby":"label_50 sublabel_50_first", "required":True, "placeholder":"&bull;&bull;" }), "password2": forms.PasswordInput(attrs={ "id":"last_50", "name":"q50_name50[last]", "class":"form-textbox", "autoComplete":"section-input_50 family-name", "data-component":"last", "aria-labelledby":"label_50 sublabel_50_last", "required": False }), "library_no": forms.TextInput(attrs={"required": False}), } signup.html <!DOCTYPE html> <html class="supernova"> <head> <title>SignUp</title> <style type="text/css">@media print{.form-section{display:inline!important}.form-pagebreak{display:none!important}.form-section-closed{height:auto!important}.page-section{position:initial!important}}</style> <link rel="stylesheet" href="/static/signup/css/style.css"> <link rel="stylesheet" href="/static/signup/css/main.css"> </head> <body> <form class="jotform-form" action="/signup/" method="post" name="form_230023299150548" id="230023299150548" accept-charset="utf-8" autocomplete="on"> {%csrf_token%} <div role="main" class="form-all"> <style> .form-all:before { background: none; } </style> <ul class="form-section page-section"> <li id="cid_28" class="form-input-wide" … -
Can I return multiple values from a SerializerMethodField? I am getting an error telling me I can't. How do I then get the values?
I have a post model that represents a normal post with images and possibly a video. I have a post reply model that represents comments or replies to a post. Here is the models.py file: class Category(models.Model): name = models.CharField(max_length=100, verbose_name="name") slug = AutoSlugField(populate_from=["name"]) description = models.TextField(max_length=300) parent = models.ForeignKey( "self", on_delete=models.CASCADE, blank=True, null=True, related_name="children" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "category" verbose_name_plural = "categories" ordering = ["name"] db_table = "post_categories" def __str__(self): return self.name def get_absolute_url(self): return self.slug def video_directory_path(instance, filename): return "{0}/posts/videos/{1}".format(instance.user.id, filename) def post_directory_path(instance, filename): return "posts/{0}/images/{1}".format(instance.post.id, filename) def reply_directory_path(instance, filename): return "replies/{0}/images/{1}".format(instance.reply.id, filename) def reply_videos_directory_path(instance, filename): return "{0}/posts/{1}/replies/{2}/videos/{3}".format(instance.user.id, instance.post.id, instance.reply.id, filename) class Post(models.Model): EV = "Everybody" FO = "Followers" FR = "Friends" AUDIENCE = [ (EV, "Everybody"), (FO, "Followers"), (FR, "Friends"), ] category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1) body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) video = models.FileField(upload_to=video_directory_path, null=True, blank=True) can_view = models.CharField(max_length=10, choices=AUDIENCE, default=EV) can_comment = models.CharField(max_length=10, choices=AUDIENCE, default=EV) user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name="user", related_name="user" ) published = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "post" verbose_name_plural = "posts" db_table = "posts" ordering = ["created_at"] def __str__(self): return self.body[0:30] … -
SRC link changed when trying to integrate paypal button on django website
I'm trying to add the paypal button to my django shopping site. I have used the code from the SDK and replaced the id: My code: Client ID being: AWeSepzeHNW8BHE8rWPVm6CTuAGKz7SS1WzpbqEOZvQw-s_6qwFg6lxCO9MSXPpcVheUBWRgNuW6yKol However i am receiving a 400 error. Also viewing the page source shows the src has changed: If you follow this link you get the following message: throw new Error("SDK Validation error: 'Invalid query value for client-id: AabgYuFGxyzy3AbeWLPa-EtEGGreyL9bDDbWOxH4zFbPbgNc7y5yMpNO7B2NMRxCvT7-Ysou8ZXDNycT¤cy=USD'" ); /* Original Error: Invalid query value for client-id: AabgYuFGxyzy3AbeWLPa-EtEGGreyL9bDDbWOxH4zFbPbgNc7y5yMpNO7B2NMRxCvT7-Ysou8ZXDNycT¤cy=USD (debug id: f3776258140b9) */ Anyone know why the src has been changed from the source to when its rendered by django? I have followed the original src link from paypal and this, however when the page renders the link is altered. -
How to Get same Connection id in django for every file
Every time I run my Django webservice the connection (django and MySQL connector) is same for every python function that I call but Connection_id from MySQL workbench is different for every python function. My temporary table keeps dropping from the DB which was created from a python function A and has to be accessed by another independent python function B at a later point of time from a different webservice. I guess the temporary table is being dropped as a result of new instances(connection_id) getting generated in the MySQL DB everytime I run a webservice to call my python functions. Example outputs of connections: Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> Mysql Connection ID: 18424 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> Expectation Example outputs of connections: Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> same nexttime Mysql Connection ID: 18423 django connection: <django.utils.connection.ConnectionProxy object at 0x00000203C0C84340> mysql connection: <mysql.connector.connection_cext.CMySQLConnection object at 0x00000203C1B7C070> -
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