Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing env environ (overwriting it after initialization)
I have am using environ package. I want to have my default (production) settings in settings.py file. But I want to change a couple of settings depending on the DEBUG=1 setting in my .envfile. Something like this: env = environ.Env( DEBUG=(bool, False), SECRET_KEY=(str, ''), DATABASE_URL=(str, 'postgres://testing:testing@localhost/testing'), ) if os.path.exists(env_file): env.read_env(env_file) DEBUG = env.bool('DEBUG') SECRET_KEY = env.str('SECRET_KEY') if DEBUG and not SECRET_KEY: SECRET_KEY = 'xxx' # Default '@localhost' is needed for the production server. But that will probably fail # on development machine. Write "DEBUG=1" to ".env" file to enable. if DEBUG: DATABASE_URL = 'postgres://testing:testing@testing_postgres/testing' DATABASES = {'default': env.db()} Reading the file and getting the DEBUG setting works, but I can't find a way to overwrite the DATABASE_URL variable previously set by environ.Env. Is there a way to overwrite the previously set value (partially overwrite env)? -
Why does my home link stay active with Django-Active-Link?
I am using Django-Active-Link to have active links in my navbar. However, my Home url is always active even when I go to other links in the Navbar. This works with other links, but the home is active while the others are also active. <a class="nav-link {% active_link 'home' %}" href="{% url 'home' %}">Home</a> I want the code to only display active links, but the home is always active no matter what. -
When using 'SearchFilter' I get an error when trying to search
When I use the search function in my api I get an error that says "Cannot resolve keyword 'q/c' into field. Choices are: 'XXX'" The q or c depends on which api page I am on. The 'c' I presume stands for my choices one and the 'q' I presume stands for the Questions one. from rest_framework import generics from . serializers import QuestionSerializer, ChoiceSerializer from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter, SearchFilter from polls.models import Choice, Question # need to create a view for each serializer class QuestionList(generics.ListAPIView): serializer_class = QuestionSerializer # set the serializer queryset = Question.objects.all() # set the query set to all the objects of that view filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) # allows for filters filter_fields = {'id': ['gte', 'lte', 'exact'], 'pub_date': ['gte', 'lte']} ordering_fields = ('id', 'question_text', 'pub_date') search_fields = 'question_text' class ChoiceList(generics.ListAPIView): serializer_class = ChoiceSerializer queryset = Choice.objects.all() filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter) # trying to do greater than or less than filter fields stuff filter_fields = {'id': ['gte', 'lte', 'exact'], 'votes': ['gte', 'lte', 'exact']} ordering_fields = ('id', 'votes', 'choice_text', 'question',) search_fields = 'choice_text' -
ImportError: No module named 'first_app' after adding to INSTALLED_APPS
I have created new app python first_project/manage.py startapp first_app, and after this added app to INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app'] And after python first_project/manage.py runserver get error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fe13745f6a8> ... ImportError: No module named 'first_app' Why I can not add app? -
Chrome headless crash in Ubuntu 18.04
We upgraded our scraping workers machines from Ubuntu 16.04 to 18.04. after reaching ~250 instances in a machine we are getting: WebDriverException: Message: unknown error: Chrome failed to start: crashed (unknown error: DevToolsActivePort file doesn't exist) (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) (Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 4.15.0-1040-aws x86_64) The new & old machines are running the same chrome / chromedriver versions: ChromeDriver 2.46.628388 and Google Chrome 75.0.3770.90 We tried adding these options as suggested here but to no avail: options.addArguments("--no-sandbox"); options.addArguments("--disable-dev-shm-usage"); -
Django save file on localhost
I'm working on a Django app (DRF), but I'm a JS engineer so this is all new to me. I have this in my models.py, outside of any actual models: storage = S3Storage(aws_s3_bucket_name=settings.DOCUMENTS_BUCKET) upload_location = 'recordings/' and this is a field it is used in, inside one of the models: zip_file = models.FileField( upload_to=upload_location, storage=storage, null=True) This works OK in production. However, I want to be able to test it locally, add those zip files when developing locally. So I've added this for storage and upload_location: if settings.DEBUG: storage = FileSystemStorage(location='/') upload_location = '' Then, when I try saving a file from admin on localhost, I get the following error: [Errno 13] Permission denied: '/my-file.zip' If I got it right, the app cannot just create that location somewhere on my file system. Maybe I'm wrong. How can I solve this? -
add data to M2M through models
I'm trying to make records for my database of a web-based course planning application in an institution. My concern is that of not being able to make recordings in the intermediary table resulting from the relation M2M in views.py but it works in shell in browser I have an ValueError :The QuerySet value for an exact lookup must be limited to one result using slicing. models.py class Departement(models.Model): code_departement=models.CharField("code du département", max_length=100, unique=True) libelle_departement=models.CharField("Libellé du département", max_length=100) faculte=models.ForeignKey("Faculte", on_delete=models.CASCADE) cursus=models.ManyToManyField("Cursus", through="AvoirCursus") class Cursus(models.Model): code_cursus=models.CharField("Code du cursus", max_length=10, unique=True) libelle_cursus=models.CharField("Libellé du cursus", max_length=100) class AvoirCursus(models.Model): cursus=models.ForeignKey("Cursus", on_delete=models.CASCADE) departement=models.ForeignKey("Departement", on_delete=models.CASCADE) views.py if request.method == 'POST': f = forms.Departement_Form(request.POST) if f.is_valid(): dept = f.save(commit=False) code_departement = f.cleaned_data['code_departement'].upper() dept.code_departement = code_departement cursus = f.cleaned_data['cursus'] dept.save() cursus = get_object_or_404(Cursus, libelle_cursus=cursus ) AvoirCursus(departement=dept, cursus=cursus) return redirect('configuration:lister_departement') -
How to build Rest Api for custom model with one to one relationship with django user model
I want to build a rest api endpoint for create operation on a model which has a one to one relationship with a Users model which inherits from abstractuser. This is the Users model class Users(AbstractUser): is_user = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) This is my Admin model class Admin(models.Model): user = models.OneToOneField(Users, on_delete=models.CASCADE, primary_key=True, related_name='admin') organization = models.CharField(max_length=255, blank=True) def __str__(self): return self.organization This is my serializer class UsersSerializers(serializers.ModelSerializer): class Meta: model = Users fields = ('id', 'username', 'password') write_only_fields = ('password',) This is my create api view class UserCreateView(generics.ListCreateAPIView): """ This class defines the create behavior of our rest api. get: Return a list of all the existing users. post: Create a new user instance. """ queryset = Users.objects.all() serializer_class = UsersSerializers def perform_create(self, serializer): """Save the post data when creating a new Book.""" # serializer.save() instance = serializer.save() instance.set_password(instance.password) instance.save() I want to also be able to serialize an instance of admin model and its field together with the Users model, I do not know how to go about this, but I want to be able to display Admin model fields alongside Users model field and save Admin model data alongside Users model. -
Passwordless Authentication Django Rest Framework (OTP Login)
I am trying to find a Passwordless Authentication with Django Rest Framework, I am using drfpasswordless but I am not able to get the one-time password or token. -
Configuring Django and Webpack Dev Server
I'm setting up Django with Webpack Dev Server and having a hard time getting everything to work together. I've managed to get the Djano app to serve the static js produced by webpack dev server, but there's no live reload, and I'm getting a weird sockjs 404 error as well... In my settings.py I have this: STATIC_ROOT = os.path.join(PUBLIC_DIR, 'static') STATIC_URL = 'http://127.0.0.1:8080/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'dist'), # We do this so that django's collectstatic copies or our bundles to the STATIC_ROOT or syncs them to whatever storage we use. ) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': '', # must end with slash 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, 'IGNORE': ['.+\.hot-update.js', '.+\.map'] } } and my webpack config looks like this: var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './djangowebpack/static/js/index.js', plugins: [ new BundleTracker({filename: './webpack-stats.json'}) ] } I haven't specified an output path so it just generates a dist folder at the root. I'm using the webpack-loader to pass it to my templates like this: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> … -
Django,model inheritance: How to cast parent class object to child object
Context I have following models: # carts/models.py class Cart(models.Model): # Used to determine card type when inheriting. See example. content_type = models.ForeignKey(ContentType) class SingleProductCart(Cart): """Regular cart with single product.""" @property def product(self): pass # orders/models.py class Order(models.Model): # Has to work with any Cart subclass. cart = models.ForeignKey(to='carts.Cart') And so, i've run into following code: def do_something_with_single_product_order(order): # We assume there that order.cart is a SingleProductCart instance. assert order.content_type.model_class() == SingleProductCart # True do_something_with_product(order.cart.product) # Attribute error. Which raises exception because order.cart attribute refers to Cart model instance instead of SingleProductCart, and does not have attribute product. Question How do i cast a Cart model instances to a SingleProductCart without extra db queries or how to organize my models to make them return object of correct class? -
How to Combine Date and Time Fields into DateTime Field in Django F Expression
I have to get the difference of two datetime fields but one is pure datetime field and other is a combination of date and time. I tried this one: qs = Foo.objects.filter( bar__baz_id=self.kwargs['baz_pk'], ) start_datetime = ExpressionWrapper((F('x__date') + F('x__start')), output_field=DateTimeField()) qs = qs.annotate(start_datetime=start_datetime) before_start_wrapper = ExpressionWrapper( F('start') - F('start_datetime'), # 'start' is datetime field on Foo, start_datetime is annotated field on Foo output_field=DateTimeField() ) before_start = Extract(before_start_wrapper, 'epoch') qs = qs.annotate(before_start=before_start/3600) This also doesn't work; qs = Foo.objects.filter( bar__baz_id=self.kwargs['baz_pk'], ) start_datetime = F('x__date') + F('x__start') before_start_wrapper = ExpressionWrapper( F('start') - F(start_datetime), # 'start' is datetime field on Foo, start_datetime is combined F expression output_field=DateTimeField() ) before_start = Extract(before_start_wrapper, 'epoch') qs = qs.annotate(before_start=before_start/3600) What django does is as follows: ...(EXTRACT('epoch' FROM "foo".came" - ("db_shift"."date" + "db_shift"."start")) AT TIME ZONE) /3600 AS ... What I am expecting is: ...(EXTRACT('epoch' FROM "foo".came" - ("db_shift"."date" + "db_shift"."start")AT TIME ZONE)) / 3600 AS ... Can some one please provide the solution with Django ORM? I know I can run a raw query but wanted to look if there is a way to do the same with Django ORM? Thanks. -
HTML and CSS contents not loading
I was working on this thing, everything was loading. I started working on login and register. I finished it and when I load the site, this happened: The nav bar scroll does not work. The pages that needed to open: gallery, contact and all, are not there. Its blank. No any HTML or CSS except background gradient. home page -
Cannot update a record from database, but am able to fetch it?
I have this simple function to update an existing record, by fetching it by the primary key in a form, and then update it in the database in Django 2.0.1. I am able to fetch the data just fine from the database, but when I press Submit to POST request is sent to ([17/Jun/2019 17:59:28] "POST /suppliers/lr/13/ HTTP/1.1" 200 25533), but no change is reflected in the database. This is my code: Views.py @login_required @supplier_required def LrFormView (request, pk): lr_object = get_object_or_404(LR, id=pk) # Or slug=slug form = LrForm(data=request.POST or None, instance=lr_object) if form.is_valid(): form.save() # redirect() return render(request, 'classroom/suppliers/print_LR.html', {'form': form}) Forms.py class LrForm(forms.ModelForm): class Meta: model = LR fields = ('lr_declared', 'ewaybill_no', 'lr_quantity', 'lr_weight', 'lr_invoice_date', 'lr_item_name', 'lr_consignor_name', 'lr_consignor_address', 'lr_consignor_contact_name', 'lr_consignor_contact_phone', 'lr_consignee_name', 'lr_consignee_address', 'lr_consignee_contact_name', 'lr_consignee_contact_phone', 'vehicle_no', 'lr_vehicle_type', 'driver_name', 'driver_no', 'lr_no', 'lr_date', 'lr_billingparty', 'invoice_no') models.py: class LR(models.Model): lr_quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='quiz_lr') lr_no = models.IntegerField(default=0) lr_date = models.DateTimeField(max_length=255, default=now) lr_billingparty = models.CharField(max_length=255, default=0) # supplier company name foreign key invoice_no = models.IntegerField(default=0) lr_declared = models.IntegerField(default=0) ewaybill_no = models.IntegerField(default=0) lr_quantity = models.IntegerField(default=0) # quantity lr_weight = models.IntegerField(default=0) # weight lr_invoice_date = models.DateTimeField(max_length=255, default=now) lr_item_name = models.CharField(max_length=255, default=0) # said to contain lr_consignor_name = models.CharField(max_length=255, default=0) # shipper company name lr_consignor_address = … -
How to display a 3-way dependent drop-down menu in django form
I'm using Django 2.2. When registering for my project, I would like to see a drop-down list of provinces, districts and neighborhoods needed for the user's address. In other words, after the selection of provinces and districts selected after the province selection, the selected neighborhoods are listed. models.py from django.db import models from django.contrib.auth.models import User from django.contrib import admin from .choices import * class Province(models.Model): name_province = models.CharField(max_length=50, default=1, verbose_name="Province") def __str__(self): return self.name_province class District(models.Model): province = models.ForeignKey(Province, on_delete=models.CASCADE, blank=True, null=True) name_district = models.CharField(max_length=50, default=1, verbose_name="District") def __str__(self): return self.name_district class Neighborhood(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE, blank=True, null=True) name_neighborhood = models.CharField(max_length=50, default=1, verbose_name="Neighborhood") def __str__(self): return self.name_neighborhood class StoreOtherInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True, null=True) phone = models.CharField(max_length=11,verbose_name="Phone_Number") fax = models.CharField(max_length=11,verbose_name="Fax") province = models.ForeignKey(Province, on_delete=models.SET_NULL, null=True) district = models.ForeignKey(District, on_delete=models.SET_NULL, null=True) neighborhood = models.ForeignKey(Neighborhood, on_delete=models.SET_NULL, null=True) avenue = models.CharField(max_length=50,verbose_name="Avenue") street = models.CharField(max_length=50,verbose_name="Street") block = models.CharField(max_length=80,verbose_name="Block") number = models.CharField(max_length=11,verbose_name="Number") storey = models.CharField(max_length=11,verbose_name="Storey") profile_image = models.FileField(blank = True,null = True,verbose_name="Add Photos") def __str__(self): return self.user.username class Meta: verbose_name_plural = 'Other Informations' views.py def register(request): form = RegisterForm(request.POST or None,request.FILES or None ) if form.is_valid(): user = form.save(commit=False) first_name = form.cleaned_data.get("first_name") last_name = form.cleaned_data.get("last_name") username = form.cleaned_data.get("username") email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') … -
Architectures list you can suggest for Django
I'm looking for Arcihectures for Django. What I'm really looking for is that I'm looking for a structure that has features like error management and separate security. A structure similar to layered architecture like .net core. I found a sample project https://github.com/Oscar-Garcia/django-hexarch-example, but I want to see more architecture. I couldn't find it online. -
How to accept form data and return it along with the results of some processing in Django RESTFramework?
I am trying to understand Django RESTFramework. I am already familiar with Django. I want to create an endpoint that accepts some text data and processes it and returns it to the user along with the results of the processing (in text). I have completed a couple of tutorials on the topic but I still don't understand how it works. Here is an example from a working tutorial project. How can I edit it to achieve my goal? It all looks automagical. # views.py from rest_framework import generics from .models import Snippet from .serializers import SnippetSerializer class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): # Here I would like to accept form data and process it before returning it along with the # results of the processing. queryset = Snippet.objects.all() serializer_class = SnippetSerializer -
Django mail not sending mail
I have created a function the would send mail to a particular user when redirected to a particular url. It was working until today. However, today when it gets redirected to the url, the email is displayed in the terminal and not in the inbox of reciever. I am attaching the mail function and settings in the code. views.py def mail(request,pk): pr = UserProfile.objects.get(pk=pk) subject = "Greetings" msg = "Congratulations for your success" to = 'urvi0728@gmail.com' res = send_mail(subject, msg, settings.EMAIL_HOST_USER, [to]) if(res == 1): msg = "Mail Sent Successfuly" else: msg = "Mail could not be sent" return HttpResponse(msg) settings.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'urvi271296@gmail.com' EMAIL_HOST_PASSWORD = 'admin@site' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
Not getting the expected layout(design) on my Django website
I am designing a website using django, following the steps of a course that I've enrolled recently. All the code & resources have been provided to me. I'm following each and every step accordingly but the layout of my website is not similar to what I'm following. I faced similar problem when I was trying on similar project that I tried before the current one. The layout of my website is way too simple. I'm using the latest versions so i guess there maybe something that I've to include. It would be really helpful if someone let me know what am I missing. The image is also not displaying on my website. -
django multi-table inheritance validation with the admin app
When working with a Django Model with multi-table inheritance set-up as in the docs, the admin app cannot add a new "Restaurant" model if a matching "Place" entry exists - the admin app returns "Place with this name already exists". Django's ModelForm provides methods for data validation, is this the best place to enable turning the existing Place entry into a Restaurant? How would you achieve this? For Example, a Place(name="hotdogshop", address="bond street") exists, and the user tries to add a Restaraunt( serves_hot_dogs=True, serves_pizza=False, name="hotdogshop", address="bond street" ). The desired end result would be the same as if we had added the "hotdogshop" as a "Restaraunt" to begin with. -
Two projects under one virtual envrionment
First time I am taking over a professional app and I am asked to extend the app. Basically, there is a running application under virtualenv. I am supposed to add a new project (A2) that will make use of models defined by project A1 and a few other methods/functions defined in A1. I created A2 in same directory level as A1 in same env: env A1 app1 app2 A2 app1 app2 Now the problem is A2 doesn't know all plugins installed in the environment while A1 does. So all my django imports are failing. Secondly, I can't seem to do: from A1.app1.models import Question it can't find it. A1 will never import anything from A1 but A2 will make use of A1's. If it matters, A1 will have its own urls, settings and A2. A2 doesn't create migrations either. How would I go handling such a structure? -
How can I solve "TypeError at /post/new/" in django
While trying to create a new form in Django vesrsion 2.2. I ran into this error TypeError at /post/new/ join() argument must be str or bytes, not 'tuple'. I have really tried solving the issue but I can't solve it. These are the steps have taken.. I add a new URLConf for post_new at the app level(blog folder) # blog/urls.py from django.urls import path from . import views urlpatterns = [ path('post/new/', views.BlogCreateView.as_view(), name='post_new'), ] Then, create the view by importing a generic class called CreateView and then subclass it to create a new view called BlogCreateView. # blog/views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from . models import Post class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = '__all__' And the last step is I create the template, which we will call post_new.html. <!-- templates/post_new.html --> {% extends 'base.html' %} {% block content %} <h1>New post</h1> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock %} Edited to add the full traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/post/new/ Django Version: 2.2 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Invalid object name "django_migrations" when trying to runserver
I wanted to connect my Django app to client's MSSQL database (Previously my app worked on SQLite). I made an migration on their test server and It worked successfully, then they copied this database to destination server and when I try to python manage.py runserver It shows me just django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'django_migrations'. (208) (SQLExecDirectW)") What can be possible problem with this? This is my connection: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'ESD', 'HOST': 'IPaddress', 'USER': 'Username', 'PASSWORD': 'Password', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server' } } } -
How to fix raise ValueError("Unknown string format:", timestr) when importing excel that includes one of the fields is empty
datefield error when null with django openpyxl I want to import excel sheet but ones date fields are empty. class Drgmt(models.Model): date_ori = models.DateTimeField(default=None, null=True, blank=True) def import(request): #Many lines before date_ori = dt.datetime.strftime(parse(row_data[19]), '%Y-%m-%d %H:%M:%S') #Many lines after -
Django not able to create tables in postgresql
i am using django==2.2.1, postgres==10.8 and psycopg2==2.8.1 in ubunut 18.04 when i run makemigrations and migrate it's run successfully but the change not appear in postgres it gives me error django.db.utils.ProgrammingError: column ip_management_ipmanage.userTeam_id does not exist LINE 1: ...k_id", "ip_management_ipmanage"."userGateway_id", "ip_manage...