Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django sites and showing id in admin editor
I'm using the Site module in django. In the admin interface, I see domain name and display name. I'd really like to see the primary key id, as well, however, since I specify the sites by SITE_ID. Now I could do this by editing ./venv/lib/python3.7/site-packages/django/contrib/sites/admin.py, but that's poor form in so many ways. I'd just add "id", thus: class SiteAdmin(admin.ModelAdmin): list_display = ('id', 'domain', 'name') search_fields = ('id', 'domain', 'name') I did the following in one of my models.py files, which helps in the shell but doesn't show up in admin: def site_name(self): return '{domain} ({id})'.format( domain=self.domain, id=self.id) Site.__str__ = site_name Any suggestion how to do this (or pointer on what I'm doing wrong that I think I want it)? -
Inject variables into Model Form CharField
Pretty quick question - Is it possible to inject variables into CharFields "initial" fields in Model forms on Django? I would like to pass the current year and some link the customer fills out in a previous form field (link) and have it populate the "message." subject = forms.CharField( widget=forms.TextInput(attrs={'placeholder': ('Subject')}), initial="Subject", required=False) link = forms.CharField() message = forms.CharField(widget=forms.Textarea, initial="Dear User, today is **datetime.now()** and here is **link**", required=False) -
How to run a python code on django containing script for opening webcam on browser
I want to run a python script on django. My python code is on hand detection, and I am not able to open webcam on web browser and take inputs from it. -
Django rest framework incorrect nested serialization
I started a new django rest framework project and bumped into an annoying problem. The nested serialization doesn't work as expected. Instead of serializing relationship models and returning serialized object it returns an extra "relationship" field in addition to defaul "attributes" json field. Here is my python 3.6 code: models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='User', null=True, blank=True) first_name = models.CharField('First name', max_length=50) last_name = models.CharField('Last name', max_length=50) phone_number = models.CharField('Phone number', max_length=15) activated = models.DateTimeField('Activated') def __str__(self): return f'<Profile {self.first_name.title()} {self.last_name.title()}>' serializers.py from rest_framework import serializers from .models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('id', 'first_name', 'last_name', 'phone_number') class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('id', 'email', 'username', 'profile') views.py from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import UserSerializer from .models import Profile class UserViews(APIView): def get(self, request, format=None): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) The answer I expect to get: { "data": [ { "type": "UserViews", "id": "1", "attributes": { "email": "", "username": "admin", "profile": { "id": 1, "first_name": "name1", "last_name": "name2", "phone_number": "+79999999999", } … -
post request and url not working on google app engine django project
I am hosting my blogging app on google app engine in a standard environment. the website deploys successfully. but when I try to go to any other URL like anirudhmalik.in to anirudhmalik/blog/list/ it shows me 500 server error on the server side I am using PostgreSQL instance and the logs message only show me the error projects/anirudhmalik-274008/logs/appengine.googleapis.com%2Frequest_log" but I couldn't get any hint from this message and none of the post requests isworking on the website and everything is working fine in a local server or my local machine you can check the website on anirudhmalik.in and you can also give suggestion is google app engine is good to host your Django project and other cheap college student type hosting service thankyou main.py from annyportfolio.wsgi import application app=application app.yaml file handlers:# This configures Google App Engine to serve the files in the app's static# directory.- - url: /static static_dir: static-storage/ # This handler routes all requests not caught above to your main app. It is# required when static routes are defined, but can be omitted (along with# the entire handlers section) when there are no static files defined. - url: /.* secure: always redirect_http_response_code: 301 script: auto env_variables: DJANGO_SETTINGS_MODULE: annyportfolio.settings … -
How to update templates automatically in Django?
Consider I am having a basic model like this: class Text(models.Model): msg = models.TextField() I'm rendering a template like: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <h1>Messages<h2><br> {% for message in messages %} <a> {{forloop.counter}} - {{message}} <br> {% endfor %} </body> </html> With a corresponding views: from django.shortcuts import render from .models import Text def home(request): context = { "messages": Text.objects.all(), } return render(request, 'app/home.html', context) Assuming i am creating new objects of Text through admin page. If I save an object, I want to render it without refreshing the page. I don't have good knowledge on Javascript/jQuery/AJAX, but I'm aware that it is possible to acheive with the help of this. Can anyone guide me through on how to render the contents without refreshing the page? -
DRF how to filter user and product by Foreign key company?
How can I filter by Foreign key(company) to get Only those product which got same company and authorized user? I have these models: models: class User(AbstractBaseUser): first_name = models.CharField(max_length=254) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=255) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) serializer class ProductSerializers(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' view class ProductViewSet(ModelViewSet): serializer_class = ProductSerializers queryset = Product.objects.all() permission_classes = [IsAuthenticated] -
How can I create a search box with drop down filter in Django or python
I just used Django Python about 1 month ago. Can anyone guide me just where can I learn this, Thank you -
Storing a image in Django file-system (without using a database)
index.html <form method="POST" action="."> {% csrf_token %} {{ image_form.as_p }} <input type="submit" name="submit" value="Search via URL"> </form> forms.py class UploadImageForm(forms.Form): image_field = forms.ImageField(required=False) views.py if request.method == 'POST': if request.POST.get('submit') == 'Search via Image': print(request.POST) print(request.FILES) So I want to take the image uploaded by the user and save it in my storage, perform a few operations on it, display it on the webpage and delete it. But I am not being able to go this. In request.POST I'm getting a dict containing the file name, but that's plain text. And while using request.FILES I'm getting, <MultiValueDict: {}> How should I go about this? Thanks, in advance. -
unable to import models: for comment
i'm trying to import comment models but i'm getting error while migrate my code from django.db import models from django.utils import timezone from django.contrib.auth.models import User from PIL import Image from django.urls import reverse class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=300) image = models.ImageField(default='default.jpg',upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) class Comments(models.Model): Post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') user_id = models.ForeignKey(User,on_delete=models.CASCADE,default=True) comment = models.TextField() commented = models.DateTimeField(default=timezone.now) the error is :- django.db.utils.IntegrityError: The row in table 'userpost_comment' with primary key '1' has an invalid foreign key: userpost_comment.author_id contains a value 'sd' that does not have a co rresponding value in auth_user.id. -
How can we export dict containg list as value in csv file
Suppose this is input format... {'ID':[1,2,3,4,5,6,7,8,9,10], 'Name':['A','B','C','D','E','F','G'], Flag:['True'], City:'', } and i want to export this data as follow in csv file in python ID Name Flag City 1 A True '' 2 B '' 3 c 4 D 5 E and so on...How can we do it ..? Thankx in advance PF:Im getting input formate from django models -
How to implement Django Session Wizard with multiple templates
Im trying to implement a multi step form in django using the form wizard that comes with django-formtools and so far it steps through all the forms till the last one then instead of calling the done method, the page goes back to the first form. Some of my code is shown below: Urls.py from django.urls import path from minereg import views urlpatterns = [ path('',views.ContactWizard.as_view(views.FORMS),name="registration"), ] Views.py from django.shortcuts import render from formtools.wizard.views import SessionWizardView from .forms import RegForm1,RegForm2 FORMS = [("home",RegForm1),("bank",RegForm2)] TEMPLATES = {"home":"home.html", "bank":"bank.html"} class ContactWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self,form_list, **kwargs): #Required form_data = [form.cleaned_data for form in form_list] print(form_data) return render(self.request,template_name = "thanks.html") The print(form_data) in the done method doesn't happen, showing the code never gets to that point. home.html {% extends "base.html" %} {% load widget_tweaks %} {% load i18n %} {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="{%url 'registration' %}" method='post'> {% csrf_token %} {{wizard.management_form}} <div class="container col-md-9"> <h1>PERSONAL DETAILS</h1> <p>Please fill in this form to create an account.</p> <hr> <!-- Name --> <div class="row"> <div class="form-group col-md-4"> {{ wizard.form.name.label_tag }} {{ wizard.form.name|add_class:"form-control form-control-lg" }} </div> <div class="form-group col-md-4"> {{ wizard.form.middle_name.label_tag }} {{ wizard.form.middle_name|add_class:"form-control form-control-lg" }} … -
Visual studio code doesn't read db.sqlite3 in django framework
I saw a tutorial of django on youtube. That tutorial explain that I must open and write the db.sqlite3 file. Unfortunately Visual Studio Code doesn't read that file. Can anyone help me? -
How Do I Create A Socail Media App With Python?
Hello Guys I Wanted To Create An Social Media App Which Does Not Mine With User's Data. I Want To Build The App Purely With Python. I Know Kivy, Postgreql, Sockets And Finally Python. Is There Anything Else I Need To Learn To Create An Social Media App? Thanks In Advance. -
MultipleObjectsReturned at /checkout/ get() returned more than one Order -- it returned 2
Hi I'm trying to develop an e-commerce website using Django. I have two models and views on separate folders, one is an order model and view, another is the checkout model and view. The order view creates a new order everytime an item is added to the cart. And the checkout view creates a new billing address. I want to associate the billing address that is created to the order when the checkout form is submitted. But for some reason, it's not happening. It throws an error: MultipleObjectsReturned at /checkout/ get() returned more than one Order -- it returned 2! What is the problem? My orders.models.py: from django.db import models from shopping_cart.models import Cart from django.contrib.auth import get_user_model from accounts2.models import BillingAddress STATUS_CHOICES = ( ("Started", "Started"), ("Abandoned", "Abandoned"), ("Finished", "Finished"), ) User = get_user_model() class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) order_id = models.CharField(max_length=120, default='ABC', unique=True) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=120, choices=STATUS_CHOICES, default="Started") sub_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) tax_total = models.DecimalField(default=0.00, max_digits=1000, decimal_places=2) final_total = models.DecimalField(default=10.99, max_digits=1000, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) billing_address = models.ForeignKey(BillingAddress, on_delete=models.SET_NULL, blank= True, null=True) My orders.views.py: @login_required def order(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return … -
Best approach to multiple user types in django
I have the need for multiple user types in my application, each with different type specific information, and potentially different FK associations to other entities. In my research on the topic I've seen the recommended approach in the documentation is to create a OneToOne related user profile model to the user here. I've also seen this approach suggested in this example and this question. Let's say for the sake of an example: class User(AbstractUser): pass class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_number = models.CharField() class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) department = models.ForeignKey(Department) class Course(models.Model): convenor = models.ForeignKey(Teacher) students = models.ManyToManyField(Student) Contrary to the above examples, I've found only one example recommending the use of subclassing of the User model, here. For the above context this would instead be class User(AbstractUser): pass class Student(User): student_number = models.CharField() class Teacher(User): department = models.ForeignKey(Department) This seems to me to be the much more intuitive and less verbose implementation of the same thing. Is a subclass of a model not just a OneToOne association to the parent model? However in the above stack overflow selected answer this approach is specifically advised against, saying it will lead to problems later. How? I … -
Is it a problem to have two or more exactly same class name at different files?
For my django application, I created class based views and each of them is defined at different file: # foo.py from django.views import View ... class MyView(View): def get(...): foo() # bar.py from django.views import View ... class MyView(View): def get(...): bar() Actually, it is not necessary to have same class names because the views (the web pages) does not have the same content. They have different content created by foo() and bar(). What I want to ask is that is having the same class names at different files is contrary to Object-Oriented Programming (OOP) concepts? Any explanation is appreciated. -
.core problem. just want to do simple login app?
using VSCode i am trying to create a basic signin login app. I change to my Python 3.9 env the "no module named" **.core problem seems to be solved but its really because "couldn't import django" problem. I tried my python 3.7 venv but then "couldn't import django". -
Cloud ndb middleware for django Notimplemented error. How can I solve it?
I using django==2.2 and python==3.7. I install latest google-cloud-ndb library using pip. I added the middleware 'google.cloud.ndb.django_middleware.NdbDjangoMiddleware' in the middleware list inside settings.py file. When I try to run runserver command it gives me following error File "S:\Python\Python37\lib\site-packages\google\cloud\ndb\django_middleware.py", line 23, in __init__ raise NotImplementedError NotImplementedError -
Find current static tag in Django
I'm trying to get current active hash for my static files and I'm using CachedStaticFilesStorage <script type="text/javascript" src="https://example.com/static/js/main.787c27db2d80.js"></script> In the template invocation is like below {% javascript 'jquery' %} {% render_bundle 'main' 'js' %} How do I find programmatically (or somewhere in the database/cache) current hash 787c27db2d80 that is used and at which point this value is going to be regenerated. Django 1.11 + django-webpack-loader + django-pipeline -
django , react , redux authentication token is null
im new to react and redux , i have been trying to utilize django as my backend , react as my frontend and redux as my local storage to store authentication states. However i have encountered an error and im not too sure how to debug this. There is no error messages , just that i am unable to pass the token into my components. index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { createStore, compose, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import reducer from './store/reducers/auth'; const composeEnhances = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore(reducer, composeEnhances( applyMiddleware(thunk) )); const app = ( <Provider store={store}> <App /> </Provider> ) ReactDOM.render(app, document.getElementById('root')); registerServiceWorker(); App.js import React, { Component } from 'react'; import { BrowserRouter as Router } from 'react-router-dom'; import { connect } from 'react-redux'; import BaseRouter from './routes'; import 'antd/dist/antd.css'; import * as actions from './store/actions/auth'; import CustomLayout from './containers/Layout'; class App extends Component { componentDidMount() { this.props.onTryAutoSignup(); } render() { return ( <div> <Router> <CustomLayout {...this.props}> <BaseRouter /> </CustomLayout> </Router> </div> ); } } const mapStateToProps = state => { return … -
Do I really need to use {% load static %} in Django Templates?
I am using Django 3, the latest version. I have defined the static files directories properly as required. Currently to display an image, both the following source codes work fine. Code 1: <img src="static/img/logo.png"></img> Code 2: {% load static %} <img src="{% static 'img/logo.png' %}"> </img> Since both the code snippets are working and running fine without any problems, I am wondering why not to simply use the way of Code 1 above and refrain from the extra lines of Code 2. Which one would be beneficial and why? Please guide. -
django.urls.exceptions.NoReverseMatch on second level context
I believe my situation is different to other questions and I've tried multiple other answers to no avail. I have a config with a uuid pk. On my list of configs, one can add, edit, delete a config, if you click a config name, it doesn't take you into a detail of the config itself but rather a view of data in other models that references the config as a foreign key (i.e. data "in" that configuration). Within that configuration, one can CRUD each model. I have just started adding the "Add" buttons but get a NoReverseMatch exception. I think this is something to do with my URLs but can't work it out. I know I need to somehow pass the pk from the config to the next view. In addition, when creating an entry for each model, the pk from the config needs to automatically save as a foreign key of the new item (in the background). URLS.PY # My configuration list, and CRUD (this works) path('configurations/', ConfigurationsListView.as_view(), name='configurations'), path('configurations/create/', views.ConfigurationCreate.as_view(), name='configuration_create'), path('configurations/<uuid:pk>/update/', views.ConfigurationUpdate.as_view(), name='configuration_update'), path('configurations/<uuid:pk>/delete/', views.ConfigurationDelete.as_view(), name='configuration_delete'), # My configuration detail view (actually a view of data with the config as a foreign key) path('configurations/configuration/<config_id>', views.ConfigurationDetailView.as_view(), name='configuration_detail'), # … -
How to run a cronjob in a Django app running on nginx uwsgi
I have a django app running on a webserber with nginx and uwsgi. On my local server the crons are working. i add it with python3 manage.py crontab add command. I guess it doesnt work this way on the weberserver as it's not working when i try. I can't find / figure out how to configure it properly. Maybe someone can enlight me ? Thanks -
Django: not able to run application using uwsgi
I ma trying to run django application using uwsgi but it throws continuously one error : not able to import site module the issue is was previously running it under python2.7 env but then i switched to virtual env with python3.6 and after that i am not able to run this project under python3.6 env it always runs in 2.7 I have tried all the tutorials but i'm not able to get the result this is my uwsgi.ini file : [uwsgi] # telling user to execute file # telling group to execute file #gid = webapps # name of project you during "django-admin startproject <name>" project_name = xyz_dev # building base path to where project directory is present [In my case this dir is also where my virtual env is] base_dir = /home/ubuntu/croydoner/%(project_name) # set PYTHONHOME/virtualenv or setting where my virtual enviroment is # WSGIPythonPath = /usr/local/lib/python2.7/dist-packages/ virtualenv = /home/ubuntu/croydoner/venv/ # plugins-dir = /usr/local/uwsgi-2.0.18/plugins/python # plugins = python3.6 # unprivileged-binary-patch = /home/ubuntu/croydoner/venv/bin/uwsgi # changig current directory to project directory where manage.py is present chdir = %(base_dir) # loading wsgi module wsgi-file = %(base_dir)/demo/wsgi.py http = :8090 # enabling master process with n numer of child process master = true processes …