Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to annotate Django Queryset with the same value but with a different data type of one of existing fields?
I have a Django model that has a NumberVal field which is models.FloatField(). Then I need to annotate the queryset objects like so .annotate(numberval_as_text=str(OuterRef("NumberVal"))) - the same value, but as a string except for the fact that this throws QuerySet.annotate() received non-expression(s): OuterRef(NumberVal) error which is clearly right but it demonstrates the point. I need this because this annotation is followed by an extensive second annotation where I need this numberval_as_text in subquery filters. Any hint would be appreciated. -
Using pandas to load data into Django SQLite causes Exception Value: foreign key mismatch
Is there a reason that I can't place data in sqlite(SQL) using pandas in this situation for a Django model? I would like to use pandas to do some data cleanup and merging of data, then put it into SQL. Before doing the pandas I created my django model. models.py # myapp from django.db import models from django.contrib.auth.models import User class Agency(models.Model): system_name = models.CharField(max_length=255) county = models.CharField(max_length=60) active = models.BooleanField(default=True) system_type_tuple = [('ED', 'School'),('PG','Power Generation'),('TF','Some other Facility'),('UN','Unknown')] system_type = models.CharField(max_length=2, choices=system_type_tuple, default= 'UN') zipcode = models.CharField(max_length=5, null=True, blank=True) agency_no = models.CharField(max_length=7, primary_key=True, unique=True) def __str__(self): return self.agency_no class SitePart(models.Model): system_no = models.ForeignKey('Agency', on_delete=models.CASCADE, db_column='agency_no', null=True, blank=True,) part_name = models.CharField(max_length=125) status_tuple = [('AB','Abandoned'),('AC','Active Compliant'),('DS','Destroyed'),('NP','Need Permit'),('SB','Stand By waiting acitvation')] status = models.CharField(max_length=2, choices=status_tuple, default= 'SB') sys_site_n = models.CharField(max_length=15, unique=True) def __str__(self): return self.part_name To create the SQL database for the above model, I type into terminal the commands: python manage.py makemigrations myapp python manage.py migrate My pandas_script.py is like this: import pandas as pd import sqlite3 as sql import openpyxl import numpy as np conn = sql.connect('C:path_to/Django/my_project/db.sqlite3') support_dir = "C:/.../support/" file1 = support_dir + 'file1.xlsx' file2 = support_dir + 'file2.xlsx' df1 = pd.read_excel(open(file1, 'rb'), engine='openpyxl', sheet_name="Sheet1", usecols = 'A,B,D:G') df2 = … -
Django-Summernote editor not showing in Admin
I have a Django app for post-writing. I've integrated django-summernote to the app but I came across a issue that the django summernote widgets is not showing in admin panel. It is working fine and smooth in my template but its not showing in admin panel. Kindly help me out. settings.py INSTALLED_APPS += ('django_summernote', ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_CONFIG = { 'iframe': False, "jquery": "summernoteJQuery", 'summernote': { 'width': '100%' } } SUMMERNOTE_THEME = 'bs3' admin.py from django.contrib import admin from .models import Post, Comment from django_summernote.admin import SummernoteModelAdmin class PostAdmin(SummernoteModelAdmin): summernote_fields = ('text',) admin.site.register(Post,PostAdmin) admin.site.register(Comment) urls.py from django.urls import include # ... urlpatterns = [ ... path('summernote/', include('django_summernote.urls')), ... ] ... if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) screenshotAdminPanel -
image is not being uploaded on the website
i have made two identical functions to upload and image and second to upload an additional image. The first one works perfectly but imageSecond dosent work properly. When i upload image it works perfectly but when i upload imageSecond it dosent work properly please i am stuck here from a long time i really need some help. Also, I am using django for backend and react for frontend. Here is the Code: ProductEditScreen.js: const ProductEditScreen = ({ match, history }) => { const productId = match.params.id const [name, setName] = useState('') const [price, setPrice] = useState(0) const [image, setImage] = useState('') const [imageSecond, setImageSecond] = useState('') const [brand, setBrand] = useState('') const [category, setCategory] = useState('') const [countInStock, setCountInStock] = useState(0) const [description, setDescription] = useState('') const [uploading, setUploading] = useState(false) const dispatch = useDispatch() const productDetails = useSelector(state => state.productDetails) const { error, loading, product } = productDetails const productUpdate = useSelector(state => state.productUpdate) const { error: errorUpdate, loading: loadingUpdate, success: successUpdate } = productUpdate useEffect(() => { if(successUpdate){ dispatch({type: PRODUCT_UPDATE_RESET}) history.push('/admin/productlist') }else { if (!product.name || product._id !== Number(productId)) { dispatch(listProductDetails(productId)) } else{ setName(product.name) setPrice(product.price) setImage(product.image) setImageSecond(product.imageSecond) setBrand(product.brand) setCategory(product.category) setCountInStock(product.countInStock) setDescription(product.description) } } }, [dispatch, product, productId, history, … -
Skipping django serializer unique validation on update for the same row
I am using django serializer for validation. The code is listed below. The same code is used for validation checks on creation and updation. However, on the update, the unique validation check on certain fields should be skipped (eg: email). because on update the row will be used. from rest_framework import serializers from rest_framework.validators import UniqueValidator, UniqueTogetherValidator from dashboard.models import Users class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length=200, required=True, validators=[UniqueValidator(queryset=Users.objects.all())]) email = serializers.EmailField(validators=[UniqueValidator(queryset=Users.objects.all())]) def validate_username(self, value): if len(value) < 6: raise serializers.ValidationError('Username must have at least 3 characters') return value def validate_email(self, value): if len(value) < 3: raise serializers.ValidationError('Username must have at least 3 characters') return value def validate(self, data): return data Here, I am using the UniqueValidator, it should be skipped for the update validation check, except for the same row. -
Filtering through date range not working in django rest framework
I am trying to count the total orders made by customers in the last week. I have used ordered_date__range in my view but my API is showing count as zero. I am not sure what is the issue here because I know there are orders made in my db. My view: class DashboardView(ListAPIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): count_1 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk']).count() ...................... startdate = datetime.today() + timedelta(days=1) enddate = startdate - timedelta(days=30) count_8 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'],ordered_date__range=[startdate, enddate]).count() return Response( {'active_users_now': count_2, 'total_customers': count_9, 'total_orders': count_1, 'total_categories': count_3, 'total_subcategories' : count_6, 'total_products_available': count_4, 'total_prodcuts_sold': count_5, 'total_earnings': count_7, 'total_orders_of_the_week': count_8, }, status=status.HTTP_200_OK) Here If I call the above api, my count is showing zero. I just tried adding 2 or 3 orders, but still getting zero counts. I tried removing this part order_items__item__merchant=self.kwargs['pk'], as well, but its the same result of zero. COunt_1 is totally working. I am just trying to capture of orders made by customers of a particular merchant within the last week. My model: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) #order_items = models.ManyToManyField('OrderItem',blank=True, null=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) -
Let's Encrypt Certbot and Gunicorn
Certbot has this section in the beginning where I have to specify "My HTTP website is running **(web server) on **(system it's running on )" I use Google Domain for my domain and heroku to deploy. I'm using Django. After a bit of research I found out that my website is runing on a gunicorn webserver. In this case, which one should I select on the Software? They have Apache, Nginx, Haproxy, Plesk, Web hosting product, none of the above. Also How can I find out which system my webdite is runing on? Thank you in advance. Any advice is appreciated. I'm aware that if I upgrade my heroku to a padiu version it's easier but I want to do it for free. I got my account verrified. -
Why my django server is not down for seconds after adding changes? Before server used to stop for a while after adding changes
Before when I did some changes in my django files views.py or admin.y file in django, after refreshing browser server for 1-2 seconds is down and then starts working, but I don't know what changed now, when I add change to admin.py or other django files server is not stopping by itself automatically. It keeps running even if I add inappropriate syntax to the django files. After re-running server django detects changes. Why this happens? Before django could detect changes in its files without re-running but now I have to re-run server to see changes I am using PyCharm (latest version) Ubuntu 19.04 Chrome Python 3.7 Django 3.2.3 -
How to set a permanent value to a Django Form Field
I am building blogsite where authenticated user can add post. The form has three fields including 'user' field (which shows all the user list with a drop down option). The problem is authenticated user can also see other user name. I have tried two solution Exclude this field when rendering in template or whatever the username is chosen the post post will be saved by the name of authenticated user but the solution I want 'user' field will only show the name of authenticated user and that will be submitted with title and description class BlogForm(forms.ModelForm): class Meta: model = Blog fields = '__all__' ''' view function if fm.is_valid(): us = fm.cleaned_data['user'] ti = fm.cleaned_data['title'] ds = fm.cleaned_data['desc'] post = Blog(user=us, title=ti, desc=ds) messages.success(request, 'Blog Created') post.save() -
NoReverseMatch at /cart/ Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name
Error NoReverseMatch at /cart/ Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name. Error Screenshot This is where it shows me error, when I try to add a product to cart sessions,tho the product it added to cart sessions but when the url for cart-details is called, while loading the main base.html file it gives me a error that productView cannot be found ProductApp Templates 'app/base.html' <!doctype html> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <base href="/"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800&display=swap" type="text/css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,400i,700,700i&display=swap" type="text/css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700&display=swap" type="text/css"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <!-- <link rel="stylesheet" href="{% static 'app/css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'app/css/animate.css' %}"> --> <!--Owl Carousel CSS--> <link rel="stylesheet" href="{% static 'app/css/owl.theme.default.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/magnific-popup.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/aos.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/ionicons.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/bootstrap-datepicker.css' %}" type="text/css"> <link rel="stylesheet" href="{% … -
I am able to get else part of the code, Else part is not working
I am working on this code of logging in to the application. I can see that only if statement is working in this code for the valid values of username and password. If i enter the invalid values of username and password the else part should work, But it's not working. **main.py** @app.post("/loginsuccess/", response_class=HTMLResponse) async def login_success(request: Request, username: str = Form(...), password: str = Form(...)): p = await User_Pydantic.from_tortoise_orm(await User.get(username=username, password=password)) if p is not None: json_compatible_item_data = jsonable_encoder(p) print(json_compatible_item_data["username"], "22222222222222222") return templates.TemplateResponse("homepage.html", {"request": request, "username":username}) else: print("NOOOOOOOOOOOOOOOOO") status_code:int status_code = 500 return templates.TemplateResponse("index.html", {"request":request, "status_code":status_code}) -
Can anyone please explain what error is this, OSError [Errno 22] Invalid argument
I'm getting this error and I don't know how to solve it, i think this is related to templates directory. this is how my templates are stored My view -
Why am I not POSTing data to database Django/Python
I am unable to get the data to my database am I missing something. Followed a couple tutorials, tried my own tweaking but no luck thus far. I m not getting any errors but when I click submit on the form my database is not populating. My View def createUser(request): # form = UserForm() args = {} if request.method=='POST': userform = UserForm(request.POST) petform = PetForm(request.POST) if userform.is_valid() and petform.is_valid(): newuser = userform.save() newpet = petform.save(False) newpet.newuser = newuser newpet.save() return render(request, 'pet_list.html' ) else: userform = UserForm() petform = PetForm() args.update(csrf(request)) args['userform'] = userform args['petform'] = petform return render(request, 'add_user_pet.html', args) My Template <form action="/ " method="POST" > {% csrf_token %} <h3 class="details">User Info</h3> {{userform}} <h3 class="details">Pet Info</h3> {{petform}} <input type="submit"/> </form> Form.py class UserForm(forms.ModelForm): name = NameField() email = forms.CharField(label='E-mail',widget=forms.TextInput(attrs={"placeholder":"Whats your email"})) class Meta: model = User fields = ['name', 'email'] ################################################# class PetForm(forms.ModelForm): class Meta: model = Pet fields = [ 'name', 'submitter', 'species', 'breed', 'description', 'sex', 'age' ] -
Can we change invoice number when date change django
Please help me i am stuck in a problem if we have invoice number and we need to change according to financial year which is 1 april so can we change invoice no. Year for example - now is 2021 so invoive no. Is -- 210001 if it's 2022 invoice is 220001 so it is possible or not ??? -
How can I get String in Django model field and make sure if it is unique
This question already has answers here: How to create a GUID/UUID in Python (8 answers) Your post has been associated with a similar question. If this question doesn’t resolve your question, ask a new one. Closed 8 mins ago. (Private feedback for you) I am generating a string using below technique but one thing I just want be sure of is that uniqueness of the string. will be a great help if anybody evaluate and suggest if there is a better way of getting a unique string. models.py import random import string def random_string_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(13)) class Orders(models.Model): id= models.AutoField(primary_key=True) token = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) identifier = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) -
How to check and keep checkboxes checked when others are unchecked
I have check boxes that when I check 3of them for example and then I uncheck 1, an attribute works in the opposiste. With this I mean that Because I have a default hidden button that appears when I check a checkbox, when I hav e 3 of the checkboxes checked and I uncheck 1, the button is hidden where as 2 checkboxes are still checked meaning that the button should be unhidden. How would I correct this???? <script> $(document).ready(function() { $('#select-all').click(function() { var checked = this.checked; $('input[type="checkbox"]').each(function() { this.checked = checked; }); }) }); //Add a JQuery click event handler onto our checkbox. $('input[type="checkbox"]').click(function(){ //If the checkbox is checked. if($(this).is(':checked')){ //Enable the submit button. $('#delete_all').attr("hidden", false); } else{ //If it is not checked, hide the button. $('#delete_all').attr("hidden", true); } }); </script> <form method="post" action="{% url 'delete_students' %}"> {% csrf_token %} <table class="layout container"> <thead> <th><input type="checkbox" id="select-all"></th> </thead> <tr> <td> <input type="checkbox" name="marked_delete" value="{{ student.pk }}"> </td> </table> <button class="btn btn-dark" id="delete_all" hidden="hidden">Delete Selected</button> </form> -
How to check type is timestamp in dictionary?
{ "request_emp": { "id": 2 }, "overtime_date": "2021-05-26", "mail_body": "werr", "mail_status": 0, "mail_subject": "er", "request_start_datetime": "2021-05-26T00:00:00Z", "request_end_datetime": "2021-05-26T00:00:00Z", "request_total_datetime": null, "actual_start_datetime": null, "actual_end_datetime": null, "actual_total_datetime": null, "del_flag": 0 } how to check attribute which has datetime type value in above dict? -
How to show map in website GIS shape file map data in to my website?
Here, I'm trying to show GIS map on my website. I'm using GIS dataset from https://opendatanepal.com/dataset/nepal-municipalities-wise-geographic-data-shp-geojson-topojson-kml and I have the following files in zipped dataset: local_unit.dbf local_unit.xml local_unit.shx local_unit.prj local_unit.sbn local_unit.sbx local_unit.shp I have problem of using this file in my Django/Python website. I'm trying to use jquery library with ArcGIS from this: https://developers.arcgis.com/javascript/3/jssamples/framework_jquery.html. I don't know this is the way or not to embed map in website. Please suggest how can I use GIS map in website. -
How to display django forms in a table format?
I have the following in my Models.py class Accounts(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) .... is_assigned = False class Section(models.Model): name = models.CharField(max_length=150) .... is_assigned = False is_teacher = False class Assignment(models.Model): teacher = models.ForeignKey( Accounts, on_delete=models.CASCADE, limit_choices_to={'is_teacher': True, 'is_assigned': False} ) section = models.ForeignKey( section, on_delete=models.CASCADE, limit_choices_to={'is_assigned': False} ) Now I'm trying to assign a teacher to a section and I'm using BSModalModelForm in my forms.py but as I'm writing my code I'm starting to get lost. How can I display my form in this format? Note: All teachers that are not assigned are displayed in the table. Thank you for answering! -
How can I check the file names through python a script in python?
I am using python scripts to save web scraped data to CSV files. The name of CSV files is dynamic, like fl_todays_date.csv where today's date is the date derived from the web scraped site. After saving the data in a CSV file, I then import the CSV data into my Django models, all through the script. But the problem I'm facing is, How can I check whether the data from yesterday's file is already present in the database before importing today's data. My file structure is as follows: csv_files fl_some_pervious.csv fl_yesterday.csv fl_today.csv script scrape.py db_upload.py -
Getting KeyError: 'first name' in django serializers.py
I am stuck for a long time here. I am getting a KeyError for first name, but if I remove it then the code works. I am also using React for my front-end and its just getting messier. serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first name', 'last name', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first name', 'last name', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['first name'], validated_data['last name'], validated_data['username'], validated_data['email'], validated_data['password']) # user.save() return user # Login Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") Logs: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 26, 2021 - 08:36:27 Django version 3.1.7, using settings 'leadmanager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [26/May/2021 08:36:33] "GET / HTTP/1.1" 200 1009 [26/May/2021 08:36:33] "GET /static/frontend/main.js HTTP/1.1" 200 231194 Unauthorized: /api/auth/user [26/May/2021 08:36:33] "GET /api/auth/user HTTP/1.1" 401 58 Not Found: … -
Getting 'GET /static/css/base.css HTTP/1.1" 404 1795' error for static files
I have no idea what I'm doing wrong. I have STATIC_URL = '/static/' STATICFILES_DIR = [str(BASE_DIR.joinpath('static'))] under my settings.py. Here is an image to my current file structure https://pasteboard.co/K3uhtSN.png I linked with <link rel="stylesheet" href="{% static 'css/base.css' %}"> in base.html and loaded at the very top using {% load static %} Thank you -
How to Generate a Unique String in Django?
I am generating a string using below technique but one thing I just want be sure of is that uniqueness of the string. will be a great help if anybody evaluate and suggest if there is a better way of getting a unique string. models.py import random import string def random_string_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(13)) class Orders(models.Model): id= models.AutoField(primary_key=True) token = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) identifier = models.CharField(max_length=13, default=random_string_generator, editable=False, unique=True) -
OuterRef is compatible with UUID Django
I have the following query where the primary key of the products model is a UUID and when I use OuterRef in the query it throws me the following message: ValidationError at /api/v1/productstodist/ ["'0' it is not a valid UUID."] OuterRef does not support uuid? the following is the query that I am trying to perform between two models: queryset = queryset.filter(~Q(provider = provider)).annotate( sellproductprices=Subquery( prefetch_qr.filter(product=OuterRef('pk')) .values('id_sell_price') .annotate(count=Count('pk')) .values('count') ) ).filter( sellproductprices__gt=0 ).prefetch_related( prefetch ) -
Incorrect padding error in putting SECRET_KEY in .env file
When I'm using SECRET_KEY value in settings.py, the Django application is working fine but as soon as I put the value in .env file and stating SECRET_KEY = config('SECRET_KEY') in settings.py, it is giving padding error. Case in which I put SECRET_KEY value directly in settings.py is working fine.settings.py Using .env file giving padding error. Error Screenshot:-Padding Error Please help me out.