Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch few variables in django url template?
If I have one variable being fetched from url template according to this regular expression: re_path(r'^reset/(?P<uid>[\w]+)/?$', accounts.api.views.SetNewPassword.as_view()), how to rewrite it to fetch few possible variables: either uid or u32id? -
get corresponding column value from the database foreign key in the selected combo/dropdown django modelform classview
I am sure this is a basic question but I am trying to move from windows application development to web based application. When I select the "SiteName" from the combo, I need to save Country as well in the database with form.save() Model.py class CountryMaster(models.Model): CountryName = models.CharField(max_length=50) Code = models.CharField(max_length=10) class SiteMaster(models.Model): SiteName = models.CharField(max_length=100) Code = models.CharField(max_length=10) Country = models.ForeignKey(CountryMaster, on_delete=models.CASCADE) class DataMaster(models.Model): CountryName = models.ForeignKey(CountryMaster, on_delete=models.DO_NOTHING) SiteName = models.ForeignKey(SiteMaster, on_delete=models.DO_NOTHING) Forms.py class DataModelForm(forms.ModelForm): class Meta: model = DataMaster fields = 'SiteName' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['SiteName'].widget.attrs['class'] = 'form-control' view.py class DataCreateView(CreateView): template_name = "add_data.html" form_class = DataModelForm def get_success_url(self): return reverse("myData:data_dashboard") def form_valid(self, form): form.save() # data = form.save(commit=True) # data.save() messages.success(self.request, "You have successfully Added Data") return super(DataCreateView, self).form_valid(form) mypage.html {% extends 'base_data.html' %} {% load static %} {% block content %} <div class="content"> <form method="post" class="mt-5"> {% csrf_token %} <div class="container-fluid"> <div class="row"> <div class="col-lg-6"> <div class="card"> <div class="card-body"> <div class="form-group"> <label>Select Site Name:</label> {{ form.SiteName.errors }} {{ form.SiteName }} </div> </div> </div> </div> <div class="row"> <div class="col-lg-1"> <button type="submit" class="btn btn-block bg-gradient-primary">Add Data</button> </div> </div> </form> </div> {% endblock content %} I need to add the corresponding country on SiteName selection from … -
Django REST Framework permission_classes ModelViewSet
How do I create a permission, that only allows the user to be able to read, if they are logged in. If they are not logged in, they can not do anything. I feel like this is probably very easy, but I can't seem to find the answer. This is my views.py file: class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, ) I know IsAuthenticatedOrReadOnly allows the User to read, but I don't even want that. -
'QuerySet' object has no attribute 'time'
I am building a BlogApp and I am trying to access a model instance. BUT i am stuck on an Error. The error is keep showing 'QuerySet' object has no attribute 'time' models.py class Gallery(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) text = models.CharField(max_length=30,blank=True) time = models.CharField(max_length=30,choices=CHOICES,default='24_hours') class Photo(models.Model): photo = models.ForeignKey(Gallery,related_name='imagess',on_delete=models.CASCADE) file = models.FileField(upload_to='images') views.py def timeManage(request): varia = Gallery.objects.filter(user=request.user) show = varia.time context = {'varia':varia} return render(request, 'timeMan.html', context) I have also tried by using 'time = Photo.objects.filter(gallery__user=request.user)` BUT this error is still showing. I have no idea what i am doing wrong. Any help would be Appreciated. Thank You in Advance. -
search/filter with list of string graphene-django
I am looking to search for list of different characters/string using graphene-django with single search query run. ** class CandidateType(DjangoObjectType): class Meta: model = Candidate fields = "all" class Query(graphene.ObjectType): candidateInfo = graphene.List(CandidateType, search=graphene.String(), first=graphene.Int(), skip=graphene.Int(), last=graphene.Int(),) def resolve_candidateInfo(self, info, search=None, first=None, last=None, skip=None, **kwargs): qs = Candidate.objects.all() if search: filter = ( Q(candidateName__icontains=search)| Q(candidateEmail__icontains=search)| Q(candidateSkills__icontains=search) ) qs = qs.filter(filter) return qs ** Here the candidateName, candidateSkills, candidateEmail are in Candidate class with models.CharField With a single string/character search i am getting correct output. But it fails with list of sting/characters. -
I want to split funds using PayPal Django using django-paypal
I want to pay to the seller for his sold products How can I do this using in django please help. I'm looking into paypal payouts but is there any SDK? or anything that can help me? -
Remove remaining celery tasks when concurrency is set to 1?
I have a Django application running with Docker, I'm looking for a way to terminate the remaining celery tasks when the concurrency is set to 1. This is my urls.py file from django.urls import path from . import views urlpatterns = [ path('start-process', views.start_process), path('terminate-process', views.terminate_process), ] This is my views.py file from .tasks import add_task, remove_tasks def start_process(request): add_task.delay() return HttpResponse('Task Started') def terminate_process(request): remove_tasks.delay() return HttpResponse('All remaining tasks will be removed') This is my tasks.py file from celery import shared_task from my_app.celery import app from time import sleep @shared_task def add_task(): sleep(50) return 'task completed' @shared_task def remove_tasks(): app.control.purge() return 'All tasks removed' This does not work as expected because the concurrency is set the 1. I have started the celery worker with the following command celery -A my_app worker --concurrency=1 --loglevel=info Is there any way I can remove the remaining tasks when the terminate-process url is called? -
djnago View - how get a count queries from view?
how can I get the number of db requests during a view call? connetction.queries return empty list. My views.py: def get_context_data(self, **kwargs): context = super(OrderListView, self).get_context_data(**kwargs) date = Order.objects.get(number=1).created_date last_date = Order.objects.all().order_by('id').last() filter_ = Order.objects.filter(created_date__lte=date, created_date__gte=last_date.created_date) if self.request.GET: since_date = self.request.GET.get('date_since') to_date = self.request.GET.get('date_to') filter_ = filter_.filter(created_date__lte=since_date, created_date__gte=to_date) context['OrderListView'] = filter_ context['connections'] = connection.queries return context -
Django Image Resizing Before Upload
Currently, If I upload an image, It shrinks the image size then overwrites the file inside AWS s3 storage Media file and name it to the the file's original name For example: If i upload a 1MB size image called AA.png, It shrinks the size to 50KB, Then in AWS S3 Media file you would find the shrinked image named AA.png I want: File extension to always be .jpg, Eg: User uploads .png but stored as .jpg in AWS S3 Media Give each image a unique name generated by random numbers or strings If I change to storage.save("{random_number}.jpg", memfile), then the above problems could be solved, But it creates 2 Images in the S3 Media file, Eg: If a user uploads 1mb AA.png, Then results in S3 Media would be: some_random_number.jpg(50kb), AA.png(1MB, untouched original image), If I am correct, The image files in S3 are being overwritten if it has the same name, Is there a way to shrink the image in Django before it reaches S3 Media file and prevent the original image from being stored in the first place? Models.py: from PIL import Image from django.core.files.storage import default_storage as storage from io import BytesIO class Card(models.Model): photo_1 = … -
Run django+nginx+celery+gunicorn+daphne on docker
I have been trying for long to run my django application using docker but unable to do so. Application works fine using normal architecture like deploying on ubunutu compute engine. Below is the Dockerfile.prod ######### # FINAL # ######### # pull official base image FROM ubuntu:20.04 # create directory for the app user RUN mkdir -p /home/app # create the app user RUN adduser app RUN usermod -a -G app app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles WORKDIR $APP_HOME # install dependencies ARG DEBIAN_FRONTEND=noninteractive RUN apt-get update RUN apt-get upgrade RUN apt-get install python3-pip nano -y RUN apt-get install postgresql-contrib libpq-dev python-dev -y RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint-prod.sh COPY ./entrypoint.prod.sh $APP_HOME # copy project COPY . $APP_HOME # chown all the files to the app user RUN chown -R app:app $APP_HOME # change to the app user USER app RUN ls # run entrypoint.prod.sh ENTRYPOINT ["/home/app/web/entrypoint.prod.sh"] Below is docker-compose.prod.yml version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn Reporting.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles expose: - 8000 env_file: - ./.env.prod depends_on: - db - rabbitmq - redis db: … -
Use of Django Filter
Helloo! I have a project that works with Requests. I have a table with request_name, Department,... What I want is: for every user logging in to have only request from his department. Please help to achieve this. Thank you -
Problems deploying Django on a web server hosting multiple sites
Currently I am working on migrationg a Django site (app) to a hosting service, folder structure is as follows: /home/user /public_html /example.com /example.ee - wordpress site, needs to keep working /example.fi - where I am trying to deploy the django app When I try to install a Python app from cPanel, and set up everything to work for django application, wordpress site and all others return a 500 internal server error, how could I deploy django only for one domain without affecting other domains at all... also a problem is if I set ALLOWED_HOSTS=['*'] it does load the other pages but it loads them wrong (showing a wrong page as the home page etc.) I have searched online for a day now and I can't seem to find the answer, cPanel installs the python virtualenv into the user home directory and not in the public_html folder, where I would like it to run. and I want it to only affect the domain it is a part of. Relevant server information: Server Name : Servername cPanel Version : 94.0 (build 10) Apache Version : 2.4.46 PHP Version : 7.3.27 MySQL Version : 10.3.28-MariaDB-log-cll-lve OS : Linux -
Django template VS Angular/React/Vue - Perforamance
Since i am confused to either combine django and any javascript framework or use django templates. I would like to know to following queries, How will be the performance will effect if i combine both of them together instead of django templates? Why people prefer to combine 2 frameworks together and will they prefer for huge projects like ERP and why? Since connecting and fetching data from database like MySQL and NoSQL have major impact on performance, Does REST API (or any other way) will solve the problem? Because django templates providing inbuit functions to display the data (Suppose we have to add loop in front end and backend) I hope you will consider seconds of time for the performance monitoring. Why not bootstrap? Note : I am new to front end frameworks. -
Does Google "validate" forgotten password links? [closed]
I am working on a web app using Django (hosted on Heroku). I was testing the password reset functionality and it all worked as expected. However, I found in the web logs that after I had accessed the generated link that the exact same URL was requested 14 minutes later by a different IP address. The link had expired so the response was a 400 code. For reference, the password reset link looks like this and was sent to my gmail account: https://www.example.com/password_reset/[uidb64]/[token]/ I looked up the IP address and it shows the following host name: [town]-google-cdn-01.network.[UK-ISP].net There is no other unusual traffic to the site and my email account is secure. The only thing I can think of would be if Google were to check unidentified password reset links for phishing threats, but is that actually a thing? Is there any other way that the URL could be found? -
Inconsistent Migration History
I am trying to build a custom user model on django. I deleted all the files except init.py from migrations in the personal folder. whenever I run python manage.py makemigrations I get this error InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'. this is how my director looks like: Can someone please guide me through this problem -
Django Form request method is always GEatedT, even method=“POST” is mentioned in HTML template
Views.py Html filepng please help with this question!!! Thanks!! -
Get unique outputs from combining more than one Django filters
So, I am trying to create a search engine on my website where the user enters a query and I display those results where the query exists inside the product name or description. My product model is as follows:- '''Product model to store the details of all the products''' class Product(models.Model): # Define the fields of the product model name = models.CharField(max_length=100) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) description = models.CharField(max_length=200, default='', null=True, blank=True) image = models.ImageField(upload_to='uploads/images/products') category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1) # Foriegn key with Category Model store = models.ForeignKey(Store, on_delete=models.CASCADE, default=1) Now, I have created a search filter where I filter by name and then by description and then combine the results to return a queryset. The issue is that sometimes the query can be found in names and in descriptions so I get repeated entries like this My filtering code is mentioned below:- names = queryset.filter(name__icontains=search_query) descriptions = queryset.filter(description__icontains=search_query) queryset = list(chain(names, descriptions)) return Response(ProductSerializer(queryset, many = True).data) I want to be able to only get one result since it's the same product. Is there a way I can only save the distinct results in query set. I made a loop which checks the results in descriptions … -
Python+Django : Bug in code looking for a 2nd insight
I have a function with the following code: if request.method == 'POST': company_id = request.POST.get('company_id') choice_list = request.POST.getlist('info[]') response = read_csv_lines(choice_list,company_id) print(response) choice list contains numbers selected in a list. For example [2,3] and the ID of a dropdown box This one goes to the following function (read_csv_lines) def read_csv_lines(my_list,company_id): test_file = './upload.csv' company = Company.objects.get(id=company_id) with open(test_file) as csv_file: file_reader = list(csv.reader(csv_file, delimiter=';')) for i in my_list: i = int(i) deviceinf = file_reader[i] status = add_device(deviceinf,company.auth_token,company.company_name) I get the info from the company cause i need these to make an api call in a seperate function i open the file read every line but all lines in a list and for the value i I read the line in the list of read lines. And pass this trough to my API call. What happens next is the bug. When i launch a POST the following thing happens: It enters the read_csv_lines. jumps right back out and print as response "None" but the other calls keep on going and the api call in the background executes Could someone look into this as a 2nd opinion ? -
Django Authentication Pblm
Eg : If A user append in his/her list then it is reflecting in B user as well from django import forms from django.forms import ModelForm,TextInput from .models import * class TaskForm(forms.ModelForm): title= forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Task title...'}), label=False) due= forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Due date...'}), label=False) class Meta: model = task fields = ['title', 'due'] class UpdateForm(forms.ModelForm): title= forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Task title...'})) class Meta: model = task fields = ['title', 'due', 'complete'] -
How do i show a form list inside a form list
Front End <Form.List name='question_parts' key='question_parts'> {(fields, { add, remove }, { errors }) => ( <> {fields.map((field, index) => ( <Space key={field.key} direction='vertical' style={{ width: '450px' }} > <Form.Item key={`QuestionPart${index}`} > <Form.Item {...field} label={`Question Part ${index + 1} Description`} fieldKey={[field.fieldKey, 'part_desc']} name={[field.name, 'part_desc']} key={`part_desc${index}`} > <Input.TextArea rows={4} placeholder='Question Part Description' style={{ border: '1px solid black', width: 450 }} /> </Form.Item> <Form.List name='guided_answer' key='guided_answer' > {(fields, { add, remove }, { errors }) => ( <> {fields.map((field, index) => ( <Space key={field.key} direction='vertical' style={{ width: '450px' }} > <Form.Item key={`QuestionPart${index}`}> <Form.Item {...field} label={`Guided Answer ${index + 1}`} fieldKey={[field.fieldKey, 'model_ans']} name={[field.name, 'model_ans']} key={`model_ans${index}`} > <Input.TextArea rows={4} style={{ border: '1px solid black', width: 450, }} /> </Form.Item> <Form.Item {...field} label={`Guided Answer ${index + 1} Marks`} fieldKey={[ field.fieldKey, 'answer_mark', ]} name={[field.name, 'answer_mark']} key={`answer_mark${index}`} > <Input style={{ border: '1px solid black', width: 450, }} /> </Form.Item> <MinusCircleOutlined className='dynamic-delete-button' style={{ paddingLeft: '10px', position: 'absolute', top: '0%', right: '-5%', }} onClick={() => remove(field.name)} /> </Form.Item> </Space> ))} <Form.Item> <Button type='dashed' onClick={() => add()} icon={<PlusOutlined />} style={{ border: '1px solid black', width: '95%', }} > Add Guided Answers </Button> <Form.ErrorList errors={errors} /> </Form.Item> </> )} </Form.List> <Form.Item {...field} label={`Question Part ${index + 1} Marks`} fieldKey={[field.fieldKey, 'part_total_marks']} name={[field.name, 'part_total_marks']} … -
How do I create a model dynamically with introspection in django?
Hi want to create a database model using introspection. When I run introspection.get_table_description(cursor, 'someModeLName') the TableDoesNotExist(table) error is raised. Is this how to create a model or I got it completely wrong? -
Trouble in passing ManyToMany Queryset data via Ajax call to django template
I have two Models classes class Dishes(models.Model): dishName=models.CharField() class Hotels(models.Model): hotelname=models.CharField() dishes = models.ManyToManyField('Dishes') In views.py def check_dishes(request): HotelId = request.GET.get('Id', None) hotelObj = Hotels.objects.get(pk=HotelId ) dishesObj= hotelObj.dishes.all() data = { 'HotelName': hotelObj.hotelname } Dlist=[] for dish in dishesObj: Dlist.append(dish.dishName) data.update([ ('dishes_list', Dlist), ]) print(data) *** output as below {'HotelName': 'DeMart', 'dishes_list': ['pizza','burger']}*** return JsonResponse(data,safe=False) In hotels.html we have an ajax call like $("#getHotelDishes").keyup(function () { $.ajax({ url: "{% url 'check_dishes' %}", dataType: 'json', data: { "hotelId": Id }, // on success success: function (data) { {% for dishes in data.dishes_list%} //print dish Names of this Hotel {% endfor %} }, // on error error: function (response) { console.log(response.responseJSON.errors) } }) }); Is this the right way to pass Queryset data via Ajax call,I could not get any result in for loop -
AttributeError: module 'accounts.serializers' has no attribute 'TokenSerializer'
This code I used in my previous projects and this works fine but now I am using this in my another project and this giving me this error on terminal while running AttributeError: module 'accounts.serializers' has no attribute 'TokenSerializer' If I comment out this line from settings.py REST_AUTH_SERIALIZERS = {"TOKEN_SERIALIZER": "accounts.serializers.TokenSerializer"} then there is no error and everything works fine. Now I am confused why this happening in current project while in previous project I was using the same version of django and rest framework with same backend code .... Is that going to be problem in the future if I kept commented out from settings.py ? requirements.txt ... dj-rest-auth==2.1.4 django-allauth==0.44.0 Django==3.2.3 django-cors-headers==3.7.0 django-environ==0.4.5 django-filter==2.4.0 djangorestframework==3.12.4 django_extensions==3.1.3 ... my code in settings... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.sites', ... 'accounts', 'frontend', 'rest_framework', #https://www.django-rest-framework.org/ 'rest_framework.authtoken', 'corsheaders', # To Connect API with React App if required in seprate apps 'allauth', #https://django-allauth.readthedocs.io/en/latest/installation.html 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth', 'dj_rest_auth.registration', 'django_extensions', 'debug_toolbar', #local usage ] # Auth user Settings AUTH_USER_MODEL = "accounts.User" # Configure django-rest-framework REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.TokenAuthentication", "rest_framework.authentication.SessionAuthentication", ), "TEST_REQUEST_DEFAULT_FORMAT": "json", } REST_AUTH_SERIALIZERS = {"TOKEN_SERIALIZER": "accounts.serializers.TokenSerializer"} REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } # For django.contrib.sites SITE_ID = 1 # Configure django-allauth ACCOUNT_EMAIL_REQUIRED = True … -
ORDER BY not allowed in subqueries of compound statements; union queryset
I'm trying to create a listing page of all the questions posted that share the same type of tags a single user has used in their own questions. In other words, if a User has only posted questions about Python and OOP, they would only see questions that shared either one or both of those tags. Upon trying to implement this, I tried to use the .union() queryset to add the different filtered querysets together. However the following error is raised: ORDER BY not allowed in subqueries of compound statements. I found a similar issue raised here and it mentions how the method may be incompatible with SQLite which is the database I'm using: error "ORDER BY not allowed in subqueries of compound statements". In django while using Union function Is there another means of trying to overcome this error and getting the expected result that doesn't user the .union() queryset? models.py class Question(models.Model): title = models.CharField(max_length=50) body = models.TextField() dated = models.DateField(default=date.today) vote_tally = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] default_manager_name = "objects" def __str__(self): return self.title … -
How to check for ACCESS_KEY_SECRET AND ACCESS_KEY_ID sent by an application and these credentials are also stored in the Application table
An application is sending an api post request with ACCESS_KEY_SECRET and ACCESS_KEY_ID in headers and other information in request body as i am not using any other authentication of DRF what i am doing is just simply matching the ACCESS_KEY_SECRET and ACCESS_KEY_ID of the api header to the ACCESS_KEY_SECRET and ACCESS_KEY_ID stored in Applicaion table, as i am new to python and django just want to check if i am doing it right. views.py @api_view(['POST']) def orderdetails(request): try: ACCESS_KEY_ID = request.META.get('HTTP_ACCESS_KEY_ID') ACCESS_KEY_SECRET = request.META.get('HTTP_ACCESS_KEY_SECRET') applications = Applications.objects.all() id=0 for e in applications: if(e.ACCESS_KEY_ID==ACCESS_KEY_ID and e.ACCESS_KEY_SECRET==ACCESS_KEY_SECRET ): id = e.id+id print(id) break else: return Response({"Message":"Enter Valid Credentials"}) except ValueError: return Response({"ACCESS":"DENIED"}) if request.method == 'POST': data=request.data print(data) orders = Orders(applications=Applications.objects.get(id=id), purpose_code = data['purpose_code'], amount=data['amount'], currency=data['currency'], note=data['note'], payer_name=data['payer_name'], payer_email=data['payer_email'], payer_phone_country_code=data['payer_phone_country_code'], payer_phone_number=data['payer_phone_number']) try: orders.full_clean() except ValidationError: return Response({"Error message":"invalid request body"}) else: orders.save() serializer = OrderSerializer(orders) order_id = serializer.data['id'] access_token = serializer.data['access_token'] content = {"orderId":order_id,"accessToken":access_token} return Response(content, status=status.HTTP_200_OK) else: content = {"Error message":"invalid request body"} return Response(content, status=status.HTTP_400_BAD_REQUEST) models.py class Applications(models.Model): id= models.AutoField(primary_key=True) code = models.CharField(max_length=100) name = models.CharField(max_length=100) ACCESS_KEY_ID = models.CharField(max_length=100) ACCESS_KEY_SECRET = models.CharField(max_length=100) webhook_Auth_Token = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True,auto_now=False) updated_at = models.DateTimeField(auto_now_add=False,auto_now=True) isActive = models.BooleanField(default=False) def __str__(self): return self.name