Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble with my Wiki Search Bar - Can't get the search to work properly
I am creating a Wiki page and I can't get my search bar to function properly. When I try to search for "python" or "django" for example I am taken to a page with the address "http://127.0.0.1:8000/search/". It looks exactly like my home page but does not have any of my Headings. Here is my urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("search/", views.search, name="search"), path("wiki/<str:title>", views.title, name="title"), path("edit/<str:title>", views.edit, name="edit"), ] In views.py here is my search request: def search(request): search_key = request.POST.get("q", "") entries = util.list_entries() exists = search_key in entries if exists: return redirect('title', title=search_key) filtered_entries = [entry for entry in entries if not entry.find(search_key) == -1] return render(request, "encyclopedia/index.html", { "entries": filtered_entries }) -
Django: use related_name to create a subclass
How can I be able to use related_name to create a child model when the parent model is being created. class Parent(models.Model): name = models.TextField() child = models.ForeignKey(Child, on_delete=models.SET_NULL, related_name="parent_child", null=True, blank=True) def save(self, *args, **kwargs): self.child.parent_child.create(name="I am a child") class Child(models.Model): name = models.CharField() Currently, on save, I get a NoneType error: 'NoneType' object has no attribute 'parent_child' -
How to set required fields in PATCH API in Swagger UI
I'm using drf-spectacular and here's code in settings.py SPECTACULAR_SETTINGS = { 'TITLE': 'TITLE', 'VERSION': '1.0.0', 'SCHEMA_PATH_PREFIX_TRIM': True, 'PREPROCESSING_HOOKS': ["custom.url_remover.preprocessing_filter_spec"], } in serializers.py class ChangePasswordSerilaizer(serializers.Serializer): current_password = serializers.CharField(write_only=True, min_length=8, required=True) new_password = serializers.CharField(write_only=True, min_length=8, required=True) confirm_new_password = serializers.CharField(write_only=True, min_length=8, required=True) but still fields in request body are showing not required -
How to use credentials obtained from google with google API
Libs: dj-rest-auth + allauth I. I'm trying to interact with google API with credentials that I use to obtain internal access token. I managed to obtain both code and token but can't find how to use them with google API. The last page I found inapplicable is https://github.com/googleapis/google-api-python-client/blob/main/docs/oauth.md but probably I'm missing some things. Here's the view I'm trying to use google API in: class CreateGoogleDoc(GenericAPIView): ... def get(self, request): token = request.query_params['token'] module_dir = os.path.dirname(__file__) # get current directory file_path = os.path.join(module_dir, 'client_secret.json') flow = Flow.from_client_secrets_file( file_path, scopes=SCOPES, redirect_uri='https://example.com' ) credentials = service_account.Credentials.from_service_account_file(file_path, scopes=SCOPES) service = build('docs', 'v1', credentials=credentials) document = service.documents().create().execute() return Response([document['documentId']]) II. While I tried to swap code to internal access token class I got another error: Error retrieving access token: `{ "error": "invalid_request", "error_description": "You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure. You can let the app developer know that this app doesn't comply with one or more Google validation rules."}` Here's a view that I'm using for swapping: GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = 'http://localhist:8000/dj-rest-auth/google/' client_class = OAuth2Client Thanks! -
Can't save modelform with Choices Field
I've got the following model: class Unit(models.Model): TYPE_CHOICES = ( ("1", "Strecke"), ("2", "Zeit"), ("3", "anderes") ) symbol = models.CharField(max_length=50) name = models.CharField(max_length=500) factor = models.FloatField() base_unit = models.ForeignKey("self", blank=True, null=True, on_delete=models.CASCADE) type = models.IntegerField(choices=TYPE_CHOICES, default=3) Using a simple ModelForm: class UnitForm(forms.ModelForm): class Meta: model = models.Unit fields = '__all__' After running form.is_valid() I get the error: "Please choose a valid choice. 2 is not a valid choice". What am I missing here, isn't 1, 2 or 3 exactly the value I need to save the form, because those are the expected values from the type-field of the model to be saved in the database? -
how to use script_fields with django-elasticsearch-dsl
I'm trying to add a scripted field to my query from django-elasticsearch-dsl I've tried to add a test field like this: result = TwitterTweetDocument.search().script_fields(test="doc['sentiment'].value + 10") for hit in result: print(hit.to_dict()) but it returns 10 empty dictionary and if I try it without adding "script_fields": result = TwitterTweetDocument.search() for hit in result: print(hit.to_dict()) it returns 10 dictionary filled with my model instance data. can you please tell me what is the problem and how can i fix it? -
How do i upload multiple image file into single models using Django rest framework?
I am stuck to upload a multiple image file at duration of creating doctor model .. I think to implement multiple upload, you need to set the additional field for uploading in the DoctorSerializer. I want to upload multiple images for each student using django rest framework. currently, Im only able to upload one image for each student, but I want to be able to upload multiple images for each doctor in uploads folder in a directory of their name. Im building a facial attendance recognition system and I need multiple images of each student. here is my models.py file. Models.py class Doctor(models.Model): def get_upload_path(instance, filename): return 'documents/{0}/{1}'.format(instance.name, filename) mobile_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Up to 15 digits allowed.") name = models.CharField(max_length=255, blank=False, null=False) mobile = models.CharField(validators=[mobile_regex], max_length=15) email = models.EmailField(max_length=255, blank=False, null=False) picture = models.ImageField(upload_to="images/", blank=True, null=True) document = models.FileField(upload_to=get_upload_path, null=True, blank=True) and Here is my serializers.py class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = ['id','name','email','mobile' ,'document',] def create(self, validated_data): return Doctor.objects.create(**validated_data) and my views.py file... class CreateDoctorAPIView(APIView): parser_classes = (MultiPartParser, ) def post(self,request,*args): try: files = request.FILES['document'] print(files) serializer = DoctorSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({ 'message': 'Doctor created successfully', }) else: return Response({ 'message':'something wrong' }) except Exception … -
How to save a User as an attribute of a model Django
I am trying to create a Mail function as part of my website, I would like to save the receiving User instead of the receiving User's username in the receiver part of the Mail class, so I don't have to filter the User. This is what I did: class Mail(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.ForeignKey(User, on_delete=models.CASCADE, choices=[(u.username, u) for u in User.objects.all()]) title = models.CharField(max_length=50) content = models.TextField() django is giving me this error ERRORS: mail.Mail.sender: (fields.E304) Reverse accessor for 'mail.Mail.sender' clashes with reverse accessor for 'mail.Mail.receiver'. HINT: Add or change a related_name argument to the definition for 'mail.Mail.sender' or 'mail.Mail.receiver'. mail.Mail.receiver: (fields.E304) Reverse accessor for 'mail.Mail.receiver' clashes with reverse accessor for 'mail.Mail.sender'. HINT: Add or change a related_name argument to the definition for 'mail.Mail.receiver' or 'mail.Mail.sender'. -
Reportlab alignment & width issues
I’m having some issues with reportlab and writing a PDF. When the PDF is written it only consumes a little less than 2/3 of the page width (letter). The heading, for example, wraps and never makes it past the halfway point of the document. I’m at a loss for how to get my tables and paragraph to use the full width of the page. Any insight is greatly appreciated. Thank you in advance. import io import os from django.core.files.base import ContentFile from jsignature.utils import draw_signature from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_RIGHT, TA_CENTER, TA_LEFT from reportlab.lib.units import inch from reportlab.pdfgen import canvas from reportlab.platypus import SimpleDocTemplate, Paragraph, Table from PIL import Image # create pdf with table and paragraphs def create_pdf(participant): # create a file-like buffer to receive PDF data buffer = io.BytesIO() # define styles styles = getSampleStyleSheet() style_general = ParagraphStyle( name='left', parent=styles['Normal'], fontSize=12, fontName='Helvetica', alignment=TA_LEFT) style_image = ParagraphStyle( name='left', fontSize=30, parent=styles['Normal'], alignment=TA_LEFT) style_heading = ParagraphStyle( name='center', fontSize=18, fontName='Helvetica-Bold', parent=styles['Heading1'], leading=18, alignment=TA_CENTER) # create a simple document with page size in buffer doc = SimpleDocTemplate(buffer, pagesize=letter, author='Me') # create a list of paragraphs AllParagraphs = [] # convert png image to jpeg jpeg_image … -
How to set the value of model fields in Django in a loop
I want to set the values of the fields of a set of models in a loop. I need to do that because I have data in xml format (one xml file for each record, approx 500,000 file alltogether) that I need to import into a database. I can retreive the models of my app using app_models = apps.get_app_config('ctmatcher').get_models() I can retrieve the fields of each model by using fields=model._meta.get_fields() But how can I set the content of individual fields? If you would use the explict name of the model you would do address_object=Address.objects.create( city=address_info['city'], state=address_info['state'], zip=address_info['zip'], country=address_info['country'], facility_id=facility_id ) But how can I generate the address_object, if I only have the model object and the field objects in an immutable list ? -
Issues with Django automatically filtering template tags from database
Currently I'm putting together a deliberately vulnerable vm network for a training environment to do an exploitation and follow-on patch objective for my team. One of the vulnerabilities I'm looking to demonstrate is Server Side Template Injection via (django/jinja2) on a simple "blog" page with absolutely no filter on user input. The intake is working perfectly and storing in the sqlite db with no issues looking exactly as expected, however the problem is displaying this unsanitized user input. In fact, even while actively trying to force django to not escape or filter it continues to only display the plaintext entered by the user rather than interpret it as template tagging properly. The Rendered Output: The Template Itself: The data stored in the sqlite db: And finally the views.py rendering it: For reference I am using Python version 3.9.10, and Django version 4.0.6. Is there a way to force the behavior I'm looking for or will I have to go in search of an older version without these protections and start over on the backend work? -
Need to connect multibiometric system to my django project
I have a quiz project in Django and I want to include multi biometric system in to it for Real time update . Bio metric systems are connected in different local Ip address . -
Overriding/capturing user save and login action
This is my first time working with django. I am using django.contrib.auth (django version 3.2) There are 2 events that I want to capture. when user is activated when user has logged in The reason I want to capture these events is that I want to send out an email. I have gone through the documentation but not quite sure how to do this. One thing that comes to my mind is to override the save() method, to see when user's is_active flag has changes. I have tried the following override class for a different model, which works fine... however since user is a built-in class I don't know where to put the following override? def save(self, *args, **kwargs): super().save(*args, **kwargs) # send email Also not sure where would be the best place to add my custom code when user has logged in. -
MYSQL query equivalent in django
I have a django project with 2 models called wca and identifiers, I am wanting to update a field called 'secid' within identifiers model pulled from the equivalent field in wca model where code from identifiers model matches isin field in wca model. I have the working sql code for this but would like to convert into django equivalent for best practice. My sql query is as follows: UPDATE portfolio_identifier left outer join product_wca on portfolio_identifier.code = product_wca.isin SET portfolio_identifier.SecID = case when product_wca.secid is not null then product_wca.secid else 0 end WHERE code_type = 'ISIN'; I'd be grateful for any help on this. Thanks -
EcomUser() got an unexpected keyword argument 'mobile_number'
I'm trying to create a user and link it with the user profile. But here is the problem. This is my profile model class EcomUser(BaseModelMixin): profile = models.OneToOneField( settings.AUTH_USER_MODEL, unique=True, blank=True, null=True, on_delete=models.CASCADE) username = models.CharField(max_length=100, blank=True) email = models.CharField(max_length=100, blank=True, null=True) name = models.CharField(max_length=100, blank=True) referral_code = models.CharField(max_length=10, blank=True) signinId = models.CharField(max_length=20, blank=True) GOOGLE = 'GOOGLE' APPLE = 'APPLE' MOBILE_NUMBER = 'mobile_number' LOGIN_TYPES = ( (GOOGLE, 'GOOGLE'), (APPLE, 'APPLE'), (MOBILE_NUMBER, 'mobile_number') ) loginType = models.CharField(max_length=15, choices=LOGIN_TYPES, default=MOBILE_NUMBER) class Meta: db_table = "ecom_user" My user model: class User(AbstractBaseUser, BaseModelMixin): email = models.EmailField( verbose_name='email_address', max_length=255, blank=True, null=True ) username = models.CharField(max_length=128, null=True,unique=True) fullName = models.CharField(max_length=256, blank=True) mobile_number = models.CharField(max_length=15, blank=True,unique=True) is_superuser = models.BooleanField(default=False) class Meta: db_table = "users" USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] # Email & Password are required by default. def get_full_name(self): # The user is identified by their email address return self.fullName def __str__(self): # __unicode__ on Python 2 return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True objects = UserManager() and serializer.py class UserRegisterSerializer(serializers.Serializer): … -
django how to insert current userid using raw sql queries
I have to use a complex stored procedure that I have to use raw sql to achieve this. How can I insert also the current user userid similar to class_based_view createview something like this instance.recorded_by = ClearanceCustomuser.objects.get(userid=self.request.user.userid) to my def add(request): if request.method == "POST": if request.POST.get('office_id') and request.POST.get('sem') and request.POST.get('sy') and request.POST.get('incident_details') and request.POST.get('resolution') and request.POST.get('studid'): saverec = Clearanceinsert() saverec.office_id = request.POST.get('office_id') saverec.sem = request.POST.get('sem') saverec.sy = request.POST.get('sy') saverec.remarks = request.POST.get('incident_details') saverec.resolution = request.POST.get('resolution') saverec.studid = request.POST.get('studid') cursor = connection.cursor() cursor.execute("select add_clearance_item ('"+saverec.office_id+"', '"+saverec.sem+"', '"+saverec.sy+"', '"+saverec.remarks+"', '"+saverec.resolution+"', '"+saverec.studid+"')") return render(request, 'clearance/index.html') else: return render(request, 'clearance/add.html') hope someone can help -
Cannot read properties of undefined (reading 'map') in react js with django backend
I want to get my product's image of category 'Jeans' from django using DRF into my react frontend. Product Model looks like:(some fields are omited for simplicity) class Product(models.Model): product_image = models.ImageField(upload_to='product_image', blank = True) Serializer looks like: class ProductSerializer(serializers.ModelSerializer): class Meta: model= Product fields = ['product_image',] View Looks like class ProductView(APIView): permission_classes = [IsAuthenticated] def get(self, request): Jeans = Product.objects.filter(category='Jeans') serializer = ProductSerializer(Jeans, many=True ) return Response(serializer.data, status=status.HTTP_200_OK) then using RTK API query, hooks are generated for GET Request and I get response (in Postman) like: [ { "product_image": "/media/product_image/jeans1_bsV3Jdg.jpg" }, { "product_image": "/media/product_image/jeans2_76nciTn.jpg" }, { "product_image": "/media/product_image/jeans3_SlMg4rG.jpg" } ] But when I write code in React like this import React, {useState, useEffect } from 'react' import { useGetLoggedUserProfileDataQuery, useGetProductDataQuery } from './services/UserAuthApi' import { getToken, removeToken } from './services/LocalStorageService'; const Product = () => { const {access_token} = getToken() const productimage = useGetProductDataQuery(access_token) return ( <> { productimage.data.map((img)=>{ <h1>{img.product_image}</h1> }) } </> ) } export default Product I got the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'map') also on doing consolo.log(product_image), I got in console like this: {status: 'fulfilled', endpointName: 'getProductData', requestId: 'oUVEcITKdMPJtGZ-Pod9P', originalArgs: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90e…I6MX0.9K9THmN--5WnBQX0i5n5XUXUb9bqqslRCqf7A2Smyj4', startedTimeStamp: 1659459361351, …} currentData: (3) [{…}, {…}, {…}] data: … -
How to set cache lifetime of static files in Django using Whitenoise, gunicorn and Heroku
I successfully deployed my app and served the static files with Whitenoise on Heroku. I would like to extend their chache life time from the default (as it seems) of 4 hours to another lenght of time. I looked at the documentation and whitenoise basically says that all static files with content hash in their filenames have their cache set to forever. The Django documentation says that by using ManifestStaticFilesStorage static files are also saved in the exact format whitenoise is using However, when I check the cache lifetime of my statics, they stay at 4 hours. What am I missing? -
Creating a cashier control for stores
I'm in need of a way, but before asking for help, I'll explain my situation: I've been a programming student since the beginning of the year (still New), I've already learned HTML, CSS, JS, Python and now I'm looking at Django. Now comes the problem I want to solve, but I still don't have an idea of how. Well, my father he owns a cafeteria, I want to help by creating a cash flow system, creating an inventory, sales system, monthly profit, expenses and etc; this will make his life easier and help me, as I will be building my portfolio. I was thinking of using Django to help me and using Python to do the logic (Along with, of course, HTML and CSS). However, while I was making/studying the way I will make this system, I came across that I could do this as an .exe file. (If I were to continue with that thought of mine, my father would have to be accessing a site on localhost all the time) That way it will be easier for my dad to use, I just don't know how I can proceed from here, can I use Django? How do I … -
How much HTML/CSS knowledge is required for Flask/Django in Python?
I want to learn Flask or Django. But I think I need some HTML/CSS knowledge to code Flask/Django easily. The problem is that I do not want to learn HTML/CSS at all. I have searched for it a little and as far as I saw from the people who can code Django/Flask say you need to learn HTML/CSS to code Django/Flask. But some other people who can code Django/Flask say you do not need to learn HTML/CSS at all. That's why I am confused a lot. I'm really uncertain if I need to learn HTML and CSS or not. What should I do at this point? -
Django: How to fix <Response [403]> when using django send_mail() function?
I am trying to send a news letter broadcast email, i am getting all the email lists successfully from the db but the error seems to pointing to django send_mail() or is there something else that i am missing? def(...): ... emails = NewsLetter.objects.all() df = read_frame(emails, fieldnames=['email']) mail_list = df['email'].values.tolist() print(mail_list) if request.method == 'POST': form = MailMessageForm(request.POST) if form.is_valid(): form.save() title = form.cleaned_data.get('title') message = form.cleaned_data.get('message') send_mail( title, message, '', mail_list, fail_silently=False, ) messages.success(request, 'Message has been sent to the Mail List') return redirect('mail-letter') else: form = MailMessageForm() template <form method="POST"> {% csrf_token %} <input required id="full_name" name="title" type="text" placeholder="Subject"> <textarea required id="message" name="message" placeholder="Body"></textarea> <button class="submit-btn def-btn w-100" type="submit">Submit</button> </form> -
Assertion error parsing response to POST request from DRF viewset with DRF APIClient in tests
I've run into a strange issue with Django Rest Framework testing engine. The weird thing is that everything used to work fine with Django 3 and this issue turned up after I migrated to Django 4. Apart from testing, everything works well, and responds to queries as expected. The problem I'm using DRF APIClient to make queries for unit tests. While GET requests perform predictably, I fail to make POST requests work. Here is some minimalistic example code I created to figure out the issue. The versions I'm using: Python 3.9 Django==4.0.3 djangorestframework==3.13.1 from django.db import models from django.urls import include, path from django.utils import timezone from rest_framework import routers, serializers, viewsets router = routers.DefaultRouter() # models.py class SomeThing(models.Model): created_at = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=100, null=True, blank=True) # serializers.py class SomeThingSerializer(serializers.ModelSerializer): class Meta: fields = "__all__" model = SomeThing # views.py class SomeThingViewSet(viewsets.ModelViewSet): queryset = SomeThing.objects.all().order_by('id') serializer_class = SomeThingSerializer # urls.py router.register("some-things", SomeThingViewSet, basename="some_thing") app_name = 'question' urlpatterns = ( path('', include(router.urls)), ) Here is my test case: import json from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.test import APITestCase, APIClient class TestUserView(APITestCase): self.some_user = get_user_model().objects.create(login="some_user@test.ru") @staticmethod def get_client(user): client = APIClient() client.force_authenticate(user=user) return client def test_do_something(self): client … -
How to create multiples request in Django
I want to receive a request.POST values N times, where N is a number entered by the user. The views.py is: def valores(request): global peso_unitario, preco_unitario peso_unitario = [] preco_unitario = [] N = a print('N=' + str(N)) for i in range(N): form = Form(request.POST) c = int(request.POST.get('peso_u')) d = int(request.POST.get('preco_u')) peso_unitario.append(c) preco_unitario.append(d) return render(request, 'valores.html') return render(request, 'pacote_m.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) In this code in the end I have two returns, where the first is inside the for loop because I want to receive the values N times and return them to the template valores.html. The last return is in the end, after the for loop will redirect to a new template, this template pacote.html will show the values calculated according to I programmed, but it isn't the problem. The template valores.html is: {% extends 'basic.html' %} {% block content %} <form action="page2" method="GET"> {% csrf_token %} <h1>Digitados:</h1> numero de objetos={{n_objetos}}<br> peso peso maximo={{peso_maximo}}<br> <!--- Peso unitario: <input type="text" name="peso_u"><br><br> Preco unitario: <input type="text" name="preco_u"><br><br> ---> <table> <thead> <tr> <th>Peso unitario</th> <th>Preco unitario</th> </tr> </thead> <tbody> <tr> <td><input type="text" name="peso_u"></td> {{form.peso_u}} <td><input type="text" name="preco_u"></td> {{form.preco_u}} </tr> </table> <input type="submit"> </form> {% endblock %} My forms.py is: class Form(forms.Form): … -
How to mix the order of items of a Django object on a page?
I am trying to create a game that allows users to play a quiz, which is stored as a Django object, but I want the order of the questions to be different (as in random) every time. Is there a way to accomplish this? models.py class Quiz(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, default="") title = models.TextField(default="") question1 = models.TextField() answer1 = models.TextField() question2 = models.TextField() answer2 = models.TextField(default="") question3 = models.TextField() answer3 = models.TextField() ... (The questions and answers go to 10.) views.py def quiz(request, quiz_id): quiz = get_object_or_404(Quiz.objects, pk=quiz_id) return render(request, "capstone/quiz.html", { "quiz": quiz }) I was thinking about generating a random number, but I think that would be too complicated with the number of questions. Is there any easier way to randomly display the questions to the user? -
jinja2 emplateNotFound (but file exists)
In one of my views in Django 4.0 I want to render a summary of lesson with Jinja2. Even though a template exists for sure in good location I get jinja2.exceptions.TemplateNotFound which is very confusing. views.py: from jinja2 import Environment, FileSystemLoader def generate(request): if request.method == 'POST': ... var1 = "foo" var2 = "bar" var3 = 123 BASE_DIR = Path(__file__).resolve().parent.parent templatesPath = str(BASE_DIR) + '/static/tex/' fileSystemLoader = FileSystemLoader(templatesPath) env = Environment(loader = fileSystemLoader) renderedLatex = env.get_template(templatesPath + 'lesson_template.tex').render(pvar1, var2, var3) After calling the view the output is: jinja2.exceptions.TemplateNotFound: /home/user1/Projects/Dramath/Dramath-Project/static/tex/lesson_template.tex Just to be sure there is no typo I copied full path to the template file and compared it with the above - both paths are the same. For a quick test I tried to relocate lesson_template.tex in project root directory but it didin't do much. Any ideas where might be issue?