Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango - Two Different Views from Different Apps into a single Template
Django beginner here. I am trying to make a an app for where users can make connections, post stuff, chat, etc. There are two user types - Parents and Child. For this I extended the AbstractBaseUser model and created two another models - Parent and Child with a OneToOne link to the User. #accounts/models.py class User(AbstractBaseUser, PermissionsMixin): REQUIRED_FIELDS = [] EMAIL_FIELD = "email" USERNAME_FIELD = 'email' objects = UserManager() email = models.EmailField(unique=True) first_name = models.CharField(max_length=DefaultModel.MAX_LENGTH, unique=False) last_name = models.CharField(max_length=DefaultModel.MAX_LENGTH, unique=False) profile_photo = models.ImageField(default='uploads/profile/default_profile.jpg', upload_to=content_image_name) cover_photo = models.ImageField(default='uploads/profile/default_cover.jpg', upload_to=content_image_name) username = AutoSlugField(populate_from='first_name', unique=True, sep='.') bio = models.CharField(max_length=255, blank=True, default="Nothing to see here !") is_child = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # storing timestamps for users. created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) CHOICES = (('M','Male'),('F','Female'),('O','Other')) gender = models.CharField(max_length=10, choices=CHOICES) def get_absolute_url(self): return "/users/{}".format(self.username) def __str__(self): return "{} {}".format(self.first_name, self.last_name) class Child(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) friends = models.ManyToManyField('self', blank=True, related_name='friends', db_column='friends',) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) connections = models.ManyToManyField('self', blank=True, related_name='connections', db_column='connections',) def __str__(self): return "{} {}".format(self.user.first_name, self.user.last_name) As you can see a Child can only be a friend with another Child and a Parent … -
How do you save Textarea form data line by line using Django's CreateView?
I have a Model and would like to save data as a batch by using a textarea form in Django. The data shall be save line by line, which I am using splitlines(), each data is comma separated by split(","). I am operating the manipulation in the form_valid() function but I can't seem to get it right. Only the last line is saved successfully. forms.py class DataForm(forms.ModelForm): textarea_data = forms.CharField(widget=forms.Textarea) class Meta: model = Item exclude = ('part_number','length','height','weight') views.py class InsertData(generic.CreateView): model = Item form_class = DataForm def get_success_url(self): return reverse('item_list') def form_valid(self, form): self.object = form.save(commit=False) textarea_data = form.cleaned_data['textarea_data '] data_line_list = textarea_data.splitlines() for each_line in data_line_list: each_line_list = each_line.split(",") self.object.part_number = each_line_list[0] self.object.length = each_line_list[1] self.object.weight = each_line_list[2] self.object.height = each_line_list[3] self.object.save() May I know where did I go wrong. Should the manipulation be done some where else? -
Add a new table row with HTMX
I am trying to add a new table row with Htmx. By clicking the "Add A New Row" button, a new row should be added to the table. I can't get the row in the secondary_hx.html to be added to the table, instead it results as three forms next to each other without or . Any help would be appreciated. Thank you in advance. My code is like this: main.html: <table id="myTable"> <thead> <tr> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody id="Tbody"> <tr> <td> <button class="add_button" type="submit" hx-post="/add_row/" hx-target="#Tbody" hx-swap="beforeend" > Add A New Row </button> </td> </tr> </tbody> </table> partials/secondary_hx.html: <tr hx-target="this" hx-swap="outerHTML"> <td>{{ form.a }}</td> <td>{{ form.b }}</td> <td>{{ form.c }}</td> </tr> -
Programming Error: No result found Previous SQL was not a query in Django
I'm sending post request to the SQL Stored Procedure where I couldn't able to pass in the SQL it showing as no result. Even I tried the same approach for another API and passing it to another Stored Procedure which worked well. Programming Error at /api/Data/StartShift/ No results. Previous SQL was not a query. views.py: Here "IP" is empty @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': UserId = request.POST.get('UserId') Ip = request.POST.get('Ip') PortNumber = request.POST.get('PortNumber') print("UserId-->", UserId) print("Ip-->", Ip) print('Portnumber-->', PortNumber) cursor = connection.cursor() cursor.execute('EXEC [dbo].[Usp_StartShift] @UserId=%s, @IP=%s, @Port=%s', (UserId, Ip, PortNumber,)) result_set = cursor.fetchall() response_data=[] for row in result_set: response_data.append( { "UserId":row[0], "Ip":row[1], 'PortNumber':row[2] } ) return Response(response_data, status=status.HTTP_200_OK) Here, is the Stored Procedure which I tried to access from Django SP: GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER Procedure [dbo].[Usp_StartShift] @UserId varchar(100), @IP nvarchar(255), @Port nvarchar(255) as begin insert into tblUserShiftDetails(UserId, IPAddress, PortNumber) values(@userid,@ip,'CD_'+@port) end -
TypeError: setQty is not a function. Can someone fit it. i cant solve that problem. Thanks beforehand
`<Form.Select as="select" value={qty} onChange={(e) => setQty(e.target.value)}> {[...Array(product.countInStock).keys()].map((x) => ( {x + 1}))} ` Here is the code... -
how do i get email delivery report(IP addresses (if more devices received email) ,message opened time, received time) python django [duplicate]
I have sent email to a test email address using smtp.EmailBackend python Django, how do i get email delivery report(IP addresses (if more devices received email) ,message opened time, received time) -
date filter in django template - isoformat
When I use this snippet in django template <td id="tdId_{{ i.0 }}4">{{i.4|date:'c'}}</td> it outputs 2021-12-01T08:34:54. I'm losing some information. In the database is 2021-12-01 08:34:54.000 How can I achieve the correct result in django template? -
escpos-python printing is working fine on local server but not working on live server
ESCPOS PYTHON ERROR, printing is working fine on local server but not working on live server. PLEASE HELP -
Validation error on nested writable serializer
I have a writable nested serializer like this - class AddressSerializer(serializers.ModelSerializer): class Meta: model = publicAddress fields = "__all__" class customerSerializer(serializers.ModelSerializer): publicAdd = AddressSerializer(many=True) class Meta: model = customerMaster fields = ['id','publicAdd'] def create(self, validated_data): Address = validated_data.pop('publicAdd') customer = customerMaster.objects.create(**validated_data) for addres in Address: publicAddress.objects.create(customer=customer, **addres) return customer this all works fine until I apply validation such as class AddressSerializer(serializers.ModelSerializer): class Meta: model = publicAddress fields = "__all__" validators = [ UniqueTogetherValidator( queryset=publicAddress.objects.all(), fields=['customer', 'someValue'] ) ] And defining read_only_fields = ('customer',) in AddressSerializer won't help either. Now it throws an error such as cust field is always required and to send the cust value via api. Any help on how to validate this without an error? -
How to filter forms in django?
I am trying to make a rating system with django. So, I have: class Region(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.name class Salesman(models.Model): region = models.ForeignKey(Region, related_name='region', on_delete=models.CASCADE) name = models.CharField(max_length=40) surname = models.CharField(max_length=40) def __str__(self): return self.name class Rating(models.Model): RATING_CHOICES = [(i, str(i)) for i in range(1,6)] salesman = models.ForeignKey(Salesman, related_name='salesman', on_delete=models.CASCADE) region = models.ForeignKey(Region, related_name='regions', on_delete=models.CASCADE) phone = models.CharField(max_length=15, blank=True) rating = models.IntegerField(choices=RATING_CHOICES, blank=False) sent_time = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.rating}" It is my model. In the first page user should select the region and then form should be opened with salesman, phone and rating fields. And salesman fields must show those salesmen who work in the selected region. My forms.py is here: class RateAddForm(ModelForm): class Meta: model = Rating exclude = ('region',) def __init__(self, region=None, **kwargs): super(RateAddForm, self).__init__(**kwargs) if region: self.fields['salesman'].queryset = Salesman.objects.filter(region=region) But still it shows me all salesmen regardless of their region. My views.py is here: def report_add(request): if request.method == 'POST': form = RateAddForm(request.POST) if form.is_valid(): message = "Thanks!" form.save() return HttpResponse(message) else: form = RateAddForm() else: form = RateAddForm(request.POST) return render(request, 'account/report.html', {'form': form}) Are there anything I missed or would you suggest any good method? Thanks in … -
django pagination for controller
How to add pagination here? @method_decorator(admin_decorator()) def post(self, request): try: controller = UserListController(data=request.data) return Response(status=status.HTTP_200_OK, data=controller.get_data()) except Exception as e: print(e) return Response({"message": "Internal Server Error"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
How to do updateview in django using ajax
models.py from django.db import models # Create your models here. class Login(models.Model): username=models.TextField(max_length=30) password=models.TextField(max_length=30) class CreateProduct(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=200) image = models.FileField(blank=True) def __str__(self): return self.title views.py from django.db import models from django.db.models import fields from django.shortcuts import redirect, render from django.views.generic import TemplateView,CreateView,FormView,ListView,DetailView from django.views.generic.edit import UpdateView from django.contrib.auth.models import User,auth from .models import CreateProduct from django.urls import reverse_lazy from django.shortcuts import get_object_or_404 # Create your views here. def home(request): return render(request,'index.html') def login(request): if request.method=="POST": username=request.POST['username'] password=request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('productslist') else: return redirect('/') else: return render(request, 'index.html') class ProductsList(ListView): model = CreateProduct context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = CreateProduct fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = CreateProduct.objects.all() context_object_name = 'products' model = CreateProduct class ProductsUpdate(UpdateView): model = CreateProduct fields = ['title','description','image'] template_name = "productsupdate.html" queryset = CreateProduct.objects.all() success_url=reverse_lazy('productsdetail') productdetail.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <!-- <title>Bootstrap Example</title> --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <!-- <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> --> <ul class="nav navbar-nav"> <li … -
How to get the name of the same file uploaded as Response when downloading in python Django
I uploaded and downloaded the file. I do not get the name of the file I uploaded when I downloaded it. I try to program in python Django, any solution to solve this. def mDownloadResume(request, userid): profile = UserProfile.objects.get(id=userid) ts = profile.up_auth_user_id print(ts) resumefilename = Resume.objects.get(rs_auth_user_id=ts) vs = resumefilename.rs_original_name us = resumefilename.rs_auth_user_id ts = resumefilename.rs_saved_name contentype = "application/pdf" filepath = os.path.join(BASE_DIR , "Resume", ts) if os.path.exists(filepath): with open(filepath, 'rb') as fh: response = HttpResponse(fh.read(), content_type=contentype) response['Content-Disposition'] = 'inline; filename=' +os.path.basename(filepath) \ return response raise Http404 -
Cant able to access the django application hosted on nginx in another system in same lan network (windows)
Not able to access the django application in another system which is hosted on nginx in window's machine under same lan network. getting "This site cant be reached" page. Please do needful -
Django redirect from form upload
From the page This page isn’t working. If the problem continues, contact the site owner. HTTP ERROR 405 From the terminal Method Not Allowed (POST): / Method Not Allowed: / [20/Dec/2021 22:00:27] "POST / HTTP/1.1" 405 0 How to redirect to the same page after page upload click. form.html->included in sidebar.html-> included in home.html <form method = "POST" action='.' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> views.py from django.shortcuts import render from .forms import UserProfileForm def index(request): print(request.POST) return render(request,'home.html') -
Validate a single field of Django model-form?
Actually I m working on Blood Donation And I have done almost each and everything but one thing is not working and it is in Form validation. Thanks in advance forms.py def clean_cnic(self): cnic = self.cleaned_data['cnic'] print("This is a cnic",cnic) if not User.objects.filter(cnic=cnic).exists(): return cnic existuser = User.objects.get(cnic = cnic) if existuser: previous_date = existuser.last_donation current_date = datetime.now().astimezone() print(previous_date,"-----_---",current_date) final = current_date - previous_date print("The final is -> ",final) if final < timedelta(days= 1): raise ValidationError("U have to wait 1 days to complete") return cnic def clean_blood_group(self): print("<--------This is blood_function------>") cnic = self.cleaned_data.get("cnic") blood_group = self.cleaned_data['blood_group'] print(blood_group) print("CNIC----->",cnic) obj = User.objects.get(cnic = cnic) print(obj.blood_group) if obj.blood_group == blood_group: print("I m here") return blood_group raise ValidationError("Blood group does not match") When I give blood group is correct it add data Ok and when I give wrong My raise validationError is not run. CNIC come from above validation ok its working perfectly Please tell me what's going on -
How to connect Salesforce database in django? Perform API calls using Python?
How to connect Salesforce database in django? Perform API calls using Python ? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'salesforce_db', }, 'salesforce': { 'ENGINE': 'salesforce.backend', "CONSUMER_KEY" : 'EDIT: your key you get.......................', "CONSUMER_SECRET" : 'EDIT secret you get', 'USER': 'EDIT your@user.login.name', 'PASSWORD': 'EDIT password + security_token', 'HOST': 'https://login.salesforce.com', } } SALESFORCE_QUERY_TIMEOUT= (4, 15) -
I am getting a error "invalid escape character in string.jsonc(261)" in settings .json
I tried adding interpreter path both manually and recommended, but it didn't create .vscode folder so I only created .vscode file and copy pasted settings.json please help me with this error. -
What should be the type of Image file in isinstance() arg 2?
def setUpTestData(cls): cls.point = PickUppoints.objects.create( img=File(file="b") ) def test_it_has_information_fields(self): self.assertIsInstance(self.point.img, Image) It gives "typeError: isinstance() arg 2 must be a type or tuple of types". What should I use in isinstance() arg 2? Isn't 'Image' a type of class? -
How to use python function in django rest api?
I'm building a data analysis function using Python, and somehow I need to make a restAPI of those function using Django. Since I'm new to the API and rest API world, I've learnt Django in this past week but still had no idea how to convert those python functions into Django-like codes. Here's a sample code function I've been working on: def filter_dataset(data, period): # filter dataset for XYZ Classification Function # copy the data first then change Date into datetime format data_copy = data.copy() data_copy['Date'] = pd.to_datetime(data_copy['Date'], dayfirst=True) data_copy['month'] = data_copy['Date'].dt.month # get the last 3 months data months = data_copy.month.unique() last_3_months = months[-3:] # filtering the data based on period choice if period == 'Last 3 Months': data_period = data_copy.loc[data_copy['month'].apply( lambda x: x in last_3_months)] else: data_period = data_copy data_period.drop(columns='month', inplace=True) return data_period The function above is used to filter data based on selected months period. I want to build a restAPI using django that work like this: Let say we get the data in json: [ { 'id': 1, 'product_code': 'Product_001', 'date' : '2017-05-29, 'demand': 200 }, { 'id': 2, 'product_code': 'Product_002', 'date' : '2017-05-29, 'demand': 150 }, ] And it will return the data like this: … -
How can I use MinimumLengthValidator?
enter image description here i am trying to build register api with builtin validators of django but whenever i try, it allows me directly in to success i dont know why it does not work can anybody help me out? Please Someone HELP ME! -
Apache can't load static files from a specific Django app
I have the following project: ``` 📦 project_name ┣ 📂app_name ┃ ┣ 📂migrations (truncated) ┃ ┣ 📂static ┃ ┃ ┣ 📂css ┃ ┃ ┃ ┗📜dashboard.css ┃ ┃ ┗ ┗📜password_reset.css ┃ ┣ 📂templates (truncated) ┃ ┃ ┗ 📂password_reset (truncated) ┃ ┣ 📂templatetags (truncated) ┃ ┣ 📜__init__.py ┃ ┣ 📜asgi.py ┃ ┣ 📜constants.py ┃ ┣ 📜forms.py ┃ ┣ 📜models.py ┃ ┣ 📜settings.py ┃ ┣ 📜urls.py ┃ ┣ 📜views.py ┃ ┗ 📜wsgi.py ┣ 📂media (truncated) ┣ 📂static ┃ ┣ 📂css ┃ ┃ ┗📜dropzone_style.css ┃ ┃ ┗📜login.css ┃ ┃ ┗📜password_reset_confirm.css ┃ ┣ 📂img ┃ ┃ ┗📜csv.png ┃ ┃ ┗📜excel.png ┃ ┣ 📂js ┃ ┃ ┗📜datatables.js ┃ ┃ ┗📜dropzone.js ┃ ┃ ┗📜sidebar.js ┃ ┗ 📜favicon.ico ┣ 📂staticfiles ┃ ┣ 📂admin (truncated) ┃ ┣ 📂css ┃ ┃ ┗📜dashboard.css ┃ ┃ ┗📜dropzone_style.css ┃ ┃ ┗📜login.css ┃ ┃ ┗📜sidebar.css ┃ ┃ ┗📜style.css ┃ ┣ 📂img (empty) ┃ ┣ 📂js ┃ ┃ ┗📜datatables.js ┃ ┃ ┗📜dropzone.js ┃ ┃ ┗📜index.js ┃ ┃ ┗📜sidebar.js ┣ 📂templates (truncated) ┣ 📜.gitignore ┣ 📜db.json ┣ 📜db.sqlite3 ┗ 📜manage.py ┗ 📜requirements.txt ``` I have 2 static folders: one in the root folder and one inside of the app folder. This is the error I am getting in the browser console: There are no errors in … -
Django Channels Change HTML/Javascript For Everyone
I want to make it so if a user disconnects from the websocket their status will change to "offline" for everyone that is viewing the user's profile page. I have successfully done so for detecting when users are online but using the same code for disconnecting doesn't work. How should I go about doing this? Here's the code for the Javascript activityWS.onmessage = function(event) { var parsedDict = JSON.parse(event['data']); profileUrl = window.location.origin + '/account/' + parsedDict['user'] + '/'; if (window.location.href == profileUrl) { $('.online-status').text('Online'); } } $(window).on('beforeunload', function(event) { // won't change to offline but online changing works if (window.location.href == profileUrl) { $('.online-status').text('Offline'); } }); -
Cannot log in to token endpoint with username/password: drf token auth and custom user model, Django
I have a basic Django app using Django rest framework, a custom user model inheriting from the default, and basic token authentication. I am able to generate a token for any user by running python3 ./manage.py drf_create_token {USERNAME/EMAIL} and authenticate relevant requests with it. However, when I attempt to hit my token endpoint (in this case http://127.0.0.1:8000/api/token/, or the equivalent for the deployed app), I get { "non_field_errors": [ "Unable to log in with provided credentials." ] } My request body (application/json) is like: { "username": "test@test.com", "password": "test" } I have ensured that the user is active; that the password is correct; and that the username is the same as the email. My custom user class: class Customer(AbstractUser): first_name = models.CharField(max_length=240) last_name = models.CharField(max_length=240) email = models.EmailField(unique=True) phone_number = PhoneNumberField(unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) is_active=models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["password", "phone_number", "first_name", "last_name", "username"] def __str__(self): return f"{self.first_name} {self.last_name}" relevant urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/users/', include('customer.urls')), path('api/token/', obtain_auth_token, name="auth_token"), ] in settings.py I have the following: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'phonenumber_field', 'customer', 'contact', 'rest_framework', 'rest_framework.authtoken', ] ... REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } ... … -
Django import existing Ppasswords from PHP site that used password_hash()
I need to import a list of users and hashed passwords from an old PHP site that used password_hash() to a new django site. The stored passwords look like this: $2y$10$ZnxKDPbqOfACnGmQeN76o.UtdwWBFBCCLTiGnvCSvl/zqIBeVxhai I found Django password hasher using php format of function password_hash() on here when trying to look this up, and I think that will help for the NEXT step. But currently I can't setup an import process that will correctly bring over the old passwords. When I try to manually create the users during the import process it refuses the password stating "Invalid password format or unknown hashing algorithm." when I look at the users after the import runs. I think I am just going about this totally incorrectly, here is an example snippet where I create the users. usertest = User(username='testguy',email='testguy@test.com',password='$2y$10$ZnxKDPbqOfACnGmQeN76o.UtdwWBFBCCLTiGnvCSvl/zqIBeVxhai') That results in no password being store. Using the create_user function results in the user being created but with that hashed password output as their password: User.objects.create_user(username='testguy',email='testguy@test.com',password='$2y$10$ZnxKDPbqOfACnGmQeN76o.UtdwWBFBCCLTiGnvCSvl/zqIBeVxhai') How can I just get these passwords stored properly in the new database so I can move onto the next step of actually checking against those passwords?