Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query returns multiple rows of Sum, I only want to display one row
currently the way I have the code written is that I have a model named Finances. I have an aggregate set up so it sums up all of the rows. I am trying to display the outcome of the rows, but when I do it displays a row for every database entry. I understand that I am grabbing all with .all() in the viewpayout = Finances.objects.all() in views.py, but I am unsure of how this should be written to only display one row. How would I display only one row that sums up all of the rows for a column? Any help is greatly appreciated! Below is my code: views.py def finances(request): viewpayout = Finances.objects.all() updatepayout = UpdatePayout() updatewithdraw = UpdateWithdraw() updatecash = UpdateCash() if request.method == "POST": if 'add_payout' in request.POST: updatepayout = UpdatePayout(request.POST) if updatepayout.is_valid(): post = updatepayout.save(commit=False) post.save() return redirect("/finances") else: updatepayout = None if 'bank_withdraw' in request.POST: updatewithdraw = UpdateWithdraw(request.POST) if updatewithdraw.is_valid(): post = updatewithdraw.save(commit=False) post.save() return redirect("/finances") else: updatewithdraw = None if 'add_cash' in request.POST: updatecash = UpdateCash(request.POST) if updatecash.is_valid(): post = updatecash.save(commit=False) post.save() return redirect("/finances") else: updatecash = None return render(request, 'portal/finances.html', {"updatepayout": updatepayout, "updatewithdraw": updatewithdraw, "updatecash": updatecash, "viewpayout": viewpayout}) model.py class Finances(models.Model): payout … -
Django join tables
How can I join the below tables in the view to get the addresses of all the Dials in DataUpload table from BO table. class BO(models.Model): id = models.AutoField(primary_key=True) Dial = models.IntegerField() Customer_Address = models.CharField(max_length=100, null=True, blank=True) Wallet_Limit_profile = models.CharField(max_length=100, null=True, blank=True) class DataUpload(models.Model): Dial = models.IntegerField() Serial = models.IntegerField(null=True) Bag = models.IntegerField(null=True) Today_Date = models.DateField(null=True) user = models.CharField(max_length=100) summary = models.ForeignKey(summary, on_delete=models.CASCADE) summary_text = models.CharField(max_length=100, null=True, blank=True) Name = models.CharField(max_length=100) C**ustomer_Address = models.ForeignKey(BO, on_delete=models.CASCADE, null=True, blank=True)** National_ID = models.IntegerField() Customer_ID = models.IntegerField() Status = models.CharField(max_length=100) Registration_Date = models.DateTimeField(max_length=100) Is_Documented = models.CharField(max_length=100, null=True) Needed_Action = models.ForeignKey(needed_action, on_delete=models.CASCADE, null=True, blank=True) Hard_Copy_Type = models.ForeignKey(Hard_Copy_Type, on_delete=models.CASCADE, null=True, blank=True) Request_Status = models.ForeignKey(Request_Status, on_delete=models.CASCADE, null=True, blank=True) -
When I start gounicorn.services, I get error 200/CHDIR. How can it be corrected?
gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root WorkingDirectory=/var/www/botproject/ ExecStart=gunicorn --workers 5 --bind unix:/run/gunicorn.sock botproject.wsgi:application [Install] WantedBy=multi-user.target /var/www/botproject/ - project folder systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Sat 2022-07-09 21:28:04 UTC; 3s ago Process: 83314 ExecStart=/usr/local/bin/gunicorn --workers 5 --bind unix:/run/gunicorn.sock botproject.wsgi:application > Main PID: 83314 (code=exited, status=200/CHDIR) Jul 09 21:28:04 server.domain.com systemd[1]: Started gunicorn daemon. Jul 09 21:28:04 server.domain.com systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR Jul 09 21:28:04 server.domain.com systemd[1]: gunicorn.service: Failed with result 'exit-code'. I can't figure out what is causing the 200/CHDIR error -
Reverse for 'category_site' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<category>[-a-zA-Z0-9_]+)\\Z']
Im trying to make url and content of currently displayed product category dynamic, with using one 'category.html' template, but I just keep getting this error urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', display_records, name="display_records"), path('about/', about_site, name="about_site"), path('product/<int:id>', product_site, name="product_site"), path('all_products/', all_products_site, name="all_products_site"), path('<slug:category>', category_site, name="category_site"),]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def category_site(request, category): category_filter = (Q(category__icontains=category)) results = Farfocel.objects.filter(category_filter) return render(request, 'category.html', {'products': results}) product.html <ul class="breadcrumbs"> <li class="breadcrumbs__item"> <a href="{% url 'display_records' %}" class="breadcrumbs__link">Home</a> </li> <li class="breadcrumbs__item"> <a href="{% url 'all_products_site' %}" class="breadcrumbs__link">Products</a> </li> <li class="breadcrumbs__item"> <a href="{% url 'category_site' product.category %}" class="breadcrumbs__link">{{ product.category }}</a> </li> <li class="breadcrumbs__item"> <a href="" class="breadcrumbs__link breadcrumbs__link--active">{{ product }}</a> </li> Honestly I tried everything I could find and I still keep failing. -
Django widget for ManyToManyField
I'm new to Django. I have a model Course with a ManyToManyField to another model Person (representing the teachers of the course). In my views.py, I have the class CreateCourse(CreateView) for creating new instances of courses. The standard widget for the ManyToManyField does not work for me, because in principle there will be too many people. What is the best way to solve the problem, for example, how to create a text input from which I can insert the surname and getting the corresponding person? Thanks in advance! -
Django DRF How to force login on swagger
I'm using Django Rest Framework in a project with swagger for documentation. Swagger UI can be accessed by everyone who knows its URL. Is that possible to add an authentication method so only people with the right access can see and read swagger docs? on urls.py schema_view = get_schema_view( openapi.Info( title="API Docs", default_version='v1', description="beautiful and long text", license=openapi.License(name="BSD License"), ), public=True, permission_classes=[permissions.AllowAny], ) ... urlpatterns = [ url( r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui' ), url( r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc' ), ] on settings.py SWAGGER_SETTINGS = { 'SHOW_REQUEST_HEADERS': True, 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header', }, 'basic': { 'type': 'basic' } }, 'USE_SESSION_AUTH': True, 'JSON_EDITOR': True, 'SUPPORTED_SUBMIT_METHODS': [ 'get', 'post', 'put', 'delete', 'patch' ], } -
How do i do the summation of two dictionary with aggregate in django , and show it in HTML?
i am new to django , would u experts pls kindly help me.. so i have two modules, and in CBV's get_context_data they both return total sum, now I want to add both the totals and display it on my HTML page, I honestly tried many things but I am always getting an error. here is my views.py def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) today = datetime.datetime.now() # Order.objects.filter(created_at__year=today.year, created_at__month=today.month) context['expense1'] = Tracker.objects.filter(user=self.request.user) context['Total1'] =(Body.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity'))) , Sport.objects.filter(user=self.request.user, pub_date__year=today.year, pub_date__month=today.month).aggregate(total=Sum(F('price') * F('quantity')))) return context so what I want is , total of body + total of sports , which is being asgn to the context "total1" ,and then I want to show it in HTML my HTML file this is how I am displaying the total, Total: {{Total1}} -
How to sort the records in the table for the month for each doctor (DJANGO)
There are two tables class Doctors(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") content = models.TextField(blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d") time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) spec = models.ForeignKey('Speciality', on_delete=models.PROTECT, null=True) class Appointment(models.Model): class Meta: unique_together = ('title', 'date', 'timeslot') TIMESLOT_LIST = ( (0, '09:00 - 09:30'), (1, '10:00 - 10:30'), (2, '11:00 - 11:30'), (3, '12:00 - 12:30'), (4, '13:00 – 13:30'), (5, '14:00 – 14:30'), (6, '15:00 – 15:30'), (7, '16:00 – 16:30'), (8, '17:00 – 17:30'), ) title = models.ForeignKey('Doctors', on_delete=models.CASCADE) date = models.DateField() timeslot = models.IntegerField(choices=TIMESLOT_LIST) username = models.ForeignKey(User, max_length=60, on_delete=models.CASCADE) complaints = models.CharField(max_length=500) phone = models.CharField(max_length=30) When you make an appointment with a doctor, an entry is added to the Appointment table, I need to find out how many entries for each doctor for a month and for all time. -
Detail view is not displaying content of models
i'm new to Django, so please bear with me. My detail View in Django, isn't successfully displaying the content selected from the listviews. The following is my code. Model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Post_Model(models.Model): Title = models.CharField(max_length=50) Author = models.ForeignKey(User, on_delete=models.CASCADE) Body = models.TextField() def __str__(Self): return Self.Title + ' | ' + str(Self.Author) urls: from django.urls import path from .views import Article_details, Home_page urlpatterns = [ path('', Home_page.as_view(), name="Home"), path('Article/<int:pk>/', Article_details.as_view(), name="Article"), Views: from django.shortcuts import render from django.views.generic import ListView, DetailView from . models import Post_Model class Home_page(ListView): model = Post_Model template_name = 'June11App/Home.html' class Article_details(DetailView): model = Post_Model template_name = 'June11App/Article.html' HTML LIST VIEW: <h1>Home Page</h1> <ul> {% for Post in object_list %} <li> <a href="{% url 'Article' Post.pk %}"> {{Post.Title}} </a> - {{Post.Author}}<br> {{Post.Body}} </li> <br> {% endfor %} </ul> HTML DETAIL VIEW: <h1>Article Page</h1><br> {{Post.Author}} {{Post.Body}} I hope my query made sense. I don't receive any error on myside, its just not working as it should. -
Django session variables not being created on post
I have a weird problem, I have been asked to modify a Django form to include an address (simple I thought), the original html form collects the data, name, contact, etc and then the views.py gets the session variables using sender_name = request.POST.get('sender_name', ''), etc. The sender_address which is a textarea on the HTML form is not included in the dictionary. I can see all the other session variables. The weird thing is if i change one of the original session variables in the HTML form, example sender_name to sender_name1, it too also stops working and disappears from the dictionary. I’m new to Django, slowly getting my head around it, is there a way in django to protect the session variables or am I completely missing something. The form data is not being stored in a dB its being fired off in a email. There isn’t any forms.py associated with the view either. I’ve checked all the MIDDLWWARE entries just in case too. Ive googled the problem but only find stuff on sessions which is not useful. Thank you. -
django - save list of base 64 images to database
i have a list of base64 images that i send from a react panel. images list look like below: [ "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkG", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAADkCAY" ] Note: i remove most of the charachters because each index charachters is more than 2000 and it's just a example of what i have. so i want to save them in django model. my field for saving this list of images is this: ArrayField(base_field=models.ImageField(upload_to='hotel_images/')) so how should i convert list of base64 images to real images and save them to this ArrayField? or do you have a better way for saving this base64 images list? Note: i convert images to base64 in react panel by code below: const FR = new FileReader(); FR.addEventListener("load", function () { image = FR.result; }) FR.readAsDataURL(img); and i do this because i have a json that contains other fields like name and description so when i want to send this json with request body i should use JSON.stringify() for that and when i use JSON.stringify(), images field is turn to empty array and i have to convert images to base64. so if you have a solution for this problem, that could help too! Final Note: my database is postgreSQL. -
How do I limit requests per user in Django rest framework using throttling?
I'm working on a Quiz app and one question gets uploaded every week in a month (4 ques/month). Now I want to make sure that a logged in user can only attempt the question twice per week and not more than that. How can I do this using throttling or any other way? Here's my Quiz model: Days = ( ("Mon", "Monday"), ("Tue", "Tuesday"), ("Wed", "Wednesday"), ("Thu", "Thursday"), ("Fri", "Friday"), ("Sat", "Saturday"), ("Sun", "Sunday") ) class QuizDetail(models.Model): name = models.CharField(max_lenght=255, blank=False, null=False) start_date = models.DateTimeField() end_date = models.DateTimeField() publisehd_week_day = models.CharField(max_length=255, choices=Days) The published_week_day can change every month, so basically one month it can be Tuesday and next month it can be Thursday. Note: If in a month published_week_day is Tuesday and a user attempts last week's quizz on Monday and exhausts his two attempts then on Tuesday he should be able to attempt as it will be a fresh quizz. Thanks in advance. -
is there a way to access a single element of many-to-many relation in django without using for loop?
I'm really new to using Django and I've been stuck on this for weeks. I've got a list of voters which is named thumbs under each candidate, and it is a many-to-many field which is populated once a user votes. How can I check if a user is already in thumbs (i.e. has already voted) so that I display components differently based on this? Here is what I've got: myTemplateFile.html {% if request.user == candidate.thumbs.all %} <small style="color:grey; font-size:10px;">you've already voted here</small> <a id="Thumbs" class="btn btn-success btn-sm thumbaction{{poll.id}}{{candidate.id}}" value="thumbsup" data-toggle="tooltip" title="upVote: I like this candidate" role="button"> <svg id="{{poll.id}}{{candidate.id}}thumbsup" width="1em" height="1em" viewBox="0 0 16 16" class="up bi bi-hand-thumbs-up d-none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd"/> </svg><span id="i_like_this"><span class="" style="color:white; font-size:xx-small" id="{{poll.id}}{{candidate.id}}up">{{candidate.thumbsup}} </span></span><font class="" style="color:white; font-size:xx-small;" id="{{poll.id}}{{candidate.id}}approve">&nbsp;approved</font> </a> <a id="Thumbs" class="btn btn-danger btn-sm thumbaction{{poll.id}}{{candidate.id}}" value="thumbsdown" data-toggle="tooltip" title="downVote: I dont like this candidate" role="button"> <svg id="{{poll.id}}{{candidate.id}}thumbsdown" width="1em" height="1em" viewBox="0 0 16 16" class="down bi bi-hand-thumbs-down d-none" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd"/> </svg> <span class="" style="color:white; font-size:xx-small;" id="{{poll.id}}{{candidate.id}}down">{{candidate.thumbsdown}} </span><font style="color:white; font-size:xx-small;" id="{{poll.id}}{{candidate.id}}reject">&nbsp;rejected</font> </a> {% else %} <a id="Thumbs" class="btn btn-success btn-sm thumbaction{{poll.id}}{{candidate.id}}" value="thumbsup" data-toggle="tooltip" title="upVote: I like this candidate" role="button"> <svg id="{{poll.id}}{{candidate.id}}thumbsup" width="1em" height="1em" viewBox="0 0 16 16" class="up bi bi-hand-thumbs-up" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd"/> </svg><span style="color:white; font-size:xx-small;" id="i_like_this"><span … -
from.import views ImportError: attempted relative import with no known parent package
from django.urls import re_path as url from . import views urlpatterns=[ url('home/',views.home,name="home"), url('marketing_courses/',views.marketingCourses,name="Marketing courses"), url('privacy_policy/',views.privacyPolicy,name="Privacy policy"), url('blog/',views.blog,name="blog"), ] -
Uncaught TypeError: Cannot read properties of undefined (reading 'amount')
I converted the Django models into a JSON data object and accessed it in Javascript. However, I cannot access a field from the object and assign it to a text box. The JSON object that is being returned: [{"model": "inventory.inventory","pk": 1, "fields": {"product": "nice", "title": "Asus", "amount": 56000}}, {"model": "inventory.inventory", "pk": 2, "fields": {"product": "nice", "title": "Lenovo", "amount": 55000}}] The javascript code that I am using: <html>....{{ data|json_script:"hello-data" }}.... <script type="text/javascript"> const data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(){ var line_one=document.getElementById('id_line_one').value; var id=line_one-1; document.getElementById('id_line_one_unit_price').value = data[id].fields.amount; }; </script>....</html> The dropdown value returns its primary key, i.e., product_number and basically I want to fetch the amount of the product associated with that product_number. As the objects are stored from 0(?) in JSON, I thought the logic of my code was correct but I am not an expert so I am pretty sure I am making some silly mistake here. How can I return the amount of the object in the unit price text box when the title is selected in the dropdown list? Thanks! views.py @login_required def add_invoice(request): form = InvoiceForm(request.POST or None) data = serializers.serialize("json", Inventory.objects.all()) total_invoices = Invoice.objects.count() queryset = Invoice.objects.order_by('-invoice_date')[:6] if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/invoice/list_invoice') context … -
Creating a SET of strings in Redis but returning integers
Noticing that when I try to add a list of strings to my redis_instance as members of a SET when I try to retrieve the elements in this SET I only see integers. From how I read the documentation if I were to for example have a set containing: 'Fred', 'Emmanuel', 'Marcus Aurelius' If I were to return the entire SET, assuming the key for the set is 'newSet' by running this command: SMEMBERS newSet I should see a list of all members of said state, instead this is the response I get: 1) "32" 2) "39" 3) "44" 4) "65" 5) "69" 6) "70" 7) "77" 8) "91" 9) "93" 10) "97" 11) "99" 12) "100" 13) "101" 14) "105" 15) "108" 16) "109" 17) "110" 18) "114" 19) "115" 20) "117" This is the code I am using to create and append to said set: @api_view(['GET', 'POST']) def manage_items(request, *args, **kwargs): ... elif request.method == 'POST': new_users = request.body for i in range(0, len(new_users)): redis_instance.sadd('pairs', str(new_users[i])) response = { 'msg': f'set contains: {new_users}' } return Response(response, 201) Any ideas what's going on? -
Generic detail view UpdatePostView must be called with either an object pk or a slug in the URLconf
Trying to implement a update post view to my django blog. It keeps throwing me the error: 'Generic detail view UpdatePostView must be called with either an object pk or a slug in the URLconf.' I know it is telling me to call it with a PK or slug, but I'm not sure how to do this. views.py: class UpdatePostView(UpdateView): model = Post template_name = 'update_post.html' fields = ('title', 'excerpt', 'slug', 'featured_image', 'content', 'author', 'status') urls.py: from .views import AddPost, PostList, PostDetail, PostLike, UpdatePostView from django.urls import path urlpatterns = [ path('', PostList.as_view(), name='home'), path('like/<slug:slug>/', PostLike.as_view(), name='post_like'), path('add_post/', AddPost.as_view(), name='create_post'), path('edit_post/', UpdatePostView.as_view(), name='update_post'), path('<slug:slug>/', PostDetail.as_view(), name='post_detail'), ] update_post.html: {% extends "base.html" %} {% block content %} <header> <div class="container-fluid" id="image"> <div class="row px-4 text-center"> <img class="img-fluid header-image" id="main-background" src="https://res.cloudinary.com/dhyy9pzrd/image/upload/v1653761818/header-image_q71tuy.jpg" alt="blue/pink background image"> <div class="col-lg-6 mx-auto"> <div class="caption"> <div class="text-center-caption"> <h1 class="post-title fw-bolder text-uppercase">Update your post</h1> <h6 class="post-subtitle fw-bold">blablablabla</h6> </div> </div> </div> </div> </div> </header> <form class="text-center m-3" action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-signup right" id="button">Post</button> </form> {%endblock%} -
The Tables are overlapping on Each other in django
The problem is as my tables are dynamic I want to create tables in such a way that whenever I add data, after some lines in tables the 1st table starts over lapping on another table. I want that whenever I will add data automatically the position of the second table changes as per increasing data in first table. This is being Made in Django Css <style> #coursetable { position: absolute; height: 40px; top: 30%; left: 50%; transform: translate(-50%, -50%); margin: 0; } #coursetable h2 { color:white; } #yeartable { position: absolute; height: 40px; top: 90%; left: 50%; transform: translate(-50%, -50%); margin: 0; } #yeartable h2 { color:white; } #divisiontable{ position: absolute; height: 40px; top: 140%; left: 50%; transform: translate(-50%, -50%); margin: 0; } #divisiontable h2{ color:white } </style> **Table one** <div class="container" id="coursetable"> <h2>Courses</h2> <table class="table table-striped table-dark" style="width:100%;table-layout:fixed"> <thead> <tr> <th scope="col">#</th> <th scope="col"><h5 style="color:white;">Course Code</h5></th> <th scope="col"><h5 style="color:white;">Course Name</h5></th> </tr> </thead> <tbody> {%for course in courses%} <tr> <th scope="row">{{course.id}}</th> <td>{{course.course_code}}</td> <td>{{course.course}}</td> </tr> {% endfor %} </tbody> </table> </div> **Table Two** <div class="container" id="yeartable"> <h2>Year</h2> <table class="table table-striped table-dark" style="width:100%;table-layout:fixed"> <thead> <tr> <th scope="col">#</th> <th scope="col"><h5 style="color:white;">Year</h5></th> </tr> </thead> <tbody> {%for year in years%} <tr> <th scope="row">{{year.id}}</th> <td>{{year.year}}</td> … -
Why integers doesn't work within Django using {% with %}
I'm working with an HTML file within my Django web app. {% with var1=1 %} Indexig with variables: {{ticker.var1}} {% endwith %} </br> Indexig with numbers: {{ticker.1}} But then I get only this: Any help is highly appreciated! -
Not Redirecting to checkout pages
I have a case where I want a user to enter an amount they want to make payment with and i want the user to be redirected to this Payment Gateway checkout page imeediately they enter an amount. AttributeError at /payment/opay/nowdepos/ 'Response' object has no attribute 'streaming'. but my users are never redirected to this page when the amount is been entered. kindly correct me on the error from my code. def process_paynow_payment(request, comment = None): if request.method == 'POST': form = PaymentForm(request.POST) if form.is_valid(): payment = form.save() user = request.user first_name = user.first_name last_name = user.last_name email = user.email now = datetime.datetime.now() name = first_name amount = payment.amount ref = payment.ref ramount = amount first_name = request.user.first_name last_name = request.user.last_name headers = { "authorization": f"Bearer Pubpaynowxxx04970xxxxxx", "MerchantId": "352789092", "Content-Type": 'application/json' } data = { "reference": ref, "mchShortName": name, "productName": "Balance Deposit", "productDesc": "simply deposit now", "userPhone": "+19876543210", "userRequestIp": "123.123.123.123", "amount": ramount, "currency": "USD", "payTypes": ["BalancePayment", "BonusPayment", "OWealth"], "payMethods": ["account", "qrcode", "bankCard", "bankAccount", "bankTransfer", "bankUSSD"], "callbackUrl": "https://callbackurl.com/callbackUrl", "returnUrl": "https://myreturnurl.com/returnUrl", "expireAt": "10" } url = 'https://cashierapi.paynow.com/api/v3/cashier/initialize' response = requests.post(url, json=data, headers=headers ) return response else: form = PaymentForm(request.POST) return render(request, 'paynow/paynow_initiate_payment.html', {'form': form}) How do i resolve this issue where my … -
OOP Python Diango Help Beginner
I am starting learning python. I have learned the basics and now want to create a simple project. My idea is to create a project for my lessons. What I mean, is, at school we have subject (maths, geo, history, ...). I want to store a lesson for each of my subject. For example, each time I have a new lesson, I will store that lesson in my database under label (math, geo, ...). For each lesson, I will have sentences (my summary for each lesson) and also some lessons will have graphes and images. So, I have build a database: Table for Lesson (id_lesson, Subject, date, grade, id_sentences, id_graphs) Table for Sentences (id_sentence, id_lesson) (non-sql as each class can have multiples sentences. If it is wrong please help me how to do it :) Table for Graphs (id_graphs, id_lesson) (non-sql as each class can have multiples graphs. If it is wrong please help me how to do it :) Now I have to create the classes for my project (python) and then in django to have an interface to be more nice :) I don't know how to use inheritance in my case. class Lesson: def __init__(self, subject): self.subject … -
UnicodeDecodeError, 'utf-8' codec can't decode byte 0x80 despite using ignore as error handler in decode
I am running a redis_instance I just flushed. When I run keys * to check what key values I have I receive this output 1) "pairprogramming:1:views.decorators.cache.cache_page..GET.3ab7bc76b513f7063fc20ab3fdb2d22b.d41d8cd98f00b204e9800998ecf8427e.en-us.UTC" 2) "pairprogramming:1:views.decorators.cache.cache_header..3ab7bc76b513f7063fc20ab3fdb2d22b.en-us.UTC" 3) "pairprogramming:1:views.decorators.cache.cache_page..GET.146382e9a37a1da80e630eb042e9e924.83bf0aec533965b875782854d37402b7.en-us.UTC" 4) "pairprogramming:1:views.decorators.cache.cache_header..146382e9a37a1da80e630eb042e9e924.en-us.UTC" 5) "pairprogramming:1:views.decorators.cache.cache_page..GET.21d502855d4ad5b0f631c20fc5e899c6.65330eb47d0175f264fdb29633829c0b.en-us.UTC" 6) "pairprogramming:1:views.decorators.cache.cache_header..21d502855d4ad5b0f631c20fc5e899c6.en-us.UTC" I assume each time I try to make a GET request that attempt is written into my redis_instance? This is besides the point, the problem I am having is that when I try to do a GET request, I expect to receive this: {"count":0,"msg":"Found 0 items.","items":{}} However, I am getting this error: UnicodeDecodeError at /cache/ 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte This is the offending line/characters The string that could not be encoded/decoded was: ��� I have tried to change the default error handler to: ignore, replace, backslash, but keep getting the same error. This is how my code looks currently: @api_view(['GET', 'POST']) def manage_items(request, *args, **kwargs): if request.method == 'GET': items = {} count = 0 for key in redis_instance.keys("*"): items[key.decode("utf-8", errors='ignore')] = redis_instance.get(key) count += 1 response = { 'count': count, 'msg': f"Found {count} items.", 'items': items } return Response(response, status=200) elif request.method == 'POST': item = json.loads(request.body) keys = list(item.keys()) values = list(item.values()) for i … -
Django django.db.utils.IntegrityError: duplicate key value
I have a problem with simple user model.I wrote a test for email normalize function and in response i've got a " django.db.utils.IntegrityError: duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=() already exists. " When I added a "user.delete()"after "self.assertEqual(user.email, expected)" all test passed.What is wrong ? Is that test creates users with the same username field ? Models.py class UserManager(BaseUserManager): """Manager for user""" def create_user(self, email, password=None, **extra_fields): user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser, PermissionsMixin): """User model""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' test.py class ModelTest(TestCase): def test_create_user_with_email(self): """Testing creating user with email address""" email = 'testaddress@example.com' password = 'testpassword1234' user = get_user_model().objects.create_user( email=email, password=password, ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_user_email_normalized(self): """Testing email normalize function""" test_emails = [ ['test1@EXAMPLE.Com', 'test1@example.com'], ['TesT2@exaMple.com', 'TesT2@example.com'], ] for email, expected in test_emails: user = get_user_model().objects.create_user(email, 'password123') self.assertEqual(user.email, expected) user.delete() -
socket.gaierror: [Errno -2] Name or service not known when try to establish socket connection with js client to django running in docker container
1- I have a django project which is running in docker container in localhost on port 8000 2- And I have a react app which is running in localhost on port 3000 I want to establish socket connection between react app and django with this command react app const chatSocket = new WebSocket( 'ws://' // + window.location.host + 'localhost:8000' + '/ws/room/' ); chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); if (data.message) { // document.querySelector('#chat-messages').innerHTML += ('<b>' + data.username + '</b>: ' + data.message + '<br>'); } else { alert('The message is empty!'); } }; chatSocket.onclose = function(e) { console.log('The socket close unexpectadly'); }; const handleNewUserMessage = (message) =>{ chatSocket.send(JSON.stringify({ 'message': message, 'username': username, 'room_name': roomName })); console.log("received"); } and django files are like below: asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing from .settings import ASGI_APPLICATION os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Irangard.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ) }) routing.py from django.urls import path from chat.consumers import ChatConsumer websocket_urlpatterns = [ path('ws/room/', ChatConsumer.as_asgi()), ] consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): # self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_name = 'emad12' self.room_group_name = 'chat_%s' % self.room_name # Join room async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) … -
Two variables in for loop for django form request
As the title says I am trying to use 2 variables in for loop in a django view. The django view takes 2 inputs from the html form and insert the received data into the django model. I tried using zip() and itertools.product() but they do not seem to work, I also tried nesting them as well as using 2 different for loops, but that also does not seem to work, is there a way to do this? Code as follows, template.html {% extends 'staff/base.html' %} {% load crispy_forms_tags %} {% block title %}Sem-1 Attendance{% endblock %} {% block content %} <h1>Semester 1 Attendance:</h1> <hr /> <form method="POST"> {% csrf_token %} <select name="subject" class="select form-select" id="id_subject"> <option value="ENGINEERING MATHEMATICS">ENGINEERING MATHEMATICS</option> <option value="FUNDAMENTALS OF COMPUTER">FUNDAMENTALS OF COMPUTER</option> <option value="FUNDAMENTALS OF ELECTRICAL &amp; ELECTRONICS ENGINEERING LAB" > FUNDAMENTALS OF ELECTRICAL &amp; ELECTRONICS ENGINEERING LAB </option> <option value="IT SKILLS LAB">IT SKILLS LAB</option> <option value="ENVIRONMENT SUSTAINABILITY"> ENVIRONMENT SUSTAINABILITY </option> </select> <table class="table table-bordered"> <thead> <th>Roll Number</th> <th>Status</th> </thead> <tbody> {% for x in at1 %} <tr> <td> <input class="form-control-plaintext" type="text" name="roll_no" id="roll_no" readonly value="{{ x.roll_no }}" /> </td> <td> <input class="form-check-input" type="checkbox" value="absent" id="absent" name="absent" /> <label class="form-check-label" for="flexCheck"> Absent </label> </td> </tr> {% …