Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
BigIntegerField becomes serial4 on Postgresql
Setting the type of primary keys as BigIntegerField id = models.BigIntegerField(primary_key=True) makes the type of the files serial4 at the Postgresql database. Also the foreign keys have type int4 instead of the expected bigint. BigIntegerField serial4 -
Update into existing database not working
I have a page where the users can add a new mco number, when the user click on the Add mco button, it will retrieve the id as shown below: but when the user add the new mco number and click on the submit button, it will create another row and not update into the id database as shown below, why is that so and how do I solve this issue? views.py @login_required() def AddMCO(request, id): photo = get_object_or_404(Photo, id=id) if request.method == "POST": form = AddMCOForm(request.POST) if form.is_valid(): mcoNum = form.cleaned_data['mcoNum'] form.save() return redirect('ViewMCO') else: form = AddMCOForm() context = { "form": form, "photo": photo } return render(request, 'AddMCO.html', context, ) forms.py class AddMCOForm(forms.ModelForm): mcoNum = forms.CharField( label='Enter MCO Number', widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Please enter MCO Number here..' } ) ) class Meta: model = Photo fields = ("mcoNum",) def __init__(self, *args, **kwargs): super(AddMCOForm, self).__init__(*args, **kwargs) self.fields['mcoNum'].widget.attrs.update({'class': 'form-control', 'placeholder': 'MCO Number'}) self.fields['mcoNum'].label = '' self.fields['mcoNum'].help_text = '' AddMCO.html <!DOCTYPE html> <html> <head> <script> $(function () { $("#datetimepicker1").datetimepicker(); }); </script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>SCS Add MCO</title> <meta name='viewport' content='width=device-width, initial-scale=1'> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" … -
Django Login Authentication: I am able to SignUp new user and create new user as well but UNABLE to login as SignUp user
Django Login Authentication: I am able to SignUp new user and create new user as well but UNABLE to login as SignUp user My views.py for handlelogin def handlelogin(request): if request.method == 'POST': loginemail= request.POST['loginemail'] loginpass = request.POST['loginpass'] user = authenticate(request, username=loginemail, password=loginpass) if user is not None: print(loginemail, loginpass) login(request, user) messages.success(request, "Successfullly Logged-In") return redirect('/') else: messages.error(request, "Invalid Credentials, Please Try Again") return redirect('/') return HttpResponse('404 - Page Not Find') I have tried print() statement to check , and it do work in else statement only ,not in if user is not none. NOTE: THE SYNTAX IN QUESTION IS LITTLE BIT DISTURBED ...BUT IN CODE IT IS COMPLTELY FINE. -
get user location django
I want to create a site where I can get the exact location of the user with Django and Python.Here is a method, but it uses Google Maps. I want to use Open Street Map and I do not want to use Google Map. How can I do this? Thanks -
I want to create an inframe for all the products
My main objective is to create an iframe for all products page, like the iframe code will be stored in a textbox area from where the user can copy the code and paste it to their websites or in any of their other platform. The project is in python, django for web development. I want to create an iframe where the values will be as: There will be an image of the product There will be an Visit button below the image, and Anchor to the target link of the product details page. I tried to achieve but the iframe content is not been rendered or shown to the HTML page. Or, I have seen the iframe plugin in Django. Will it be more efficient to follow Django's iframe-plugin or the same will be as the element of HTML. -
having problem loading url from the views and url in django
I am building a webpage from a custom bootstrap template available freely in GitHub. I have tried to connect Django to the back end. I am facing problem using urls and views. I have mentioned perfectly but i am getting page not found. urls.py file from django.urls import path, include from django.conf.urls.static import static from . import views urlpatterns = [ path('', views.homepage, name='homepage'), path('publications', views.publications, name='publications'), path('alumni', views.alumni, name='alumni'), path('contact', views.contact, name='contact'), path('joinus', views.joinus, name='joinus'), path('phdstudents', views.phdstudents, name='phdstudents'), path('pi', views.pi, name='pi'), path('project1', views.project1, name='project1'), path('research', views.research, name='research'), path('researchers',views.researchers, name='researchers'), path('shiladit', views.shiladit, name='shiladit'), path('students', views.students, name='students'), path('team', views.students, name='team'), ] views.py from django.shortcuts import render def homepage(request): return render(request, 'lab/index.html') def publications(request): return render(request, 'lab/publications.html') def alumni(request): return render(request, 'lab/alumni.html') def contact(request): return render(request, 'lab/contact.html') def joinus(request): return render(request, 'joinus.html') def phdstudents(request): return render(request, 'phd_students.html') def pi(request): return render(request, 'lab/pi.html') def project1(request): return render(request, 'lab/project1.html') def publications(request): return render(request, 'lab/publications.html') def research(request): return render(request, 'lab/research.html') def researchers(request): return render(request, 'researchers.html') when i click on the navbar to redirect the page i am getting error. but when i give the url it is loading how to rectify this. -
Django websocket ValueError
When I access a websocket on a non-existent put (ws://127.0.0.1:8000/ws/dgd/), django raises an error Is this normal behavior or should I handle this case? 2021-10-04 11:35:46 ERROR server Exception inside application: No route found for path 'ws/dgd/'. Traceback (most recent call last): File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/Users/934214/PycharmProjects/uhrg_2.0/venv/lib/python3.9/site-packages/channels/routing.py", line 168, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/dgd/'. routing.py websocket_urlpatterns = [ re_path(r'^ws/user/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$', consumers.UserConsumer.as_asgi()), ] settings.py CHANNEL_LAYERS = { 'default': { "BACKEND": "channels.layers.InMemoryChannelLayer" }, } asgi.py application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websockets.routing.websocket_urlpatterns ) ), }) -
How do I assign a value to a model field that is the concatenation of two other model fields?
I'm developing a booking system as part of my portfolio. It allows a user (company) to book time slots for deliveries that will be made to a distribution center (DC) on a specific date & time. Models.py from django.db import models from django.utils import timezone from django.urls import reverse import datetime as dt from django.contrib.auth.models import User # Create your models here. class Booking(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateTimeField() delivery_time = models.TimeField() booking_number = models.CharField(max_length=50) def __str__(self): self.booking_number = # How to concatenate delivery_date and delivery_time? return self.booking_number def get_absolute_url(self): return reverse("booking_detail",kwargs={'pk':self.pk}) forms.py from django import forms from bookmyslot.models import Booking from bootstrap_datepicker_plus import DatePickerInput import datetime as dt HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)] class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('qty_plts','cbm','booking_date','booking_time') widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6]}), 'delivery_time':forms.Select(choices=HOUR_CHOICES)} What I would like to do is assign a value to the booking_number field that is a concatenation of the delivery_date and delivery_time fields. So, if the customer is able to successfully book a slot at the requested delivery date & time, a unique booking number is generated as per above. How can I do this? If possible, … -
POST for Django API but require multiple inputs while my model only have 1 field that is able to take in inputted data
I am facing a issue right now on API post for @api_view[('POST'). I have the following codes: models.py class Job(models.Model): datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters'] As you can see there is only 1 field. But i dont know how to set up my @api_view['(POST)'] to do the same thing as my html because my html for this looks like this: Upon clicking the save button, I have to get the individual inputs from the textbox, textarea, dropdown box and convert it into the following : Example - {'device': 177, 'configuration': {'port_range': 'TenGigabitEthernet1/0/1,TenGigabitEthernet1/0/2,TenGigabitEthernet1/0/3,TenGigabitEthernet1/0/4,TenGigabitEthernet1/0/5', 'port_mode': 'Access', 'port_status': 'Disabled', 'port_param1': 'Test\r\n1\r\n2\r\n3', 'port_param2': 'Test\\n1\\n2\\n3'}} But how do I do the same thing in my API view if it doesnt follow how my html look like with so much input areas? -
Why graphene enum returns value instead key for my ENUMS key?
When i post data it return the value of the enum For example when i choose PL it returns the "Poland".I want to get the key of the enum instead of the value. I need PL instead of "Poland. Here is the code **This is my models** class Candidate(models.Model): class CountryChoices(models.TextChoices): PL = "Poland" DK = "Denmark" FI = "Finland" ---------- **This is my enums** class CandidateCountry(graphene.Enum): PL = "Poland" DK = "Denmark" FI = "Finland" residence_country = models.CharField( max_length=100, choices=CountryChoices.choices, null=True, blank=True) ---------- -
Django Rest Framework how to request [GET, POST, PUT, PATCH] from two different projects?
Here, I have two different services(Projects) running, Project A = Auth Server (which manages project auth-system) Project B = Products CRUD (Project A checks the credentials, then users can do crud Project B) Is there any example or document regarding this type of problem? Is there any way of communicating between the two projects? How can we fetch data from other projects or other project's endpoint and can check in Project B. -
Jinja template groupby sorting issue
In this code block, I have grouped by headings. But I want to sort the titles in array index order. Not alphabetically. {% set list = widget.attributes.faq_item %} {% for title_group in list|groupby('value.main_title') %} <h2 class="account-sss__title">{{title_group.grouper}}</h2> {% for item in title_group.list %} <a href="#" class="account-sss__list--link js-link"> {{item.value.question}} </a> <div class="account-sss__content js-account-sss__content"> {{item.value.answer}} </div> {% endfor %} {% endfor %} -
Refused to apply style because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled
Hello guys i'm working in a django project I get this error in all pages of my website here is my project organisation in base.html file i import css like this <link href="{% static '/store/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/> <link href="{% static '/store/css/business-casual.css' %}" rel="stylesheet" type="text/css"/> thank you -
How to implement url template loading of django in javascript?
I have built a chat app like WhatsApp using Django channels, redis and websockets. It includes features like private and public chat. The user also can send images in chat. The UI is designed such that the sender's message is on the right hand side and the receiver's message is on the left hand side. What I want? I want to add a feature such that the user can delete each and every text message. I have added a delete button (looks like circle containing cross symbol) after each chat. The delete action is happening only after refreshing the page. I want it to happen without refreshing the page. Therefore, I want to add url template loading in javascript but it is not working. It is showing errors like "Could not parse the remainder" (django error) or "$ is not defined" (javascript error). I have tried all the solutions mentioned here. My code in room.html This code is of Group Chat {% block content %} <br><br> {% include 'message.html' %} <div class="container mb-5" style="max-width: 600px;"> <form> <div> <label class="h4 pt-5">Public Chatroom</label> <div class=" border border-primary border-2" placeholder="Chat Screen" id="chat-text" style=" height: 400px; overflow-y: scroll;"> {% if group_messages %} {% for … -
Is it possible to host a django project on firebase ? if yes please share the steps?
Is it possible to host a django project on firebase ? if yes please share the steps ? -
how to get new data at run time from django?
I am working on a Django project with ReactJs frontend. I have to built a simple chat application in that project where users can communicate with each other. in django views I have following function to read messages Views.py class MessagesListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): condition1 = Q(sender=15) & Q(receiver=11) condition2 = Q(sender=11) & Q(receiver=15) return Messages.objects.filter(condition1 | condition2) serializer_class = MessagesSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) this gives me all the messages between user 11 and user 15. on frontend I am getting these messages from rest Api by calling above function frontend const chatApi = axios.create({ baseURL: 'http://localhost:8000/chat/' }) const getMessages = async() => { let data = await chatApi.get(`MessageRead/`).then(({data})=>data); setMessages(data); } I am calling this function in an onClick event of button. and displaying the messages by maping messages array. problem is that at the time when these messages are open to the user. at that time if a new message(data) is added in database. I have to press that button again and call getMessages function again to display that message. Is there a way to automatically get that new message(record) without calling this function again by pressing a … -
how can we add sqlformat.exe in path and django-admin.exe in path?
Installing collected packages: sqlparse, pytz, asgiref, django WARNING: The script sqlformat.exe is installed in 'C:\Users\Slug\AppData\Roaming\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. WARNING: The script django-admin.exe is installed in 'C:\Users\Slug\AppData\Roaming\Python\Python310\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. -
Fail to serve static files in deployed Django app (Docker, gunicorn, whitenoise, Heroku)
I have built a Django REST API which serves JSON responses only. My problem is, in production (deployed on Heroku with debug=False) the app does not seem to serve relevant static files needed for the proper styling of the admin interface (only use case for static files). Note, in development (localhost with debug=True) the admin interface is properly styled. Going to the admin route at the deployed (Heroku) address, the content is delivered but without any styling. The browser developer tools indicate that style sheets could not be loaded due to a 500 error code. Django logging output reveals the below detail. django.request ERROR Internal Server Error: /static/admin/css/base.1f418065fc2c.css Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/secure_my_spot/custom_middleware/request_logging.py", line 30, in __call__ print(f"Content: {response.content}") File "/usr/local/lib/python3.8/site-packages/django/http/response.py", line 407, in content raise AttributeError( AttributeError: This WhiteNoiseFileResponse instance has no `content` attribute. Use `streaming_content` instead. I have gone into the Heroku dyno and verified that the static files, which cause the 500 error, are in fact in the static_root as per Django's settings.py. I have been spending a significant amount of time scouring the internet for clues as to what might cause the files to not … -
Multiple models in a queryset and/or multiple serializers for one View?
Say I have a Foo model and a Bar model: # models.py class Foo(models.Model): foo_title = CharField() class Bar(models.Model): bar_title = CharField() # serializers.py class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ["foo_title"] class BarSerializer(serializers.ModelSerializer): foo = FooSerializer() class Meta: model = Bar fields = ["bar_title"] If I want to return a Foo and a Bar model, I have to set up and call two views: # urls.py path("foo/<pk>/", FooView.as_view()) path("bar/<pk>/", BarView.as_view()) # views.py class FooView(generics.RetrieveAPIView): serializer_class = FooSerializer lookup_field = pk class BarView(generics.RetrieveAPIView): serializer_class = BarSerializer lookup_field = pk And then combine the two data results on my front-end. Is it possible to create one View that has multiple models in the queryset and/or multiple serializers? How can I make only one call to my API backend to return the data of different serializers with different models? e.g. Something like # urls.py path("foobar/<foo_pk>/<bar_pk>", FoobarView.as_view()) # views.py class FoobarView(generics.ListAPIView): pass -
How to horizontally align buttons in different elements
I have 3 buttons in different divs with different content. I would like all the divs to be the same height and to horizontally align the 3 buttons. Below is an image that shows the current page, and the desired page with the styling I'd like to achieve. But I just added margins manually in the dev console, so it's not using best practice (see the below image to see how it looks on an Ipad, not very good). And here is what it looks like on ipad (because i just manually added margin-top to each div). Does anyone know the proper way to achieve this? Below is the code: <html> <head> <meta content="width=device-width, initial-scale=1" name="viewport" /> <style> @import url(https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css); @import url(https://fonts.googleapis.com/css?family=Raleway:400,500,800); @import url(https://fonts.googleapis.com/css?family=Montserrat:800); .snip1214 { font-family: 'Raleway', Arial, sans-serif; color: #000000; text-align: center; font-size: 16px; width: 100%; max-width: 1000px; margin: 40px 0 40px 0; } /* MOBILE CUSTOMIZATIONS */ @media screen and (max-width: 767px) { .snip1214 .plan { width: 90%; margin: 0 auto; margin-bottom: 90px; background-color: #ffffff; } } @media screen and (min-width: 768px) { .snip1214 .plan { min-height: 350px; max-height: 350px; margin: 0; width: 33%; float: left; background-color: #ffffff; border: 1px solid rgba(0, 0, 0, 0.1); } .plan-select … -
the value 0.01 not retrieving in python django
model.py class Memopayment(models.Model): tp = models.DecimalField(max_digits=5, decimal_places=3) example.html <td>{{ m.tp|floatformat:3 }}</td> I have entered 0.01 in entry.html but the value retrieved is 0.000 instead of 0.010 Please help me in solving the issue. -
Django - Support query parameter list
I am in the process of migrating a NodeJS backend to a Django backend (DRF). There are some legacy API's I have to support for older app versions. One of them involves reading a list in the query params. "/questions/?questionIds[]=abc&questionIds[]=xyz" I know this is not the way Django handles list in query params but I still have to support it for legacy reasons. When I try to read this using request.query_params["questionIds"] it gives me an error django.utils.datastructures.MultiValueDictKeyError: 'questionIds' Is there any way in which I could support this or is it not possible using Django? -
Django Select from a Subquery
I want to query with window function and then do some group by aggregation on the subquery. But I couldn't make it with ORM method. It will return aggregate function calls cannot contain window function calls Is there any way to make a query like SQL below without using .raw() SELECT a.part_id, AVG(a.max_count) FROM ( SELECT part_id, MAX(count) OVER (PARTITION BY part_id ORDER BY part_id) AS max_count FROM table_one ) a GROUP BY a.part_id -
AttributeError: 'AnonymousUser' object has no attribute '_meta' Django channels
I am trying to login users in django channels and its throwing AttributeError: 'AnonymousUser' object has no attribute '_meta' My Consumer class LoginConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = "login_room" self.room_group_name = "login_group" await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() await self.send(json.dumps({"message": "connected to login socket"})) async def receive(self, text_data): self.json_data = json.loads(text_data) await login(self.scope, await self.query()) await database_sync_to_async(self.scope["session"].save)() async def query(self): await self.get_user_from_db() @database_sync_to_async def get_user_from_db(self): user = User.objects.get(username=self.json_data["username"]) return user async def disconnect(self, code): print("disconnected") await super().disconnect(code) My login view def login_user(request): if request.user.is_anonymous: if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("index") else: messages.error(request, "invalid username or password") return redirect("login") return render(request, "login.html") else: return redirect("index") My js file const username = document.querySelector(".username"); const password = document.querySelector(".password"); const socket = new WebSocket("ws://localhost:8000/ws/auth/login"); const button = document.querySelector("button"); button.addEventListener("click", (e) => { if (password.value !== "" && username.value !== "") { socket.send( JSON.stringify({ username: username.value, password: password.value, }) ); } }); Full Traceback: Exception inside application: 'AnonymousUser' object has no attribute '_meta' Traceback (most recent call last): File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/__neeraj__/.local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, … -
Where are the Django and python files?
I'm new to Django and Python, i'm coming from Laravel. I'm working on a Windowsmachine. My Laravel project has tons of folders (vendor etc.) and is >100 MB my Django project is <50kB. In the end i want to upload my Django project to a webserver. But i'm curios where the Djangofiles on my computer are located, and how deployment works. (what are the essential parts/files compared to laravel (Project Folder + DATABASE) which i've to transfer) Is the DjangoFramework similar like a Javascript file, which i can put i my project folder or get it via linking?