Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save user input in database from django form
I hava created a small project in django where i have created a form and with 3 fields now i want if user type his name , email and invite message then it should save in databse. i am unable to save the data in database. form.py from datetime import datetime from bootstrap_datepicker_plus import DatePickerInput from django.contrib.admin.widgets import AdminDateWidget from bootstrap_datepicker_plus import DateTimePickerInput from bootstrap_datepicker_plus import TimePickerInput # from .models import check class Email_app(forms.Form): Name = forms.CharField() Email = forms.EmailField() Invite = forms.CharField() start_date = forms.DateField(label="Start_Date", widget=DatePickerInput()) start_time = forms.DateField(label="Start_Time", widget=TimePickerInput()) end_date = forms.DateField(label="End_Date", widget=DatePickerInput()) end_time = forms.DateField(label="End_Time", widget=TimePickerInput()) def __str__(self): return self.Name Form > enter image description here below is the view.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import formatdate # from email import encoders from email.encoders import encode_base64 import os,datetime COMMASPACE = ', ' # from django.shortcuts import render # Create your views here. from django.shortcuts import render from operators.settings import EMAIL_HOST_USER from . import forms from django.core.mail import send_mail # Create your views here. #DataFlair #Send Email def email_app(request): sub = forms.Email_app() if request.method == 'POST': sub = forms.Email_app(request.POST) subject = 'Welcome to Email Event' message = … -
Passing Data Through AJAX Call Causes Failure
I am building a really simple AJAX call using Python/Django. I've never had issues with it before, but now I keep on getting a Not Found error if I ever put actual data in the AJAX call. Works fine if I place no data. I must be making a very obvious mistake that I just can't see. In my code below, if I comment out the #test value it will work fine, so I know all the URLs are working correctly. It's just if I add any real data it fails (#product_id_notes is just filler, does not refer to an actual ID). Can anyone help bail me out here? This has been driving my crazy for the last several hours. My error: Not Found: /admin/ajax/order_analysis My code: <button id = 'test1234' >Submit</button> <input id = "submit-order-analysis-url" type = 'hidden' value = ' {% url 'admin:order_analysis' %} '> <div id = "test" value = "123">This is a test</div> <script> $('#test1234').click(function(){ var url = $('#submit-order-analysis-url').val(); var data = {'test':$('#test').val(), 'product_id':$('#product_id_notes').val() } $.ajax({url: url, data: data}) .done(function(data){ //do nothing }) .fail(function(){ //do nothing console.log("Something went wrong") }); }) </script> -
How to aggregate time for each employee in bi-weekly pay schedule in Django
How to add up time_work for each employee up to 15th of each month? class TimeLog(models.Model): employee = models.IntegerField(null=True, blank=True, related_name='employee id') start_date = models.DateTimeField (null=True, blank=True) end_date = models.DateTimeField (null=True, blank=True) time_worked = models.DurationField(null=True, blank=True) -
Python requests login to django
hey im trying to login into the django page at https://extensions.gnome.org/ import requests from bs4 import BeautifulSoup client = requests.Session() client.headers.update({"referer": "https://extensions.gnome.org/accounts/login/"}) data = client.get("https://extensions.gnome.org/accounts/login/") soup = BeautifulSoup(data.text) mtoken = soup.find("input", {"name": "csrfmiddlewaretoken"}) print(mtoken["value"]) csrftoken = client.cookies["csrftoken"] login_data = client.post("https://extensions.gnome.org/accounts/login/", data={ "csrfmiddlewaretoken": csrftoken, "username": "email", "password": "password", "next": "/" }) print(login_data.text) but the response is always invalid csrf token. has someone an idea how to get this working? -
Update Django model instance only if certain condition is met
I'm trying to solve what looked like an easy problem at first to me and probably I'm overthinking it, but I'm unsure where to put the bit of logic required, so any input would be much appreciated. Following situation (example code, not real project) # models.py class Product(models.Model): title = models.CharField() price_in_cents = models.IntegerField() # ... class ProductImage(models.Model): product = models.ForeignKey('Product', null=True, blank=True) image = models.ImageField() user = models.ForeignKey(get_user_model()) # ... So in short I have products and images that show these products. This is part of a DRF project which is consumed by a Vue frontend. The flow is as follows: The client creates new images by posting the image data to /api/productimages/ The API creates the Image instance and returns the data including the created instances PK. The client then posts a list of image ids along with the data to create the product to /api/products/ the api creates the product and should now associate the passed images with the created product. This should only happen if current user == image.user and image.product is not set yet (==Null) Now my question: Where should I put the logic to associate the images with the created product? I see the … -
Django ValidationError when serializing nested object
So I have a serializer like this: class FirstSerializer(serializers.ModelsSerializer) second = SecondSerializer() class Meta: model = First While validating SecondSerializer may raise ValidationError. If it does, in return I get this: { "first": { "second": [ "Error" ] } } How can I make this error not connected with validated field, for example: { "non_field_errors": [ "Error" ] } -
Django whats the .distinct('column_name') for SQLite equivalent?
In my current project, I need to select all distinct elements from my SQLite database and I wanted to use: distinct_ingredients = Ingredients.objects.all().distinct('ingredient') But I learned that this just works for I think PostgreSQL, so my question is what is the equivalent to .distinct(column_name) for an SQLite Database? I tried different things out but the didn't give me the distinct ones. Thanks for your help. -
Currency symbol not displaying correctly on Saleor platform
Please I have some issue with displaying the right currency symbol for Naira in saleor platform. In the documentation, I saw it could be changed by redefining DEFAULT_CURRENCY in settings.py DEFAULT_CURRENCY = os.environ.get("DEFAULT_CURRENCY", "USD") How I approached the issue: Saleor-platform default currency came with USD which displayed $ as the currnecy symbol (e.g $ 1000) Then I changed it to NGN but it displayed NGN as the currency symbol (e.g NGN 1000) instead of ₦1000 And then I tried changing it to EUR and it displayed € as the currency symbol (e.g €1000) Maybe minor countries where not considered while building the platform. Please could there be a way to tweak this? see screenshot of the display below: saleor currency display -
Django: get_or_create not creating object, only reporting error that matching query does not exist
I am making my first django web (mostly for fun -hence the theme, toilet rating app- and learning). But this stopped being fun a day ago. I am trying for user to be able to create and rate the toilets (create/update user's rating). Creation is fine, the rating is where I have all the issues. The current and biggest problem is that line rating, created = Rating.objects.get(user_id=user, toilet_id=toilet) is throwing rating.models.Rating.DoesNotExist: Rating matching query does not exist. Now the snippets: VIEW: @login_required(login_url='login') def rate_toilet_view(request, upk, tpk, *args, **kwargs): toilet = Toilet.objects.get(id=tpk) user = User.objects.get(id=upk) rating, created = Rating.objects.get(user_id=user, toilet_id=toilet) form = RatingForm(instance=rating) if request.method == "POST": form = RatingForm(request.POST, instance=rating) if form.is_valid(): form.save() toilet = Toilet.objects.get(toilet_id = toilet) # SOME COMPUTATIONs HERE toilet.save() return redirect('/') context = {'form': form} return render(request, 'pages/rate_toilet_form.html', context) MODELS: class Rating(models.Model): id = models.IntegerField(primary_key=True, auto_created=True) user_id = models.ManyToManyField(User, through='RatingUser') toilet_id = models.ManyToManyField(Toilet, through='RatingToilet') # FIELDS TO BE RATED HERE class RatingUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.ForeignKey(Rating, on_delete=models.CASCADE) class RatingToilet(models.Model): toilet = models.ForeignKey(Toilet, on_delete=models.CASCADE) rating = models.ForeignKey(Rating, on_delete=models.CASCADE) class Toilet(models.Model): CATEGORY = (#CATEGORIES OF TOILETS HERE#) id = models.IntegerField(primary_key=True, auto_created=True) category = models.CharField(max_length=120, null=False, choices=CATEGORY, default=None) place = models.CharField(max_length=120) # OVERAL VALUES OF RATED … -
URL Keep Adding Backslash Django
I need your help in fixing this issue. urlpatterns = [ path('', views.dashboard, name='dashboard'), path('menu', views.menu, name='menu'), path('close', views.close, name='close'), path('lead', views.lead, name='lead'), path('audience', views.audience, name="audience"), path('audience/<action>', views.audience, name="audience") ] That's my code URLs but I keep getting a backslash at the end of the URL. For instance, if I link to dashboard/menu, I get dashboard/menu/ -
Django 1.11 - Attempting to populate models with fake data using Faker
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() ##fake pop script import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t= Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): #get topic for entry top = add_topic #create fake data fake_url = fakegen.url() fake_Date = fakegen.date() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] # create a fake acess record for taht Webpage acc_rec = AccessRecord.objets.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('populating complete') Hello, so I am working on a Django course, it is using Django 1.11 as the question mentioned, and while trying to populate my models with fake data using Faker, I am getting some errors coming from the Django packages i believe, below are the command line errors i received, thanks in advanced! enter code here (MyDjangoEnv) D:\Coding Projects\DjangoCourse\first_project>python populate_first_app.py populating script! Traceback (most recent call last): File "populate_first_app.py", line 44, in populate(20) File "populate_first_app.py", line 37, in populate webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", l ine 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", lin e 464, in get_or_create return self.get(**lookup), False File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", lin e 371, in get clone = self.filter(*args, … -
Uncaught TypeError: Cannot set property 'innerHTML' of null Django
I know there are many similarly to this question but I can't find a way. I have a table and when I click edit in row table the modal should show and I want to pass data from table to modal and display some data in modal that comes from my table .When the button click it always error and the modal didn't show.I been using Django.Please see the image below. Below is my current code. Can you help me please? Error accounts.html {% extends 'navigation.html' %} {% block content %} <script> function exampleModal(firstName,lastName){ document.getElementById('firstNameValueId').innerHTML = firstName document.getElementById('secondNameValueId').innerHTML = lastName $("#exampleModal").modal('show'); } </script> <!-- mytable --> <div class="tabs-animation"> <div class="card mb-3"> <div class="card-header-tab card-header"> <div class="card-header-title font-size-lg text-capitalize font-weight-normal"><i class="header-icon lnr-laptop-phone mr-3 text-muted opacity-6"> </i>Accounts Information </div> <div class="btn-actions-pane-right actions-icon-btn"> <div class="btn-group dropdown"> <button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="btn-icon btn-icon-only btn btn-link"> <i class="pe-7s-menu btn-icon-wrapper"></i> </button> <div tabindex="-1" role="menu" aria-hidden="true" class="dropdown-menu-right rm-pointers dropdown-menu-shadow dropdown-menu-hover-link dropdown-menu"> <h6 tabindex="-1" class="dropdown-header">Header</h6> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-inbox"> </i><span>Menus</span> </button> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-file-empty"> </i><span>Settings</span> </button> <button type="button" tabindex="0" class="dropdown-item"> <i class="dropdown-icon lnr-book"> </i><span>Actions</span> </button> <div tabindex="-1" class="dropdown-divider"></div> <div class="p-3 text-right"> <button class="mr-2 btn-shadow btn-sm btn btn-link">View Details</button> <button class="mr-2 … -
Provision product with strip and dj-stripe
I'm using stripe with DRF and on top of that, I've implemented the library dj-stripe. Everything works so far but I'm not really sure how to provision my product now. I do have access to the subscription and customer object for every user but these objects are quite complicated / big. I can't really do something like if user.subscription -> do this since the subscription could be e. g. deleted, inactive. I also need a more granular solution since I need to apply limits like: if subscription.plan.product === "Entry Plan": # allow user to only create 5 instances I can't really find information on how to do this elegantly and consistently for an entire app. -
How to add a number range of items per page in custom pagination django rest framework
I have created some serialized data using django rest framework. I am in the process of building a custom pagination, since there is a lot of data that is being serialized. I have managed to add the required key, value pair needed in the custom pagination. The page_size is set to 200. So it currently displays like this : { "totalPages": 11, "totalData": 2065, "currentPage": 2, "nextPage": "http://localhost:8000/cluster/37/tasks?page=3", "previousPage": "http://localhost:8000/cluster/37/tasks", "results": [...] } I want to also display additional data in the custom pagination, I want to display the range of the starting data (firstDataNumber) and the final data (lastDataNumber) in the page. For example in page 1 : { "totalPages": 11, "totalData": 2065, "currentPage": 1, "firstDataNumber" : 1, #first data on page "lastDataNumber" : 200, #last data on page ... } same for page 2, which should be : { "totalPages": 11, "totalData": 2065, "currentPage": 2, "firstDataNumber" : 201, #first data on page "lastDataNumber" : 400, #last data on page ... } How do I achieve this insertion of a range of data number in the custom pagination? Thanks. This is my code on custom pagination so far : class LargeResultsSetPagination(PageNumberPagination): page_size = 200 page_size_query_param = 'page_size' max_page_size = … -
Django TextField does not enforce blank=False
I can't get django.db.models.TextField(blank=False) to enforce non-blank. It seems to ignore the constraint and only enforces not-null. Example: import django.core.exception import django.db.models import unittest class Mymodel(django.db.models.Model): id = django.db.models.AutoField(primary_key=True) text = django.db.models.TextField(blank=False) with self.assertRaises(django.core.exception.ValidationError): Mymodel.objects.create() # <--- should raise validation exception The above code creates a new Mymodel instance with the text field set to a blank string, but instead it should raise a ValidationError -
How do you pass data like this (Shown in the question body) as form data in postman for django rest framework api?
Hey guys I have data like this to be passed on to the form-data in postman or insomnia, but the problem is I am getting this error all the time if I use form-data to send. { "product_variation": [ "This field is required." ] } This is the data I am sending. "product_variation": [ { "size-colour": "1", "size_name": "small", "colour_name": "Green", "price": "100", }, { "size-colour": "2", "size_name": "medium", "colour_name": "Blue", "price": "100", } ] Also, I am not able to send images if I try to send the data as raw json data. Can anyone tell me how to properly send this? Thanks -
How to change default empty representative in forms CharField?
I use an unbound form with BooleanField and CharField None are required but when empty, value in database is a representative empty string for Charfield and 0 for BooleanField I would like NULL value instead but don't find how to set this. class CreateForm(forms.Form): def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields["field1"] = forms.BooleanField(label = "", required = False, initial=None) self.fields["field2"] = forms.CharField(label = "", required = False, initial=None) -
I created an extra table extra table in one to one relation with User table. how to show phone field in User registration
I am trying to create a simple API to get a user register. I am using the default User table for authentication purpose, created another table called "phone" with one to one relation with User. I am trying to add "phone" field just above the password. (I hope the image attached is visible). ** Serializer.py class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = UserDetailsModel fields = ('phone', 'user') class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=68, min_length=6, write_only=True) class Meta: model = User fields = ('username','first_name', 'last_name','email','password') read_only_fields = ('id',) ** models.py<< ** class UserDetailsModel(models.Model): phone = models.IntegerField() balance = models.DecimalField(max_digits=10, decimal_places=2, default=0) user = models.OneToOneField(get_user_model(),primary_key='email' , on_delete=models.CASCADE) def __str__(self): return str(self.user) ** views.py ** class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data,status=status.HTTP_201_CREATED) class DetailsRegisterView(generics.GenericAPIView): serializer_class = UserRegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data,status=status.HTTP_201_CREATED) ** urls ** urlpatterns = [ path('',RegisterView.as_view()), path('details', DetailsRegisterView.as_view()) ] ** -
Post.get in django and html form method
what will be form method in html if i use post.get[] . I tried post and get but it gave me 'method' object is not subscriptable error . -
Docker build getting errors after I tried to install pip install -r requirements.txt file
This is the error I get after I installed RUN pip install -r requirements.txt RROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 ➜ django-docker pip install psycopg2 Defaulting to user installation because normal site-packages is not writeable Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) ERROR: Command errored out with exit status 1: command: /usr/bin/python3.6 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-7xuxd9cm/psycopg2/setup.py'"'"'; file='"'"'/tmp/pip-install-7xuxd9cm/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-uon18vv4 cwd: /tmp/pip-install-7xuxd9cm/psycopg2/ Complete output (23 lines): running egg_info creating /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info writing /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-uon18vv4/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
How to copy information from a table in one project to another project in Django sqlite
I have to projects. They have different Databases. But one table - Brands - is the same. I need to add new brands from one project to another. What is the best way to do it. I tried to do it with the help of dumpdata and load data. But it doesn't work for me. maybe I was doing something wrong. The dumpdata worked well. I've got the json with all the data. But I cannot add this data to my existing table in another database. I solved this problem by parsing json. But I have more tables to copy. And I think there must be a better solution for this. Can someone help with this? -
AttributeError: 'NoneType' object has no attribute 'history_change_reason'
I am saving change history on every change in django model by using django-simple-history. that what I tried: class MyModel(models.models): field1 = .. ... history = HistoricalRecords( history_change_reason_field=models.TextField(null=True) ) name = 'xyz' for doc_id, status in my_data: reporting , _ = Reporting.objects.get_or_create( doc_id=doc_id, user=self.request.user ) reporting.is_accepted = status reporting.save( update_fields=['is_accepted] ) update_change_reason( instance=reporting, reason=f'Change request done by {name}' ) and I got below error. AttributeError: 'NoneType' object has no attribute 'history_change_reason' -
can someone explain me this django views part
def download(request , path): file_path = os.path.join(settings.MEDIA_ROOT , path) if os.path.exists(file_path): with open(file_path , 'rb') as file: response = hr(file.read(),content_type="application/admin_upload") response['Content-Disposition'] = 'inline;filename='+os.path.basename(file_path) return response raise Http404 i saw one on how to upload a img by the admin and the code works fine but i dont understand this part :/ -
How to login as an existing user in django shell
In django shell, I want to debug a specific api call, and for the resource to work, one should be logged in. from django.test import Client from urllib.parse import urlsplit, parse_qsl client = Client() client.login(username='my_username', password='my_password') # I also tried client.force_login() without success url_data = urlsplit(url) r = client.get(path=url_data.path, data=parse_qsl(url_data.query)) # r is <HttpUnauthorized status_code=401, "text/html; charset=utf-8"> How do I login properly? -
repeat watermark only once per page when printing the html page
I'm using pdfkit with Django to convert a html template into pdf. The template is 3 page long when printed and I need to display a "Cancelled" watermark on each page of the document when printed. Currently, it only gets printed once in the first page, but i need it to be printed at the center of the page, once on all the pages <style> #watermark { display:block; z-index: 99999; width: 86%; position:fixed; } #watermark img { opacity: 0.2; filter: alpha(opacity=15); } </style> <div id="watermark"> <img src="/media/images/policy_cancel.png" style=" width: 650px; height: 414px;"> </div>