Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App loaded in Django admin, but doesn't showing up
I am trying to add my app to django admin panel. I have 3 apps: users orders advertisements All this applications loaded in settings.INSTALLED_APPS correctly, but django-admin showing up only two apps: users and orders. The most interesting in this situation is that in source code of html file for django-admin panel all apps are loaded, but app advertisements doesn't showing up. As you can see below, code for advertisements app is loaded in html file. When I try to go on links for this app in a tags, i see only white screen on opened page, but source code for page is loaded too. Thanks a lot for any help. <div id="content-main"> <div class="app-advertisements module"> <table> <caption> <a href="/admin/advertisements/" class="section" title="Models in the Advertisements application">Advertisements</a> </caption> <tr class="model-advertisingspacecategory"> <th scope="row"><a href="/admin/advertisements/advertisingspacecategory/">Advertising space categorys</a></th> <td><a href="/admin/advertisements/advertisingspacecategory/add/" class="addlink">Add</a></td> <td><a href="/admin/advertisements/advertisingspacecategory/" class="changelink">Change</a></td> </tr> <tr class="model-advertisingspace"> <th scope="row"><a href="/admin/advertisements/advertisingspace/">Advertising spaces</a></th> <td><a href="/admin/advertisements/advertisingspace/add/" class="addlink">Add</a></td> <td><a href="/admin/advertisements/advertisingspace/" class="changelink">Change</a></td> </tr> </table> </div> <div class="app-auth module"> <table> <caption> <a href="/admin/auth/" class="section" title="Models in the Authentication and Authorization application">Authentication and Authorization</a> </caption> <tr class="model-group"> <th scope="row"><a href="/admin/auth/group/">Groups</a></th> <td><a href="/admin/auth/group/add/" class="addlink">Add</a></td> <td><a href="/admin/auth/group/" class="changelink">Change</a></td> </tr> </table> </div> <div class="app-orders module"> <table> <caption> <a href="/admin/orders/" class="section" title="Models in the Orders … -
Howto Python Request in Django
I am very new to Django, I am trying to request informations from another side to display them on my own. My site works and outside of Django I can request. I have no idea how to request and display the informations in Django neither where to do this in the project. Please help. models.py: from django.db import models class Form(models.Model): ipName = models.CharField(max_length=100) ipAddress = models.CharField(max_length=100) ipKey = models.CharField(max_length=100) ipSecret = models.CharField(max_length=100) ipMask = models.CharField(max_length=100) ipWahrheit = models.BooleanField(default=True) def __str__(self): return self.ipName views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Form import requests def home(request): context = { 'ox': Form.objects.all() } return render(request, 'Ips/home.html', context) home.html: {% extends "Ips/Ips.html" %} {% block content %} {% for ip in ox %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ ip.ipName }}</a> <small class="text-muted">{{ ip.ipAddress }}</small> </div> <p class="article-content">{{ ip.ipName }}</p> </div> </article> {% endfor %} {% endblock content%} With the Informations i get from Form i want to make an request to that Ip address and get back a jason. -
Django contact form sending email back to my own email address
views.py def contact(request): if request.method == "POST": username = request.POST['username'] phone = request.POST['phone'] customer_email = request.POST['customer_email'] subject = request.POST['subject'] message = request.POST['message'] #send Email send_mail(subject, message, customer_email, ['myemail@gmail.com']) return render(request, 'contact.html', {'username': username }) else: return render(request, 'contact.html', {}) This is my html <form method="post" action="{% url 'contact' %}" id="contact-form"> {% csrf_token %} <div class="row clearfix"> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="username" placeholder="Name" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="phone" placeholder="Phone" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="email" name="customer_email" placeholder="Email" required=""> </div> <div class="col-lg-6 col-md-6 col-sm-12 form-group"> <input type="text" name="subject" placeholder="Subject" required=""> </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group"> <textarea name="message" placeholder="Message"></textarea> </div> <div class="col-lg-12 col-md-12 col-sm-12 form-group"> <button class="theme-btn btn-style-one" type="submit" name="submit-form">Submit Now</button> </div> </div> </form> This is the form I have that should send an email to customer_email, but instead I am getting the email back to me. That is, sender and recipient are both same. What is the issue here. Also is it possible to add the customer's email and phone number in the email message itself. Kindly help. -
'ASGIRequest' object has no attribute 'Get'
Got an error when trying django (4.0.2), the error thrown was: 'AsgiRequest' object has no attribute 'Get' Running with channels 3.0.4, Django 4.0.2, python 3.8 Running via python3 manage.py runserver from django.shortcuts import render,redirect from django.contrib import messages from .models import * # Create your views here. def home(request): if request.method == 'post': username=request.POST.get('username') option=request.POST.get('option') room_code=request.POST.get('room_code') if option=='1': game=Game.objects.filter(room_code=room_code).first() if game is None: messages.success(request, 'Room code not found') return redirect('/') if game.is_over: messages.success(request, 'Game is over') return redirect('/') game.game_opponent=username game.save() else: game=Game(game_creater=username,room_code=room_code) game.save() return redirect('/game/'+room_code+'?username=' + username) return render(request, 'home.html') def game(request, room_code): username=request.Get.get('username') context={'room_code': room_code , 'username' : username} return render(request, 'play.html', context) -
Django Like Button Post not showing on html site
I have followed an online tutorial to add a like button to my website/index html file, but for some reason it is not showing on the site. It must be witht the url or views files, but I can not figure it out. Below is the code. The models that I am trying to pull are migrated and work. If anybody has any tips that I could try I woudl greatly apprechiate it. views file: **from django.shortcuts import render, redirect from django.http import JsonResponse import json import datetime from .models import * from .utils import cookieCart, cartData, guestOrder from .models import Post, Like # Create your views here. def index(request): return render(request, 'index.html', {}) def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'posts/postlike.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.filter(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('post-list')** urls file: **from django.urls import path from . import views from .views import post_view, like_post urlpatterns = [ path('', views.index, name='index'), path('store/', … -
collapsing accordion content in django for loop
I am trying to implement for loop in my accordion. Everything seems to be fine except the fact that when I click on 3rd or 4th button then other bodies stay expanded. It should work exactly the same as in the first example in Bootstrap documentation so if you click on Accordion Item #2 then Accordion Item #1 and Accordion Item #3 collapse. I am sure that the issue is with my {% if forloop.first %} but I am not sure how can I dynamically change that so it will collapse all accordion contents except active one. My code: {% for category in top_categories %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{{category.id}}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{category.id}}" aria-expanded="false" aria-controls="collapse{{category.id}}"> {{category.title}} </button> </h2> <div id="collapse{{category.id}}" class="accordion-collapse {% if forloop.first %} show {% else %} collapse {% endif %}" aria-labelledby="heading{{category.id}}" data-bs-parent="#accordionExample"> <div class="accordion-body"> {% for qa in category.qa.all|slice:"0:3" %} <a href="{{ qa.get_absolute_url }}">Q: {{qa}}</a><hr> {% endfor %} </div> </div> </div> </div> {% endfor %} -
"AttributeError: 'list' object has no attribute 'items'" While importing Json
I get the following error when i try to use the "deleted" part of my json file to change one field (ReportedStatusField) for each "Facility" in my Database that matches with the id's inside "deleted": File "C:\users\management\commands\deactivate_facilities.py", line 42, in handle for key, data in data_object.items(): AttributeError: 'list' object has no attribute 'items' It's basically a list of UUID's of Facilities that closed so i change the status this way with a json file that gets imported with a url. import requests import json from users.models import Facility from django.core.management.base import BaseCommand IMPORT_URL = 'https://domain/file.json' class Command(BaseCommand): def import_facility_from_file(self, data): key = data.get('key', None) if Facility.objects.filter(key=UUID): msg = "\n\nFacility closed: {}\n{}".format(key, str()) print(msg) facility, facility_closed = Facility.objects.update_or_create(key=UUID, defaults={ 'ReportedStatusField': 'closed' } ) def handle(self, *args, **options): headers = {'Content-Type': 'application/json'} response = requests.get( url=IMPORT_URL, headers=headers, ) response.raise_for_status() data = response.json() for key, data_object in data.items(): if key in ["deleted"]: for key, data in data_object.items(): self.import_facility_from_file(data) My JSON { "added": {"125hk24h5kjh43k5": { "UUID":"125hk24h5kjh43k5", "Name":"Test Facility 1", "AddressInfo": {"PrimaryAddress":"1234 Drive RD"}, "ImporterLastModifiedTimestamp":1643721420}}, // This is the "list" of deleted Facilities "deleted":["235hk24h5kjh43k5,235hk345789h43k5"], "modified":{"995hk24h5kjh43k5": { "UUID":"995hk24h5kjh43k5", "Name":"Test Facility 2", "AddressInfo": {"PrimaryAddress":"2345 Test RD"}, "ImporterLastModifiedTimestamp":1643721420} } } -
Django advanced model operation
I do have such operation: Contact.objects.filter(contact_code__icontains=my_string[-8:]).exists() I want to find my_string[-8:] not in the beggining, not at the end but strictly on x position in contact_code. Or I want to splite contact_code field, them do MD5 on it and only then look on it? How can I manipulate model query here? I can do it in raw sql and want to do it in model filter - not in code. -
operator does not exist: character varying[] = text[] in django?
models.py from django.contrib.postgres.fields import ArrayField class Product(DateTimeModel): colors = ArrayField(models.CharField(max_length=500),null=True, blank=True) # I am having => black,red views.py def filters(request): color_filters = request.GET.getlist('colors', default=None) # from form ['red'] products = Product.objects.filter(colors__in=l) print(products) When I am performing this I am getting this error ProgrammingError at /product/filter-query/ operator does not exist: character varying[] = text[] HINT: No operator matches the given name and argument types. You might need to add explicit type casts. How to perform this. please needed help. -
Django - modelform + model property
I am trying to solve one issue about saving data in db. This is an example how I think of it: class MyModel(models.Model): id = models.AutoField(primary_key=True) fieldX = models.SomeFieldType() @property: def foo(self): return self._foo @foo.setter def foo(self, var): self._foo=var class MyModelForm(models.Modelform): class Meta: model = models.MyModel fields = '__all__' The thing is I have dict that I am passing to this form (so I am not using view or any provided interaction with user directly. In dict I have some fields and what I want to do is one field that is passed to use it as model property but I do not want it to be saved in db. So I tried something like: form = MyModelForm(data_dict) if form.is_valid(): form.foo = data_dict['data_for_property_not_db'] form.save() Form does not know that my model has this property. So basiclly what I want is to write some parts of my data_dict normaly to form and db as always ->works fine and then I want some data_info pass to that property and use it somewhere in save() as needed without saving it to db itself. Can you help me with this? -
How to refer to class instances from the class itself
I have a class 'Scene'. From this class I can have several choices (0..n). They will be presented to the User of Scene object with a simple sentence (String). Each of the choices must point to a Scene instance (the next_scene). So I only need to associate this choice with a scene instance Id. How can I implement that in Django Models, and/or in django model.Admin. Example of a class Scene : class Scene(model.Models) title = models.CharField(max_length=30) description = models.TextField() choices = # TODO I have tried several solutions but get always blocked. I suspect I do not conceive it right from the beginning. Any help would appreciated. Stéphane -
Django restricting html section to unauthenticated users on template
my homepage has a navbar and then some content. I want to restrict the visibility of the content only to logged in/authenticated users. I tried something like this : {% if user.is_authenticated %} <div class="album py-5 bg-light"> <div class="container"> <div class="row"> {% for product in products %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="http://127.0.0.1:8000/media/{{ product.image|truncatewords:2 }}" style="max-height:400px; max-width:100%"> <div class="card-body"> <p class="card-text"> {{ product.description|truncatechars:105 }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary" style="background-color:rgb(0,128,50, 0.5)">Buy</button> <button type="button" class="btn btn-sm btn-outline-secondary"><a href="http://127.0.0.1:8000/book/{{ product.id }}" style="text-decoration:none">Read More</a></button> </div> <small class="text-muted" style="border: 1px solid black; padding:3px; border-radius:5%"><strong>{{ product.price}}€</strong></small> </div> </div> </div> </div> {% endfor %} {% else %} <h1>Just login, bro</h1> {% endif %} this is my view that renders the page : def all_products(request): products = Product.objects.all() return render(request, 'store/home.html', {'products' : products, 'user': request.user}) So, what should I do in order to show that piece of HTML only if the user is authenticated or logged in ? I have already seen someone do something like this but can't find it, am I missing something? -
AWS RDS and PGAdmin
I am working on a personal Django project and plan on using a PGSQL DB on AWS RDS. Tutorials I see always show the process of linking RDS dbs to PGAdmin and I am wondering if this step really is necessary/vital. Would there be consequences (apart from not having access to all the benefits of PGAdmin of course) if I skipped it? -
Django user.is_authenticated is not for some subpage
In my index.html(base template) have nav bar and user is_authenticated is not working for profile subpage it is working for home Index.html <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> ... {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link mx-1" href="/account/profile/">{{user.username}}</a> </li> <li class="nav-item btn-danger "> <a class="nav-link text-white " href="/account/logout/">Logout</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="/account/login/">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="/account/register/">Register</a> </li> {% endif %} ... </nav> Profile.html {% extends 'index.html' %} {% block body %} {% for user_info in user%} <div> ... </div> {% endfor %} {% endblock body %} What i am trying here is when i login it remove login and registration button and instead whatever the user name and logout button is appear it is working on home but whenever i got profile page i see login and registration even though i am curretly logged in . Thanks and any advice would be much appreciated. -
How to send all django error as json data
I am building a rest api in django, I am using postman to test my apis, Everything is great though I want if any error occurs in my django app so django send me a json error rather than a html page. Is there a way to do that. -
how can i use django form validation
I am trying to use Django form and validation is not working. django version 3.2 I tried different methods and still, none of them worked for me. from django import forms from django.core import validators from django.core.exceptions import ValidationError #Custom_Validator def check_size(value): if len(value) < 6: raise forms.ValidationError("value is short") class UserForm(forms.Form): firstName = forms.CharField() LastName = forms.CharField(validators = [check_size, ]) password = forms.CharField(widget = forms.PasswordInput, validators = [check_size, ]) def clean_firstName(self): inputfirstName = self.cleaned_data['firstName'] if len(inputfirstName)>5: raise ValidationError("reached max length") return inputfirstName -
Can we use NextJs to develop ML model App?
I have an App (Shiny) that deploys a Machine Learning model and I want to use something better than R-Shiny. I Got two suggestions Django+React and NexJS. Can you advise me which is better and if there is a free App that is developed with these technologies so I can have a look and test it by myself? Thanks. -
While using bulk_create() -> error = "detail": "JSON parse error - Expecting ',' delimiter: line 1 column
In this file, I am trying to post user information, either one or many using bulk_create() views.py @api_view(['POST']) def post_user(request): print("INSIDE") print(request.data) if len(request.data) == 1: user_data = UserInfoSerializer(data=request.data) if user_data.is_valid(): user_data.save() return Response(user_data.data) else: UserData.objects.bulk_create(request.data, batch_size=1000) The request which I send is [{"name":"George","gpa":2}, {"name":"Dev","gpa":4}, {"name":"Bianca","gpa":3.2}] When I send a request with one dictionary, data gets uploaded. But not with multiple -
Django 401 (Unauthorized) On making PUT request with axios. But working with Postman
I'm trying to update the User in Django from react side. The same function has worked on testing through Postman. But when I try to make a request using Axios in react.js Django doesn't accept it. and throw 401 error. [21/Feb/2022 16:25:16] "PUT /api/v1/accounts/profile/update/ HTTP/1.1" 401 58 On the postman, I'm using Bearer Token for authorization. And the same token I'm passing in headers config. // Related Action Code const userData = JSON.parse(localStorage.getItem('userData')) const config = { headers: { 'Content-type': 'application/json', Authorization: `Bearer ${userData.token}` } const { data } = await axios.put( `/api/v1/accounts/profile/update/`, config ) Can anybody find out why this happening? And how to fix that problem. -
My website form submission is responding with Server Error 500. How to fix it?
I have a django blogging website hosted on digital ocean apache server, but when an authenticated user is creating a blog and then submitting it, the server is responding with this error - "Server error 500". Rather it should show that 'your blog is submitted successfully' and should redirect to a different page. When I referred the /var/log/apache2/error.log file, I found this text written inside it: [Mon Feb 21 06:25:06.622898 2022] [mpm_event:notice] [pid 1379:tid 139646411897792] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Mon Feb 21 06:25:06.622981 2022] [core:notice] [pid 1379:tid 139646411897792] AH00094: Command line: '/usr/sbin/apache2' [Mon Feb 21 09:59:50.545910 2022] [core:error] [pid 1670:tid 139646038083328] [client 45.146.165.37:57224] AH00126: Invalid URI in request POST /cgi-bin/.%2e/.%2e/.%2e/.%2e/bin/sh HTTP/1.1 How can I fix this error? -
Sum of Duration Fields in Django
I am having a small issue in summing up two simple duration fields. I have two variables which contains two different duration fields. Basically, I just need to sum them in order to get the total time. The problem is that, the way the database is built, I can't use Sum or F or ExpressionWrapper because I have to accept also None values and, the calculation gives me a None value in return. I post some code: views. py duration_dual = Mission.objects.filter( training_course_id=1, solo_flight=False) total_dual_duration = duration_dual.aggregate(eet=Sum(ExpressionWrapper( F('duration_dual'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_dual_duration != None: total_dual_duration = duration(total_dual_duration) duration_solo = Mission.objects.filter( training_course_id=1, solo_flight=True) total_solo_duration = duration_solo.aggregate(eet=Sum(ExpressionWrapper( F('duration_solo'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_solo_duration != None: total_solo_duration = duration(total_solo_duration) models.py class Mission(models.Model): name = models.CharField(max_length=200) duration_dual = models.DurationField(blank=True, null=True) duration_solo = models.DurationField(blank=True, null=True) training_course = models.ForeignKey( TrainingCourse, on_delete=models.CASCADE) note = models.TextField(null=True, blank=True) solo_flight = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In fact, what I need to do is just adding the total_solo_duration and total_dual_duration variables. I tried with datetime or timedelta but I can't figure out the proper way to do so. Thank you very much in advance -
What to do when pip dependency resolver wants to use conflicting django plotly dash versions of a application?
So I'm trying to integrate plotly with my django app however I'm having an issue rendering a chart. I was using VSCode which did not pick up the dependency conflict. However when i started to use Pycharm. It said my Dash was version 1.11 which satisfies the django-plotly-dash but did not satisfy the dash_bootstrap_components which required 2.0.0 I have now installed Dash version 1.10 which conflicts with both apps just to show the error message below: Relevant error code ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following de pendency conflicts. django-plotly-dash 1.6.6 requires dash<1.21.0,>=1.11, but you have dash 1.10.0 which is incompatible. dash-bootstrap-components 1.0.3 requires dash>=2.0.0, but you have dash 1.10.0 which is incompatible. Any help is appreciated -
Django how to create object has foreignkey in views.py?
I've wrote this code: views.py if not null: Address.objects.create(user = request.user,first_name = ad,last_name = soyad,address_title = baslik,address = adres,postalcode = posta,tel = gsm,il_ilce = Ilce.objects.get(il_id__il = sehir,ilce = ilce)) models.py class Il(models.Model): il = models.CharField(max_length=20,blank=False,null=False) def __str__(self): return str(self.il) class Ilce(models.Model): ilce = models.CharField(max_length=20,blank=False,null=False) il_id = models.ForeignKey(Il,blank=False,null=False,on_delete=models.PROTECT) def __str__(self): return str(self.ilce) class Address(models.Model): first_name = models.CharField(max_length=30,blank=False,null=False) last_name = models.CharField(max_length=30,blank=False,null=False) user = models.OneToOneField(User,on_delete=models.CASCADE) address_title = models.CharField(max_length=20,blank=False,null=False,default="Adres") address = models.TextField(max_length=255,blank=False,null=False) il_ilce = models.ForeignKey(Ilce,blank=False,null=False,on_delete=models.PROTECT) postalcode = models.CharField(max_length=5,blank=False,null=False) tel = models.CharField(max_length=11,blank=False,null=False) def __str__(self): return str(self.user) + '-' + str(self.address_title) but I'm getting this error: duplicate key value violates unique constraint "Users_address_user_id_key" DETAIL: Key (user_id)=(1) already exists. I don't want the code to create a new user object I want it to create a new address object only. -
'NoneType' object is not subscriptable df.apply(lambda row: (row)[0], axis=1)
I linking two table from variety_id to variety_name but my code is giving an error when the variety_id is null 'NoneType' object is not subscriptable the code where I am linking table if not df.empty: df['commodity_name'] = df.apply(lambda row: commodity_name(row)[0], axis=1) df['state_name'] = df.apply(lambda row: state_name(row)[0], axis=1) df['variety_name'] = df.apply(lambda row: variety_name(row)[0], axis=1) def commodity_name(self): if self.commodity_id: return get_commodity_name(self.commodity_id) return None def state_name(self): if self.state_id: return get_region_name(self.state_id) return None def variety_name(self): if self.variety_id: return get_variety_name(self.variety_id) return None also written query for mapping the columns def get_variety_name(variety_id): """ This function is used to return state_name by querying the database based on lgd_state_id """ query = "SELECT commodity_variety_name FROM itrade.commodity_variety_master WHERE commodity_variety_id={}".format( variety_id) query_result = get_column_value(query) if not query_result.empty: return list(get_column_value(query)['commodity_variety_name']) return None def get_commodity_name(commodity_id=None): """ This function is used to return commodity_name by querying the database based on commodity_id """ query = "SELECT commodity_id, commodity_name FROM itrade.commodity_master" if commodity_id: query += " WHERE commodity_id={}".format(commodity_id) return list(get_column_value(query)['commodity_name']) return get_column_value(query).to_dict(orient='records') -
Django function params
Where there are a series of parameters passed to a Django function they may have defaults. If a param is supplied when the function is called it is used. If not the default is used. Is there a way to access the first default while supplying subsequent param[s] in the function call? Example: def pong(fname = 'Pinkus', lname = 'Poke'): print(f'My name is {fname} {lname}') pong() # My name is Pinkus Poke pong('Frank') # My name is Frank Poke pong('Frank', 'Finklestein') # My name is Frank Finklestein pong('', 'Bloggs') # only gives empty string, no default!