Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best method for retrieving all objects associated with a foreign key using Django rest_framework?
I have a React application where I'm using Django+REST for the API and backend. On the frontend, I send a POST request to create a Job model and run the job. In the response, I retrieve the ID of the new Job object. axios.post('http://127.0.0.1:8000/api/jobs/', query) .then((resp) => { setActiveJobs([...activeJobs, resp.data.id]) }, (error) => { console.log(error) }) When the job finishes running, it creates multiple Result objects associated to it by a ForeignKey. These are my two models: class Job(models.Model): query = models.CharField(max_length=255, blank=True, null=True) status = models.CharField(max_length=10, blank=True, null=True) class Result(models.Model): job = models.ForeignKey(Job, blank=False, null=False, on_delete=models.CASCADE) result_no = models.IntegerField(blank=False, null=False) ... more fields I'm having trouble using rest_framework in Django to send a GET request using the Job's ID to get a list of all the Result associated with it. I've tried to give custom implementations for retrieve(self, request, pk=None) and get_queryset(self) but so far my approaches have not worked. Ideally, I'd like to call a url such as localhost:8000/api/results/15 where 15 would be the object id of the Job that was created. If there are 5 Result objects that have the job ForeignKey field set as the Job object with an ID of 15, a list of those … -
Updating a mysql row via Django
I have a basic working app that displays the contents of a table and also allows you to insert new rows. My next step is to allow updating of existing rows, and I'm running into some mental roadblocks that I think are caused by my basic understanding of how components of a django project interact with each other (views,models,templates,etc.). I currently have this views.py file within my "enterdata" app. The "showform" function allows you to create a new record within the db. What I am working on is the "updatedata" function below it, which eventually I would like to have the ability to select a row via the UI and then update. But for now, I am hardcoding the primary key and the value just to get the basics going. I am getting hung up on how I can add an "update" button to my existing HTML template that I'm already using for the ability to create rows. It trips me up that it's not easy to see how a button on an HTML form is mapped to a function in a view. Coming from a Visual Basic background where this was clear, I'm struggling a bit. How can I … -
How to deploy a specific django folder in a repository to an azure app service?
I have a Github repository with the folders back-end and front-end. The folder back-end contains a folder custom-site, which contains a Django project. I would like to use Azure to deploy this Django project, but it seems that Azure only attempts to deploy the root folder of the repository. How do I indicate that the back-end/custom-site/ folder should be used as root? -
how can add the data in db field which already exist
I am trying to add the data in main_storage table but when i save the record it show the error failed unsupported operand type(s) for +: 'DeferredAttribute' and 'int' in Main_Storage productId is foreign key i want to add the data according to the foreign key but it show the error data = self.request.POST.get orderView = GatePass( fault=data('fault'), remarks=data('remarks'), order_id=order_Id ) faultItem = orderView.fault order_request.order.orderProduct.quantity -= int(faultItem) storage = Main_Storage( product_id=productId, quantity=Main_Storage.quantity+order_request.order.orderProduct.quantity ) storage.save() -
Get array of images from JS to Django template
I want to show random images every time someone enters my art gallery or on refresh and change the images on my art gallery every 30 seconds. I have everything set up correctly in Django. In JS I have created a list of jpeg files. I want to pick a random picture. I am not sure how to use the Django syntax {% %} in JS nor do I know if it is possible. There is some code I found and it does something like this: //Add your images, we'll set the path in the next step var images = ['banner-1.jpg', 'banner-2.jpg', 'banner-3.jpg', 'banner-4.jpg]; //Build the img, then do a bit of maths to randomize load and append to a div. Add a touch off css to fade them badboys in all sexy like. $('<img class=" class="fade-in" src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#banner-load'); </script> However, I would like use the Django syntax or something similar so I don't have to specify the path to the images. Also, is there a way to tie this to a timer that will continue to show random pictures for my art gallery? Thanks! -
Cannot resolve keyword 'name' into field. Choices are:
I'm Trying to filter through a model but everytime I tried this error keeps happening: Exception Type: FieldError at /store/dashboard/utiles_dashboard/sliders/ Exception Value: Cannot resolve keyword 'name' into field. Choices are: id, image, order, slider, slider_id here is part of the code: views.py: class SliderListView(SingleTableMixin, generic.TemplateView): """ Dashboard view of the slider list. """ template_name = 'oscar/dashboard/utiles_dashboard/slider_list.html' form_class = SliderSearchForm table_class = SliderTable context_table_name = 'sliders' def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['form'] = self.form return ctx def get_description(self, form): if form.is_valid() and any(form.cleaned_data.values()): return _('Resultado de busqueda de sliders') return _('Sliders') def get_table(self, **kwargs): if 'recently_edited' in self.request.GET: kwargs.update(dict(orderable=False)) table = super().get_table(**kwargs) table.caption = self.get_description(self.form) return table def get_table_pagination(self, table): return dict(per_page=20) def get_queryset(self): """ Build the queryset for this list """ queryset = Slider.objects.all() queryset = self.apply_search(queryset) return queryset def apply_search(self, queryset): """ Filter the queryset and set the description according to the search parameters given """ self.form = self.form_class(self.request.GET) if not self.form.is_valid(): return queryset data = self.form.cleaned_data if data.get('name'): queryset = queryset.filter(name__icontains=data['name']) return queryset Forms.py: class SliderSearchForm(forms.Form): name = forms.CharField(max_length=255, required=False, label=_('Nombre')) def clean(self): cleaned_data = super().clean() cleaned_data['name'] = cleaned_data['name'].strip() return cleaned_data slider_list.html: {% extends 'oscar/dashboard/layout.html' %} {% load i18n %} {% load thumbnail %} {% load static … -
How to remake a function and a loop | Django
When a user places a bid, it is saved in the database and I want to get the info about the bid and display it on the html template. Function: def addprevbid(request, item_id): obj = Bid() obj.user = request.user.username obj.bid = request.POST.get('bid') obj.listing_id = item_id obj.save() item = Listing.objects.get(id=item_id) bidobj = Bid.objects.filter(listing_id = item_id) bid = Bid.objects.filter(bid = item_id) return render(request, "auctions/viewlisting.html", { "item": item, "bids": bidobj, "bid": bid }) Class in models.py class Bid(models.Model): user = models.CharField(max_length=64) title = models.CharField(max_length=64) listing_id = models.IntegerField() bid = models.IntegerField() Loop in html template: <h3>Previous bids:</h3> {% for i in bid %} <h5>{{i.user}}</h5> <h5>{{i.bid}}</h5> {% endfor %} -
Pre-signed URLS on Vultr Object Storage using boto3
I have been working with Vultr for quite a while, and when I wanted to store some media files, I thought of AWS'S S3, and Vultr provides an S3 compatible service (Object Storage). I can use s3cmd CLI to play with the service, and they point to use boto3 for interacting with the S3 service. I wanted to have my objects have signed URLs, but I believe boto3 has amazonaws.com as the hostname as a constant somewhere in the code and that cannot be changed from configs as below in below: import logging from django.conf import settings import boto3 from botocore.exceptions import ClientError from premarket.models import PreMarket from .models import SupervisorLogs class Supervisor(): def __init__(self) -> None: self.bucket_name = settings.BUCKET_NAME self.link_expiration = settings.ONE_WEEK self.queryset = PreMarket.objects.all() # Generate a presigned URL for the S3 object self.s3_configs_object = settings.AWS_S3_CREDS self.s3_client = boto3.client('s3', **self.s3_configs_object) def sign_objects(self): for obj in self.queryset: try: presigned_url = self.create_presigned_url(obj.video_url) obj.presigned_url = presigned_url obj.save() except Exception as e: self.supervisor_logs(level="ERROR", message=e, description=e) logging.error(e) self.supervisor_logs(level="COMPLETE", message="Object URL signing has completed", description="Object URL signing has completed") def create_presigned_url(self, object_name): """Generate a presigned URL to share an S3 object :param object_name: string :return: Presigned URL as string. If error, returns None. """ … -
Vue JS frontend and Django backend
im a begginer in programming and got a task. in general i need to prepare a project with frontend in VueJS3 and backend in Django. i have already built the front end (views, templates etc etc) and it works. the problem is that i need to inject one data from backend. the project is to make a local catering menu let's say. and the menu i need to build in django. i created a superuser and products but i have no idea how to import it to vue. via urls? or other option? i have already looked via the internet but no exact answear. is there any 'shortcut' for it? as i said the front end works good so i dont wanna change it to django now. -
want to remove error message in custom login form in django custom login
i don't want user have to see this message without any error i load page this come automatically here is my views.py def my_login(request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('accounts:home') else: return HttpResponse('<h1>Page was found</h1>') else: return render(request, "login.html", {'form': form}) my forms.py class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("User does not exist.") if not user.is_active: raise forms.ValidationError("User is no longer active.") return super(LoginForm, self).clean(*args, **kwargs) -
Django Celery Heroku - Changed Redis URL enviro variable, but still pointing to old Redis URL
I updated the enviro variable, known as config vars in Heroku for REDDIS_URL I turned off both my app dyno and my worker dyno. I then restarted my app dyno, web gunicorn myapplication.wsgi and have no issues I then restarted my worker worker celery -A myapplication worker -l info --concurrency 2 Which causes me to get the following error in logs [2021-07-06 16:00:05: ERROR/MainProcess] consumer: Cannot connect to redis://OLD_REDDIS_URL Error 111 How do I get the worker to reference the updated config var (enviro variable) for REDDIS_URL? -
How to create a button to change a text in my html with data coming from Django's models.py?
I'm starting to work with Django and I'm starting a test to solidify what I've been learning. The idea is a single page, which displays a sentence as soon as the site opens. Below the phrase, there is a button that I would like to change the phrase to some other phrase coming from a variable declared in models.py and which contains several phrases that were registered through Django's admin panel. This is my models.py file: from django.db import models class Base(models.Model): criado = models.DateField('Criado', auto_now_add=True) modificado = models.DateField('Atualização', auto_now=True) ativo = models.BooleanField('Ativo', default=True) class Meta: abstract = True class Frase(Base): frase = models.CharField('Frase', max_length=100) dica = models.CharField('Dica', max_length=200, default='-') class Meta: verbose_name = 'Frase' verbose_name_plural = 'Frases' def __str__(self): return self.frase This is my views.py file: from django.views.generic import TemplateView from .models import Frase class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['frases'] = Frase.objects.order_by('?').all() return context This is my index.html <div class="container px-4 px-lg-5 h-100"> <div class="row gx-4 gx-lg-5 h-100 align-items-center justify-content-center text-center"> <div class="col-lg-8 align-self-end"> <h1 class="text-white font-weight-bold" id="frase">{{ frases|first }}</h1> <hr class="divider" /> </div> <div class="col-lg-8 align-self-baseline"> <a class="btn btn-primary btn-xl" onclick="nova_frase()">Nova frase</a> </div> </div> </div> (...) <!--rest of the html code--> … -
Scope <style> tag inside markup of text field created by WYSIWYG editor in Django
I have Django website with django-summernote WYSIWYG editor. Admin can add news. Editor is used for editing text fields of DB models using HTML markup. User can edit field in HTML source mode. So he can paste <style> tag inside. For example he can paste something like this: <style> p { color:red; } </style> And of course after rendering field with this snippet in Django HTML template it will affect all next <p> tags, not only those which are inside field. And this is the problem. I want to allow user use <style> tag inside markup but prevent it from affecting other parts of the page. I know I can put markup in iframe but maybe there are other solutions. So I want to to know how should I do it. P.S If there is another WYSIWYG editor lib for django which can scope style in some way tell me. -
How can I integrate SSLCommerze to my django app?
I have created a ecommerce site. Now i want to integrate payment method. By adding SSLCommerce to my site, all payment method will be taken care of in Bangladesh. But I don't know how can I add it to my Django app. Please help! They said something session. But I did not get it. Here is thier github repo https://github.com/sslcommerz/SSLCommerz-Python?fbclid=IwAR0KkEH3H-AOwaWneQy0POGkTw6O3vvL9NiRM4amflyQEt54_W1g1rgYB48 -
Unble to use image which is store in django database
i create a model name profile with the help of signal so ever time a user get created it automatically create a profile with that usename in db all i want to fetch the image which i used as default in model like we fetch username with this {{ user.username }} here is my code my model class Profile(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE,) profile_pic = models.ImageField(upload_to='profile_pics/', default='default.png',) first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=75, blank=True) dob = models.DateField(blank=True, null=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, *args, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() my html <img class="profile-pic nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="max-width: 45px; max-height:45px; border-radius: 50%;" src="{{ user.Profile.profile_pic.url|escape }}" > please help -
Filter object by common words in title
I try to get related objects by get title of the current objects and and filter the common words between two titles, I could able to make something but it is not accurete I get the title and split it using .split() and use Q to filter by first and second word but this not accurate .What I want to do I want get results by get the common words between the current object title and result title def get_queryset(self): book_pk = self.kwargs['pk'] book = Video.objects.get(pk=book_pk) lst = book.title split = lst.split() return Book.objects.filter(Q(title__icontains=split[0]) & Q(title__icontains=split[1])) -
Calculate value of multiple columns in single row in django
hi i am new to django framework and i am trying to develop results management system for my degree project. i need to calculate total value of multiple subjects for each student and view the total and name of student. i aready created model and upload results usign excel. `class Marks_sheet(models.Model): id = models.AutoField(primary_key=True) term = models.CharField(max_length=20) grade = models.CharField(max_length=20) year = models.IntegerField(null=True, blank=True) school_name = models.CharField(max_length=40) student_registrationno = models.CharField(max_length=30) student_name = models.CharField(max_length=30) maths = models.IntegerField(max_length=20, null=True, blank=True) science = models.IntegerField(max_length=20, null=True, blank=True) english = models.IntegerField(max_length=20, null=True, blank=True) sinhala = models.IntegerField(max_length=20, null=True, blank=True) relegion = models.IntegerField(null=True,blank=True) history = models.IntegerField(null=True, blank=True) group1 = models.IntegerField(null=True,blank=True) group2 = models.IntegerField(null=True,blank=True) group3 = models.IntegerField(null=True,blank=True) def __str__(self): return self.student_name` this now i am try but it only show one student details only `def analyse(request): cursor = connection.cursor() cursor.execute("SELECT student_name, relegion + maths + science + english + sinhala + history + group1 + group2+ group3 as total FROM marks_Marks_sheet GROUP BY id ") r = cursor.fetchone() #r = Marks_sheet.objects.all() print(r) return render(request,'student.html',{'result':r})` -
Hello I buils a web app using react and django but when I deployit its using serverside camers as feed and not at client side
"""Please Help """ """Hello I buils a web app using react and django but when I deployit its using serverside camers as feed and not at client side. Means its not using React camera /how to use client camrea as feed for django opencv .One more thing is I am displaying django only on client side and using react as only template for django""" -
Read with python and django an array of input fields
i'm tring to read from request.POST an array of fields <input type="text" name="arrayfield[]" /><br /> <input type="text" name="arrayfield[]" /><br /> <input type="text" name="arrayfield[]" /><br /> <input type="text" name="arrayfield[]" /><br /> <input type="text" name="arrayfield[]" /><br /> <input type="text" name="arrayfield[]" /><br /> <input type="text" name="arrayfield[]" /><br /> if i use print(request.POST) i get that output <QueryDict: {'csrfmiddlewaretoken': ['p0GWUzgXEEYOTI1710vTsUAPrjUUv5NpqlVCGU7Oq1zw4LWA20d222q1aE8QvlIg'], 'username': ['Oscurodrago'], 'birthday': ['1988-04-16'], 'arrayfield[]': ['try', 'tyey', 'egr', '', 'tyr', '', ''], 'edit': ['Modifica']}> but when i try get it with request.POST.get('arrayfield[]','') dosen't work what i have to do? -
name 'SocialAccount' is not defined
I want to access the 'extra-data' dictionary provided by Social Account. I need to store the family name of the user in a variable. I have attached the the code below . The following code throws an error "name 'SocialAccount' is not defined ". I saw this on "https://stackoverflow.com/questions/51804368/django-allauth-social-application-extra-data/51805154#51805154" . data=SocialAccount.objects.get(user=request.user).extra_data follows=data.get('family_name') return render(request, 'main/index.html', {"name":follows}) -
Django -- Views MultiValueDictKeyError
I want to return 4 different versions of the homepage Homepage with search bar. No data present from API Homepage with search bar. Data present from API Homepage with search bar. No data present if request doesn't exist in API Homepage with search bar. No data present if submit button is hit without any data being entered. Version two, three and four all work. However version 1, the homepage without a GET request is not returned. Due to: MultiValueDictKeyError at / 'city'" in the views.py file. How can this be resolved? Any help will be greatly appreciated urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), ] views.py from django.shortcuts import render import requests def index(request): # Query API with user input payload = {'q': request.GET['city'], 'appid': 'b3ad513f98dae40c26f94e989b7fcb84'} response = requests.get('http://api.openweathermap.org/data/2.5/weather', params=payload) # successful request if response.status_code == 200: # Parse json output for key value pairs e = response.json() context = { 'city_name': e['name'], 'weather':e['weather'][0]['main'], 'description' : e['weather'][0]['description'], 'temp' : e['main']['temp'], 'pressure':e['main']['pressure'], 'humidity':e['main']['humidity'], 'visibility':e['visibility'], 'wind_speed':e['wind']['speed'], 'wind_deg':e['wind']['deg'] } return render(request, 'index.html', {'context': context}) else: # returns homepage if invalid city name is given in form return render(request, 'index.html') -
Add Homepage and About Page to Django Dynamic sitemap.xml
I am getting all the links for 'blog_splash', this is fine. In addition to those links I need the home and about links to be generated in sitemap.xml. sitemaps.py is as follows from django.contrib.sitemaps import Sitemap from .models import DbPost class BlogPostSitemap(Sitemap): changefreq = "weekly" priority = 0.8 protocol = 'https' def items(self): return DbPost.objects.all() def lastmod(self, obj): return obj.date def location(self,obj): return '/blog_splash/%s' % (obj.id) urls.py is as follows: urlpatterns = [ path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('', MainView.as_view(), name="home"), path('about', AboutView.as_view(), name="about"), path('blog_splash/<int:pk>', BlogSplashView.as_view(), name="blog_splash"), ] -
i want to calculate basic salary of the employees and add or deduct allownace on the basic salary
I`m trying to create an allowance when I pass the enter on allowance model and after that I want dropdown on create contract model to select multiple allowance there. after that I want to generate the payroll on basic salary to add or deduct the allowance in percentages. allowance models.py class allowances(models.Model): operationType = models.CharField(max_length=200, choices=operationType_CHOICES) arName = models.CharField(max_length=200, blank=True, null=True) enName = models.CharField(max_length=200, blank=True, null=True) valueType = models.CharField(max_length=200, choices=valueType_CHOICES) value = models.FloatField() maxValue = models.FloatField() company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return "{}".format(self.enName) **contract models.py** class CreateContracts(models.Model): ContractsReference = models.CharField(max_length=250) Employee = models.ForeignKey(Employees, on_delete=models.CASCADE) Department = models.ForeignKey(Department, on_delete=models.CASCADE) Contract_Type = models.CharField(max_length=250, choices=Type_CHOICE) Date_From = models.DateField(default=timezone.now) Date_To = models.DateField(default=timezone.now) Stage = models.CharField(max_length=250, choices=Stage_CHOICE) base_salary = models.IntegerField(default=0) shift_start = models.TimeField() shift_end = models.TimeField() workinghours = models.IntegerField(default=0) breakhours = models.IntegerField(default=0) employment_type = models.CharField(max_length=250) contract_period = models.CharField(max_length=250) notice_period = models.CharField(max_length=250) probation_period = models.CharField(max_length=250) otherallowance = models.IntegerField(max_length=250) allowance = models.ManyToManyField(allowances) def __str__(self): return "{}".format(self.ContractsReference) **views.py** def savecontract(request): c = chklogin(request) if c: empid = request.POST['empid'] cid = request.POST['cid'] emptype = request.POST['emptype'] contPerid = request.POST['contPerid'] sdate = request.POST['sdate'] endDate = request.POST['endDate'] notPeriod = request.POST['notPeriod'] probPeriod = request.POST['probPeriod'] bs = request.POST['bs'] shiftstart = request.POST['shiftstart'] shiftend = request.POST['shiftend'] workhours = request.POST['workhours'] lunch = request.POST['lunch'] if empid == … -
error connecting to postgresql server with django
I am trying to connect to a postgresql server using django. I was given connection details from the host, but am still receiving the error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 54 My main question is in regards to the host. The original files were set up with localhost, and I was never given another host.... However, the server is not located on my computer and I am wondering if a different host address is needed. If so would it be an IP address only, or would a website work? I'm new to this, so any help is appreciated! I did try and look through other questions but I couldn't figure out the host question from it. My database setup (most info is commented out) is: 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'server web address', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT' : 5432, }, Thank you! -
How can I change value on one table while creating an instance on another in django model?
I wanted to select multiple users from the Profile and change their amountDue to the amount on the Matchpayment model, in other words - the amountdue for each player should increment according to each of the Matchpayment they are in using the amount from MatchPayment. Hope it makes sense. from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) amountDue = models.IntegerField() def __str__(self): return self.user.username class MatchPayment(models.Model): match = models.CharField(max_length=30) amount = models.IntegerField() players = models.ManyToManyField(Profile) datespent = models.DateField('Date Spent') def __str__(self): return self.match