Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: List and Display Data from DB
I found a code that the urls in django can contain a model, so it can display a db values directly to html, but when i tried it, i got some error in the urls because this code still using patterns, is it possible doing this thing in a newer django? The Url from django.views.generic import ListView from django.conf.urls import patterns, url urlpatterns = patterns("myapp.views", url(r'^dreamreals/', ListView.as_view( template_name = "dreamreal_list.html")), model = Dreamreal, context_object_name = ”dreamreals_objects” ,) The HTML {% extends "main_template.html" %} {% block content %} Dreamreals:<p> {% for dr in object_list %} {{dr.name}}</p> {% endfor %} {% endblock %} -
django.db.utils.IntegrityError: NOT NULL constraint failed - drf_writable_nested
Created a simple app that allows me to create clients and then also add a features list as a field (which has multiple options). models.py from django.db import models class Feature(models.Model): feature1 = models.BooleanField(default=None) feature2 = models.BooleanField(default=None) feature3 = models.BooleanField(default=None) class Client(models.Model): client_name = models.CharField(max_length=200) org_id = models.CharField(max_length=100) date_created = models.CharField(max_length=100) features = models.ManyToManyField(Feature, related_name='client_list') serializers.py from rest_framework import serializers from .models import Client, Feature from drf_writable_nested import WritableNestedModelSerializer class featureSerializer(serializers.ModelSerializer): class Meta: model = Feature fields = ('feature1', 'feature2', 'feature3') class clientSerializer(WritableNestedModelSerializer): features = featureSerializer(many=True) class Meta: model = Client fields = ('id', 'client_name', 'org_id', 'date_created', 'features') python shell >>> data = {'client_name': 'Test Client XYZ', 'org_id': '001', 'date_created': '2018-03-06', 'features': [{'feature1': True}, {'feature2': False}, {'Feature3': True},],} >>> serializer = clientSerializer(data=data) >>> serializer.is_valid() True >>> print(serializer) clientSerializer(data={'client_name': 'Test Client XYZ', 'org_id': '001', 'date_created': '2018-03-06', 'features': [{'feature1': True}, {'feature2': False}, {'feature3': True}]}): id = IntegerField(label='ID', read_only=True) client_name = CharField(max_length=200) org_id = CharField(max_length=100) date_created = CharField(max_length=100) features = featureSerializer(many=True): feature1 = BooleanField(required=False) feature2 = BooleanField(required=False) feature3 = BooleanField(required=False) >>> print(serializer.data) {'client_name': 'Test Client XYZ', 'org_id': '001', 'date_created': '2018-03-06', 'features': [OrderedDict([('feature1', True)]), OrderedDict([('feature2', False)]), OrderedDict([('feature3', True)])]} but when I actually go to save using: >>> client = serializer.save() I get the following … -
Django: How to differentiate ManyToMany relationship with the same model
Suppose User can block other User. Now I'm working on ManyToManyField that represents the list of blocked user. And the user can stop blocking other user as well. So I want to create a list of blocked user so the user can stop blocking. However, the problem is if user A blocked user B, the blocked user list userB has has userA even though userA added userB to ManyToManyField. How can differentiate the relationship each user has in this case? class User(AbstractUser): block_users_list = models.ManyToManyField("self", blank=True) -
How to integrate web push notifications with Django backend?
I just completed Google Developer's web push notification tutorial(https://developers.google.com/web/fundamentals/codelabs/push-notifications/ ). I want to integrate it with my Django backend. Url endpoint (/notifications) gives list of unread notification of current logged-in user. I want to push same notifications via web push service. How can i do it? -
Django data transfer sqllite - >> models - >> html
There is a separate script that works with some sites and writes the selected data to the database. Here is its part associated with the database. conn = sqlite3.connect("bgg1.db") conn.text_factory = str cursor = conn.cursor() # delete cursor.execute("""DROP TABLE yres;""") sql_command = """ CREATE TABLE yres ( name VARCHAR(100), track VARCHAR(100), number VARCHAR(100), point VARCHAR(100));""" cursor.execute(sql_command) cursor.execute ("INSERT INTO yres (name, track, number, point) VALUES (?, ?, ?, ?)", (str(td_text[1]),str(td_text[5]),str(td_text[6]),str(df['attribute.name'] [0]))) conn.commit() Then I have a jango project with a connected template .. and everything else .. and I want to output the data to an html file .. I don’t know how to do it through models or how. And how to start my script when starting a project? Run automatic model generation $ python manage.py inspectdb $ python manage.py inspectdb > models.py Created some model .. and then I do not know what to do models.py from django.db import models class AuthGroup(models.Model): id = models.IntegerField(primary_key=True) # AutoField? name = models.CharField(unique=True, max_length=80) class Meta: managed = False db_table = 'auth_group' class AuthGroupPermissions(models.Model): id = models.IntegerField(primary_key=True) # AutoField? group = models.ForeignKey(AuthGroup, models.DO_NOTHING) permission = models.ForeignKey('AuthPermission', models.DO_NOTHING) class Meta: managed = False db_table = 'auth_group_permissions' unique_together = (('group', 'permission'),) class AuthPermission(models.Model): … -
Django DRF | Disable OneToOneField Model "create" action once the model has been created
I have a User model and another Customer model with a OneToOneField relation with User model. So there can exist only one Customer model corresponding to User model. And an attempt to create a Customer model again (invoking the create endpoint) results in an error saying "Duplicate entry for primary key". So I want to disable create endpoint for that User once a Customer model has been created by him. My Permissions class for Customer: class UpdateCustomerProfile(permissions.BasePermission): """Allow users to edit their own profile """ def has_permission(self, request, view): """Check if user is authenticated and has permisson to access customer model """ # aunthenicated passed because superuser is being allawed in CustomerViewSet if view.action == 'list': return request.user.is_authenticated # Try and add a check for an already existing Customer model for the user. elif view.action == 'create': return request.user.is_authenticated elif view.action in [,'retrieve', 'update', 'partial_update', 'destroy']: return request.user.is_authenticated and request.user.user_type == 'CS' else: return False I was thinking of adding an is_profile_set field to my User model and set it to true when a Customer Profile is created for that User. and then I can check for that field in my Permissions class. But I'm not sure this is the … -
How can I make changes in Django runtime?
I have hard time when developing django on my docker. When I make any changes to the code, I need to restart whole container for the changes to take effect. I have a filesystem mounted locally and the changes are made locally. But even if I make changes directly in the container, make migrations or touch an affected or wsgi file, the changes do not take any effect. This is the image in compose file backend: container_name: 'backend' image: dronetag/alpha-docker/backend build: ./images/backend/ command: > sh -c " python manage.py collectstatic --no-input; python manage.py migrate; gunicorn backend.wsgi -b 0.0.0.0:80;" ports: - "10080:80" - "10443:443" volumes: - ./src/backend:/src depends_on: - postgres links: - redis - postgres Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV C_FORCE_ROOT true RUN mkdir /src WORKDIR /src COPY requirements.txt . RUN pip install -r requirements.txt -
View for Authenticated User with Microsoft Graph in Django
Started learning Django a week ago and now I'm bumping into some issue with authentication. The problem is that I need to authenticate users who are users of my organisation before they can use the applications. I'm following this tutorial from Microsoft and everything has worked fine. Now I want to add another page from the navigation bar (named "Commentary") that contains a form where authenticated user can submit multiple excel files that contains commentary data. The purpose is to use python to scrap some desired data (commentary data) from these files. So my template should have a form field where users can upload multiple files. My commentary.html template looks like this and I am pretty sure it's not right. commentary.html <form action="{% url 'commentary' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload" /></p> Here's my views.py file. from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views.generic.edit import FormView from tutorial.auth_helper import get_sign_in_url, get_token_from_code, store_token, store_user, remove_user_and_token, get_token from tutorial.graph_helper import get_user, get_calendar_events from tutorial.forms import FileFieldForm import dateutil.parser class FileFieldView(FormView): form_class = FileFieldForm template_name = … -
Django Using Pycharm
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environmen t variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Help Me! -
showing the entries in admin panel based on selected type
while creating an album in your admin panel, you require that the music_track should only show the titles having type as track class Title(models.Model): type = models.ForeignKey(Asset_Type,on_delete=models.CASCADE,null=True) owner = models.ForeignKey(Partner, null=True, blank=True) genre = models.ForeignKey(Genres_List, null=True) def __str__(self): return "%s | %s" % (self.display_name, self.code) class Album(models.Model): album_name = models.CharField( max_length = 150, blank = False ) titles = models.ManyToManyField( Title ) genre = models.ForeignKey(Genres_List, null=True) added_on = models.DateTimeField( auto_now_add = True ) release_date = models.DateField(default=date.today ) def __str__ (self): return "%s" % (self.album_name) -
How to ensure that there are unique items in PageChooserBlock (Wagtail)?
How to validate the uniqueness of all pages when adding page content via wagtail admin panel? content = StreamField([ ('solutions', blocks.StreamBlock([ ('solution', blocks.PageChooserBlock(SolutionPage)), ], required=False)), ], blank=True, null=True) Note! The project runs on wagtail 1.12.3. -
Django DRF restrict profile model creation to authenticated user
I have a many User model and a Customer model with a OneToOne relation to the User. I have established authentication for User model where a user can edit/update/delete only his profile. But I want the customer model also to be accessible (list/create/update etc) by the authenticated user. My permissions class for Customer: class UpdateCustomerProfile(permissions.BasePermission): """Allow customers to edit their own profile """ def has_permission(self, request, view): """Check if user is authenticated and has permisson to access customer model """ if view.action == 'list': return request.user.is_authenticated and request.user.is_superuser elif view.action == 'create': return request.user.is_authenticated elif view.action in ['retrieve', 'update', 'partial_update', 'destroy']: return request.user.is_authenticated else: return False My customer view set: class CustomerViewSet(viewsets.ModelViewSet): """Handle creating reading and updating Users in system""" serializer_class = serializers.CustomerSerializer queryset = models.Customer.objects.filter() permission_classes = (permissions.UpdateCustomerProfile,) But I get an error saying: "detail": "Authentication credentials were not provided." even If I add the token in Authorisation field of Header. How can I fix this? -
Django: model object related table not exist
It has been quite a while since I'd used MySQL DB using django ORM. And When I tried to make a dump file so that I can move the data to another database, I figured out some one of the table were missing. Below is the relevant code in mainapp.models.py class Review(models.Model): id = models.CharField(max_length=100, primary_key=True) title = models.TextField(blank=True) contents = models.TextField(blank=True) I expected table 'mainapp_review' should be in the database but any query or execution related to this query didn't work saying it doesn't exist. Also, 'show tables' command result confirmed mainapp_review is not there. My question now is, if it is true, where those row data exist then? And how django ORM has been able to do CRUD when there is no table for that? -
How to sign up the user with the custom user model
When i am signing up the user in the custom signin form i am getting the following error: AttributeError: Manager isn't available; 'auth.User' has been swapped for 'App.MyUser' Views.py -------- def signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] password = userObj['password'] fname = userObj['fname'] lname = userObj['lname'] print (username,password,fname,lname) if(len(password)<8): messages.error(request,"This password length should be minimum 8 characters") #raise ValidationError("This password length should be minimum 8 characters ") validate_password_strength(password) if not (User.objects.filter(username=username).exists()): p = Event(fname=fname, lname=lname, username=username) p.set_password(password) p.save() # return HttpResponseRedirect('Login.html') return redirect('/Login/') else: raise forms.ValidationError('Looks like a username with that username or password already exists') else: form = UserRegistrationForm() return render(request, 'signup.html', {'form':form}) settings.py: --------------- AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend", 'django.contrib.auth.backends.RemoteUserBackend',) AUTH_USER_MODEL = 'auth.User' urls.py: --------- urlpatterns = [ url('admin/', admin.site.urls), url('Provisioning/', include('django.contrib.auth.urls')), url(r'^signup/', views.signup,name='signup'), url(r'^Login/', views.Login,name='Login'), url(r'^Logout/', views.Logout,name='Logout'), models.py: ----------- class MyUserManager(BaseUserManager): def create_user(self, fname,lname,username, password): """ Creates and saves a User with the given username, date of birth and password. """ if not username: raise ValueError('Users must have an username') user = self.model(username=username,fname=fname,lname=lname) user.set_password(password) user.is_active = True user.save(using=self._db) print (user) return user def create_superuser(self, fname,lname,username, password,email=None): """ Creates and saves a superuser with the given username and password. """ … -
How to use ajax with python data
I am working on a django application. In the application a user can upload a csv file. That csv file is then processed with pandas and a html table is generated with the pandas to_html function. This html table is then displayed on the webpage. Until now, when the form is uploaded, the page would reload and then the html table would be displayed. This was a problem as I could not add any animations to the webpage as the page refresh would mess up the styling in the webpage. Take a look at the screenshots below BEFORE AJAX 1. When the page is first loaded 2.when the start button is clicked 3.when a csv file is uploaded So overcome this problem, I used ajax to submit the form and bypass the default page refresh. While the default actions are prevented and the form is successfully submitted, the page still looks messed up. AFTER AJAX the first two steps are the same as above 3.when a csv file is uploaded The title when the page is loaded has a size of 10em. When the start button is clicked, it is animated to 3em. and the start button should disappear on … -
Django CreateView Custom Widget Override
I want to override the DateTimeField widget in the sendDate field in my emailCreate(CreateView) ModelForm with a custom widget(XDSoft DateTimePicker). Here is the process to do so for a regular form:https://simpleisbetterthancomplex.com/tutorial/2019/01/03/how-to-use-date-picker-with-django.html#xdsoft-datetimepicker My form generates but the sendDate Field still does not display the custom widget. Any help is appreciated, here is my code: forms.py from django import forms from django.forms import ModelForm from .widgets import XDSoftDateTimePickerInput from .models import email from django.contrib.admin import ModelAdmin class emailForm(forms.ModelForm): class Meta: model = email fields = ('name', 'sendDate', 'sendClassification') widgets = { 'sendDate': XDSoftDateTimePickerInput() } Models.py from django.db import models from django.urls import reverse import datetime # Create your models here. class email(models.Model): name = models.CharField(max_length=250) sendDate = models.DateTimeField(null=True, blank=True) CLASSIFICATION_CHOICES = ( ('Best Buy Movers Program', 'Best Buy Movers Program'), ('BestBuyConnect', 'BestBuyConnect'), ) sendClassification = models.CharField(max_length=2,choices=CLASSIFICATION_CHOICES, default='BestBuyConnect') def get_absolute_url(self): # reverse expects the view name return reverse('formappdb') Views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import loader from .models import email from django.views.generic.edit import CreateView, UpdateView, DeleteView from .forms import emailForm def index(request): all_emails = email.objects.all() template = loader.get_template('formapp/index-brett.html') context = { 'all_emails': all_emails, } return HttpResponse(template.render(context, request)) class emailCreate(CreateView): model = email form_class = emailForm Widgets.py from … -
are atomic transactions in django on database level?
I have a django backend application that I'm running on a docker container, I'm using atomic transactions at some places where it's needed So because I have high traffic and there are many places that require expensive computations, I wanted to run another instance of the django application, and balance the load, My question is given instance1 started an atomic transaction, and instance2 want to start an atomic transaction on the same record, does instance2 sees that instance1 is running an atomic transaction so the request will wait till instance1 is finished? Thanks -
Unable to redirect to custom error page in django
I'm working in Django & trying to redirect all 500, 404 errors to an error page but it is still not showing the custom message and showing the default message, Server Error (500) below are my code files, settings.py DEBUG = False ALLOWED_HOSTS = [ '*' ] TEMPLATE_DEBUG = False TEMPLATE_DIRS = ( 'C:/Users/Test/dummy/app1/app/templates', ) app urls.py from django.conf.urls import handler404, handler500 from django.urls import path from app import views urlpatterns = [ path('', views.index, name='index'), # other paths ] handler404 = views.error_404 handelr500 = views.error_500 error_404 function in views.py def error_500(req): return render(req, 'app/error_404.html') I have tried all the below questions but none of them worked, Url for 404 page in Django Redirect any urls to 404.html if not found in urls.py in django Custom Django 404 error Django, creating a custom 500/404 error page Implementing http404 in django -
Heroku Django deployment is successful but the application url is showing "Application error"
I am able to deploy to create and deploy the Django app on Heroku. My app runs locally. But when I run heroku open I get the default error message An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. wsgi.py import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allistic_server.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) Procfile web:gunicorn server.wsgi --log-file requirements.txt Django==2.0.8 djangorestframework==3.9.1 gunicorn==19.7.2 whitenoise==3.6 heroku logs --tail 2019-03-05T19:14:22.539357+00:00 heroku[run.5495]: Awaiting client 2019-03-05T19:14:22.621479+00:00 heroku[run.5495]: Starting process with command `python3 manage.py migrate` 2019-03-05T19:14:30.032541+00:00 heroku[run.5495]: State changed from up to complete 2019-03-05T19:14:30.012744+00:00 heroku[run.5495]: Process exited with status 0 2019-03-05T19:14:32.734812+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=allistic-server.herokuapp.com request_id=8ad9d0a4-c449-4d43-8c0d-dbca27057c15 fwd="1.186.161.14" dyno= connect= service= status=503 bytes= protocol=https 2019-03-06T03:48:06.561682+00:00 app[api]: Starting process with command `bash` by user nedheesh.hasija@gmail.com 2019-03-06T03:48:12.189344+00:00 heroku[run.5469]: Awaiting client 2019-03-06T03:48:12.352258+00:00 heroku[run.5469]: State changed from starting to up 2019-03-06T03:48:42.200755+00:00 heroku[run.5469]: State changed from up to complete 2019-03-06T03:48:42.208643+00:00 heroku[run.5469]: Error R13 (Attach error) -> Failed to attach to process 2019-03-06T03:48:42.208643+00:00 heroku[run.5469]: Process exited with status 128 2019-03-06T03:49:06.415742+00:00 app[api]: Starting process with command `python3 manage.py makemigrations server` by user nedheesh.hasija@gmail.com 2019-03-06T03:49:11.116008+00:00 heroku[run.8566]: State changed from starting … -
How do I make a QuerySet in Django to see if a name in the database is a substring of my query string?
As the title mentions, I am working in Django and trying to make a QueryString to return all "Customer" models that have a name value that is a substring of my query_string. I want something like this: Customer.objects.filter(firstName__icontains=query_string) But in reverse: Customer.objects.filter(query_string__icontains=firstName) Except that obviously doesn't work. I am struggling to find any information on how I would go about this. Thanks in advance. -
Django formula constructor
I have a project for medical and educational purposes, so there is one module that is about formula processing, like calculating dose of insulin, BMI (body mass index), etc. So how can I perform arithmetic formulas on backend? (I have plans for built-in operator module) Should I create model for variables or formulas? How to intercept zero division exceptions? -
get_queryset providing duplicate responses
I am creating a simple online shop app so when you want to buy and item, a button click leads you to the charge api. (ex. item 2 will direct to /api/charge/2) urls.py from django.urls import path from gallery.views import ClothingView from gallery.api.views import ListClothes from gallery.api.views import ChargeView urlpatterns = [ path('api/<int:num>/', ListClothes.as_view()), path('api/charge/<int:num>', ChargeView.as_view(), name='charge_api'), ] views.py class ChargeView(ListCreateAPIView): serializer_class = ChargeSerializer count = 0 def get_queryset(self): a = ClothingModel.objects.filter(id=self.kwargs['num']).first() net_price = int(float(a.full_price) * 100) if float(a.discount) > 0.00: net_price = int(net_price * (1 - (float(a.discount) / 100))) self.count += 1 print(self.count) if self.count == 1: stripe.api_key = settings.API_KEY charge_rtn_body = stripe.Charge.create( # Create charge object amount=net_price, currency="usd", source="tok_visa", # obtained with Stripe.js description= "[Stripe charge] " + a.description.upper() ) return ClothingModel.objects.filter(id=self.kwargs['num']) serializers.py class ChargeSerializer(serializers.ModelSerializer): class Meta: model = ClothingModel fields = ('full_price', 'discount', 'description') I am creating a charge object for Stripe (payment method) each time the api gets called, but dependent on the clothing item id. So to handle this I use self.kwargs on get_queryset() to link to a clothing item. When I view the charges on my Stripe dashboard, multiple charges come at once (4 at a time). I have hard coded the if self.count … -
Django custom middleware executing twice
I am writing a middleware to track user activity by writing it to a file; the pages visited by him, the buttons clicked and so on and so forth. To test my middleware for now I am just writing a message to the file. But for some reason the message is being written twice to the file. And I am on django 1.11 Here is my middleware: from django.http import HttpResponse import datetime class TodoappMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): f = open("--my file path--", 'a') date_and_time = datetime.datetime.now() f.write('\n') f.write(str(date_and_time)) f.write('\tMiddleware successfully executed\n') f.close() response = self.get_response(request) return response -
Django - View is not rendering to HTML
Pretty straight forward question…. My view named create_view renders data correctly out of my model and my other view named create_view_two view doesn’t. How do I get my view named create_view_two to render data to home.html? Cheers #user_profile/views.py from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponseNotFound from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.conf import settings from .forms import HomeForm from .models import Listing from users.models import CustomUser def create_view(request): form = HomeForm(request.POST or None, request.FILES or None,) user_profile = Listing.objects.all() user = request.user if request.method == "POST": if form.is_valid(): listing_instance = form.save(commit=False) listing_instance.user = user listing_instance.save() return redirect("myaccount") context = { 'form': form, 'user_profile': user_profile } return render(request, "myaccount.html", context) def create_view_two(request): form_two = HomeForm(request.POST or None, request.FILES or None,) user_profile_two = Listing.objects.all() user = request.user context = { 'form': form_two, 'user_profile': user_profile_two } return render(request, "home.html", context) #user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.models import CustomUser class Listing (models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) rank = models.CharField(max_length=100, null=True) name = models.CharField(max_length=100) address = … -
Ledger-cli for Django project
I am developing a Django payment related project where more transaction is involved for that reason I am thinking to use this ledger-cli https://www.ledger-cli.org/ which is giving an option for python but not for Django framework. My question is that is it worth using that https://www.ledger-cli.org/ or can I go with conventional Django framework to develop the payment gateway. I have one more question for what purpose we can use https://www.ledger-cli.org/ in the project.