Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> {% … -
Openpyxl Django
Trying to automate modifying an Ecxel file using openpyxl lib and below code works: def modify_excel_view(request): wb = openpyxl.load_workbook('C:\\my_dir\\filename.xlsx') sh1 = wb['Sheet1'] row = sh1.max_row column = sh1.max_column for i in range(2, row + 1): # ...some_code... wb.save('C:\\my_dir\\new_filename.xlsx') return render(request, 'my_app/convert.html', {'wb': wb}) But how to implement a similar method without static (hardcoding) path to file and a filename? Like choosing xlsx file from modal window? Saving modified copy on a desktop by default? (Maybe like 'ReportLab library': response.write(pdf)=>return response. And it saving on the desktop by default.) Thank you in advance! -
Django server won't load
I am trying to run my django server using the python manage.py runservercommand. Keep getting this error in my shell. The development server is refusing to load. The image is the error message I'm getting -
Can't access Django admin page it gives an error as below
enter image description here enter image description here enter image description here Can't access Django admin page it gives an error as above . Please help me! -
Django register users
I'm building a social media app and I want to create users without using the user creation form so I can build my own form. I am using. User.objects.create_user() however when I put User.objects.create_user(username=request.POST['un']) I get this error 'UNIQUE constraint failed: auth_user.username'. When I just pass a string it works fine however when I use the form data it doesn't. -
Django popup error message on same email submit
am wondering how i can get a popup message to tell the user this email is already registerd. I got this in my models.py and the unique=True is blocking same email signup all i need is some code to let the user know it already signed up how can i do this? models.py from django.db import models class Subscriber(models.Model): email = models.EmailField(max_length=255, unique=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % self.email -
Adjust number of fields of the form based on the argument in the view
I have a form with 4 fields. class data_collect_form(forms.Form): data_entry1 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0})) data_entry2 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0}) data_entry3 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0}) data_entry4 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0})) Based on the argument "number_of_fields" in the view, I would like to delete last fields of this form. Here is the view: def add_submission(request, number_of_fields ): #delete number of fields according to number_of_fields argument if request.method == 'POST': form2 = data_collect_form(request.POST) else: form2 = data_collect_form() return render(request, 'main/second.html',{"form2":form2) I am sure it should be possible with the __init__ method, but I do not have understanding on writing it correctly. -
i have a proplem with django python
comments = project.masarif.filter(active=True) def sub_masarif(): for sub in comments: total = 0 xdd = sub.count total += (xdd) print(total) # 3 4 69 i need sum total < example print(total) # 76 -
Django Rest API login using multiple password
I have one type of login idea, One single User has multiple Accounts (OneToOne or Foreign Key). To save UserEmail I use the default User table. UserID is PrimaryKey on the User table. In the Account table, Account__UserID is ForeignKey assigned to the User table. Now Account table AccountID PrimaryKey is assigned as ForeignKey for other tables(e.g: Transaction table have Transaction ID, AccountID, TransactionAmount. In Transaction table AccountID ForeignKey of Account table). When the user login by using the User table UserPassword. The user gets a list of Account table data. Account table PrimaryKey AccountID as ForeignKey for Transaction table, so users now get List Account & List Transaction data (It's default login method). When the user login by using the Account table AccountPassword. The user gets only one Account data. so now user get only one Account & List Transaction data (Account-based login) Now I did the default login method, it's an easy one. My question is, how I can do Account-based login. -
How to integrate Django API with XMPP server (ejabberd)
I'm currently working on a project where I'm using Django rest framework (DRF) for the backend. I need to implement one to one chat on this application. For this, I'm using XMPP server. I'm using ejabberd as XMPP server. Now, I need to create users in the ejabberd server using my API built with DRF. I need to achieve following things with my API: create new users in the ejabberd server create rooms in the ejabberd server fetch all the available rooms. The username will be fetched or retrived from the frontend. Is there any Python API client or Django API client to do this in the ejabberd server? Like how there is simple-xmpp for node js I have seen many python packages for this. some of them are, pyjabberd xmppy django-xmpp I'm not sure which one to use and I don't know whether is it possible to implement the above using any of these packages. -
Starting RabbitMQ and Celery for Django when launching Amazon Linux 2 instance on Elastic Beanstalk
I have been trying to setup celery to run tasks for my Django application on Amazon Linux 2. Everything worked on AL1, but things have changed. When I SSH into the instance I can get everything running properly - however the commands upon deployment do not work properly. I have tried this in my .platform/hooks/postdeploy directory: How to upgrade Django Celery App from Elastic Beanstalk Amazon Linux 1 to Amazon Linux 2 However that is not seeming to work. I have container commands to install epel, erlang and rabbitmq as the broker - they seem to work. After that answer, @Jota suggests: "No, ideally it should go in the Procfile file in the root of your repository. Just write celery_worker: celery worker -A my_django_app.settings.celery.app --concurrency=1 --loglevel=INFO -n worker.%%h. Super simple." However would I include the entire script in the procfile or just the line: celery_worker: celery worker -A my_django_app.settings.celery.app --concurrency=1 --loglevel=INFO -n worker.%%h This seems to suggests it would just be the command: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html Then where would the script be if not in the procfile with the above line? -
Disabling a crispy form field from showing errors
I have a form to perform searching. As I am using the primary key to search, The searching process is completed successfully BUT I used to get an error below the text field saying Invoice number already exists. I did some tweaks and stopped the form from showing errors but the text field still has a red outline whenever I perform the searching operation. How can I stop the form from doing that? The code in the forms.py that disabled the form to show field errors: class InvoiceSearchForm(forms.ModelForm): generate_invoice = forms.BooleanField(required=False) class Meta: model = Invoice fields = ['invoice_number', 'name','generate_invoice'] def __init__(self, *args, **kwargs): super(InvoiceSearchForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_errors = False self.helper.error_text_inline = False self.form_error_title=False The HTML code that deals with the search operation: <div class="myForm"> <form method='POST' action=''>{% csrf_token %} <div class="row"> <div class='col-sm-12'> <div class="form-row"> <div class="form-group col-md-3"> {{ form.invoice_number|as_crispy_field }} </div> <div class="form-group col-md-3"> {{ form.name|as_crispy_field }} </div> <div class="form-group col-md-3"> {{ form.generate_invoice|as_crispy_field }} </div> <div class="form-group col-md-3"> <br> <button type="submit" class="btn btn-primary">Search</button> </div> </div> </div> </div> </form> </div> The views.py related to the search operation: @login_required def list_invoice(request): title = 'List of Invoices' queryset = Invoice.objects.all() form = InvoiceSearchForm(request.POST or None) context = { … -
How to set the fetched value of dropdown to dropdown in edit module?
Here is the photo of dropdown where I want to fetch the data from database : - https://drive.google.com/file/d/1ko15oCmKSuOiCmkFq1v0INDGgk70EzF6/view?usp=sharing html page : - <label>Country</label> <select id="countryId"> <option value="{{vr.country}}" >Select Country</option> </select> <label>State</label> <select id="stateId"> <option value="{{vr.state}}">Select State</option> </select> <label>City</label> <select id="cityId"> <option value="{{vr.city}}">Select City</option> </select> I've done this so far to fetch the records from database but i'm not geeting the values in to the dropdown list. Also, I'm geeting all the other values correctly but not getting the value in dropdown only. So, what should I do to set default selected value in dropdown? (if anyone wants more details please comment after this post.) -
{% if user.is_authenticated %} Always return true
I am just trying to run a simple {% if user.is_authenticated %}. But it always returns true. what I want to do is to check if the user is logged in. if yes the Dashboard button should appear and if not the Register button should appear. Can you help me here! Here are my files: vews.py : from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def login(request): return render(request, 'authorisation/login.html', {}) def register(request): if request.method == 'POST': email = request.POST['email'].replace('', '').lower() password1 = request.POST['password1'] password2 = request.POST['password2'] if not password1 == password2: messages.error(request, "Passwords doesn't match") return redirect('register') if User.objects.filter(email=email).exists(): messages.error( request, "A user with the email address : {} already exists, please use a different email".format(email)) return redirect('register') newUser = User.objects.create_user( email=email, username=email, password=password2) newUser.save() auth.login(request, newUser) return redirect('home') return render(request, 'authorisation/register.html', {}) My HTML page : {% if user.is_authenticated %} <li class="nav-item"> <a class="btn btn-primary ml-lg-2" href="#">Dashboard</a> </li> {% else %} <li class="nav-item"> <a class="btn btn-primary ml-lg-2" href="{% url 'register' %}">Register</a> </li> {% endif %} It always returning The Dashboard -
How to use Bengali date in django
In Django Framework how to use Bengali months date. Bengali Month Like Baishak, Joishto etc.Someone help me. I know how to use local time. -
Setting the variable with the form and its zeroing after a few hours
I have created an app using Django, I have a variable that I set using a form for more security. But after a few hours, I check its value and see that it is zero. Every time I set the value, after a while the value becomes zero I have published this app on the host -
Multidimensional dictionary losing lower levels after for loop in the django template
I have a dictionary of players and their inventory. There is a lower level dictionary for each item with the needed values. On the template I would like to do a for loop through each item and get their dictionaries. I will give a simplified example which hopefully makes it clearer to understand. Please let me know if there is something unclear about my question or examples. views.py players = {} players[1] = {} players[1].update({ 'avatar': user.avatar, 'username': user.username, players[1]['items'] = {} players[1]['items'][item.id] = {} players[1]['items'][item.id].update({ 'item_name' = item.name, 'item_value' = item.value, }) }) template.html {% for item in players.1.items %} {{item}} <!-- Gives me item ids --> {{item.1.item_name}} <!-- I would expect that to give me the value of item_name, instead I get nothing --> {% endfor %} {{players.1.items.1.item_name}} <!-- This works as it gives me the result I am expecting -->