Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to access lower and upper values in Django PostgreSQL specific fields?
More specifically I need to get start and end dates from a DateRangeField. -
Not loading svg logo in html page in django site (logo broke)
I'm trying to use svg format for my logo but getting this, can't figure out why? <div class="bgimg"> <div class="topleft"> <p><img src="{{STATIC_URL}} svg/logo.svg"/> Page title</p> </div> It look like this... -
django project-level object instantiation
Suppose I would like to create an object that performs some action every n seconds. For example, an object that does machine learning calculations on server data every hour. What is the correct way to instantiate such object in Django immediately after an app is loaded.? What is the correct way to call an infinite loop of this object? What is the correct way to call an on-server-shutdown object's method? For the first question, I think it is somehow related to the app's module apps.py, but do not know how to implement this: from django.apps import AppConfig from django.contrib.auth import get_user_model class MyAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'myapp' def ready(self): print("my app has been loaded!") -
Python Django Deployment on Amazon EC2
Can someone please help me with python django project deployment? i am having trouble in urls redirection and static files loading in the deployment server 'amazon ec2' ? I have my project deployed .. Checked the static file serving multiple times but still can't figure out the issue . Need help !! -
Is there a way to implement authentication in Django that requires an API Key and Secret?
I'm struggling in Django to set up an authentication that uses an API Key and secret. I've tried using the rest_framework_api_key but I don't see a secret offered and the documentation doesn't have very many examples. Does anyone have an example of how you would set this up in Django? -
fetching data from outside API in Django
I have an external API with its Content-Type, Authorization key, and tenant fields. The description of API is like this: URL: https://url_address.com/ method: POST Header: Content-Type: application/json Authorization: Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd= Body: -> raw : { "Tenant" : "devED" } I try to fetch these data from my django views with this: headers = {'Content-Type': 'application/json', 'Authorization': 'Basic asfvasvGasfssfafssDGDggGDgDSggsdfgsd='} Body = { "Tenant": 'devED' } GetAPI_response = requests.post('https://url_address.com/', headers=headers, params=Body).json() But it says errors like: {'Message': 'Request data is in Bad Format.'} Please suggest how can I fix this? -
Reverse for 'edit' with keyword arguments '{'title': 'HTML'}' not found
I'm running a program to create a wikipedia style website using python and the django framework. I'm running into an issue where I have a link to edit the wiki page on the entry pages. When the page tries to render I get the error message in the title of this post. I'm not sure why it's not finding the edit page, I think I might have a typo somewhere but I'm not finding it. Any help here would be greatly appreciated! URLS.py urlpatterns = [ path("", views.index, name="index"), path("error", views.error, name="error"), path("newPage", views.newPage, name="newPage"), path("random", views.random, name="random"), path("edit", views.edit, name="edit"), path("<str:entry>", views.markdown, name="entry") ] entry.html {% block nav %} <div> <a href="{% url 'edit' title=entry %}" method="GET">Edit Page</a> </div> {% endblock %} views.py entry function def edit(request, title): content = util.get_entry(title) return render(request, "encyclopedia/newPage.html", { "title": title, "content": content }) -
"unknown parameter" error on Django bootstrap table running with Sphinxsearch
I have a table in my django (2.1) site that is a filterable search that runs through my sphinxsearch mysql database. The build works with a primary postgres database that is then added to the sphinxsearch mysql table. I recently added a column to both the postgres and sphinx database, and have confirmed that both have populated through viewing mysql...but when I try to pull them up in the table, I receive the follwoing error: "DataTables warning: table id=table - Requested unknown parameter 'member_name' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4" My table works through a conf.py file that is then ran through an ajax view. conf.py section: USERS_TABLE_COLUMNS = [ dict( name="member_name", orderable=True, ), dict( name="phone", orderable=True, ), ] views_ajax.py def public_table_page(request): table_mode = request.GET.get("table_mode", conf.TABLE_MODE_GROUPS) search_query = request.GET.get("search[value]", "") search = ParseQuery(search_query, table_mode) if search.table_mode != table_mode: response = { "draw": request.GET.get("draw"), "data": [], "recordsTotal": 0, "recordsFiltered": 0, "table_mode": search.table_mode, } referer = request.GET.get("referer") if referer: parsed = urlparse(referer) referer_query = { key: value[0] if len(value) == 1 else value for key, value in parse_qs(parsed.query).items() } else: referer_query = {} response.update({ "filters": utils.get_filters(request, search.table_mode, referer_query), "table": utils.get_table(request, search.table_mode), }) return JsonResponse(response) … -
can't create multiple contacts and emails in django restframework
I want to create a contact that contains users and users can have multiple phone numbers and contact numbers. I can't find where the problem is? When I try to migrate is shows: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: models.py code: class Contact(models.Model): full_name = models.CharField(max_length=30, unique=True) nick_name = models.CharField(max_length=30, unique=True) status = models.BooleanField(default=1) def __str__(self): return self.full_name class Meta: ordering = ['full_name'] class Email(models.Model): email = models.EmailField(max_length=30) user_emails = models.ForeignKey( Contact, on_delete=models.CASCADE, related_name='emails', blank=True) def __str__(self): return self.email class PhoneNum(models.Model): contact_num = models.CharField(max_length=30) user_contacts = models.ForeignKey( Contact, on_delete=models.CASCADE, related_name="contact_numbers", blank=True) def __str__(self): return self.phone_num serializers.py code: from django.db.models import fields from rest_framework import serializers from .models import Contact, Email, PhoneNum class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' class MultipleSerializer(serializers.ModelSerializer): emails = serializers.StringRelatedField(many=True) contacts = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Email, PhoneNum fields = '__all__' views.py code: class ContactViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing contacts. """ queryset = Contact.objects.all() serializer_class = ContactSerializer Help to get this please. -
Django Online Users HTML with Jquery/Ajax Call
I made an html page and service that will show the list of online users on my project. I get json response with requests and add these elements to the dictionary. Then I print them in table format html using django tags. views.py def get_data(request): response = requests.get('https://***/?json=true') jsondata = response.json() member_items = [] for id, gvalues in jsondata.items(): for k, v in gvalues.items(): try: member_items.append({ 'line': (len(member_items)) + 1, 'id': id, 'duration': round(datetime.now().timestamp() - v.get('t')), 'user_agent': v.get('u_a').strip('Mozilla/5.0 (Linux; ').replace("wv", "Web View"), 'blur_screen': v.get('b_s').get('s').replace("focus", "Aktif").replace("blur", "Pasif"), 'current_url': v.get('c_u').get('u'), }) except: pass return render(request, 'home.html', {'member_items': member_items}) my html like: {% for data in member_items %} <tr> <th>{{ data.line | safe }}</th> <th>{{ data.id|safe }}</th> <th>{{ data.duration|safe }}sn</th> <th>{{ data.user_agent|safe }}</th> </tr What I'm trying to do is I want it to appear when a new user arrives, without refreshing the page. As far as I researched, I needed to use jquery and ajax call for this.I am a beginner in Django and Jquery.Sorry for my bad English. -
Django-filter styled inputs
I am currently using a downloaded theme. I am working on the filtering products page that already has styled filters. I am using Django-filter and was wondering if there was a way to use the styled filters with Django-filter field. I'm specifically trying to get a price slider to work instead of Django-filter min and max box inputs. -
How to annotate on a Django model's M2M field and get a list of distinct instances?
I have two Django models Profile and Device with a ManyToMany relationship with one another like so: class Profile(models.Model): devices = models.ManyToManyField(Device, related_name='profiles') I am trying to use annotate() and Count() to query on all profiles that have 1 or more devices like this: profiles = Profile.objects.annotate(dev_count=Count('devices')).filter(dev_count__gt=1) This is great, it gives me a QuerySet with all the profiles (4500+) with one or more devices, as expected. Next, because of the M2M relationship, I would like to get a list of all the distinct devices among all the profiles from the previous queryset. All of my failed attempts below return an empty queryset. I have read the documentation on values, values_list, and annotate but I still can't figure out how to make the correct query here. devices = profiles.values('devices').distinct() devices = profiles.values_list('devices', flat=True).distinct() I have also tried to do it in one go: devices = ( Profile.objects.values_list('devices', flat=True) .annotate(dev_count=Count('devices')) .filter(dev_count__gt=1) .distinct() ) -
Can't make path right in css on django site
I'm working in django, and I have one page that I have inputed css in html file, and from there I need to call background image (to be honest did not work with css in a while). However I make path is not working, even put photo in same folder with html file, created new one, nothing. I would like to put it in Django_site/static/images/1.jpg. Currently I'm in Django folder Django_site/Django_app/templates/Django_app/my.html. What do you suggest? .bgimg { background-image: url('images/1.jpg'); height: 100%; background-position: center; -
Incompatibility Issue in upgrade django from 2.4 to 3.0
I maintain a system and update it frequently because it's been used a lot since django 1.8, currently the project is on django 2.4 and I'd like to upgrade to 3.0, however, I'm having a model compatibility issue. The "models" are in simplified versions and this works normally in previous versions. The "models" are that way because I migrated a giant system so I made the database as close as possible to the old one to save me work. class Pessoa(models.Model): idPessoa=models.IntegerField(primary_key=True,blank=True) name=models.CharField(max_length=100,verbose_name="nome") address=models.TextField('endereço', blank=True, null=True) class Bancos(Pessoa): @property def idBanco(self): return self.idPessoa @idBanco.setter def idBancoSetter(self,valor): self.idPessoa = valor codigo_febraban=models.CharField(max_length=5,null=True,blank=True) def __str__(self): return self.name class ContasBancariasPessoas(models.Model): idContaBancaria = models.IntegerField(null=True,blank=True) idPessoa = models.ForeignKey(Pessoas,limit_choices_to={'visivel':True},on_delete=models.CASCADE,to_field='idPessoa',verbose_name='titular') idBanco = models.ForeignKey(Bancos,on_delete=models.CASCADE,to_field='idPessoa',verbose_name="banco", related_name='bancos',null=True) Agencia = models.CharField(max_length=10,null=False,default='0000', verbose_name="agência") Numero = models.CharField(max_length=20,null=False,default='0000', verbose_name='número da conta') Titular = models.CharField(max_length=50,null=True,blank=True, verbose_name='titular',help_text="nome que é exibido na conta") The error is the following: django.core.exceptions.FieldError: 'institucional.ContasBancariasPessoas.idBanco' refers to field 'idPessoa' which is not local to model 'institucional.Bancos' -
Django handle 2 forms in UpdateView - form_valid doesn't work (says invalid) - Post works?
I have an app where I am putting an inline_formset inside of the template of an object form. The formset is for all the related objects. The 'main object' is a GrowthPlan, the related objects are Response objects. When I click 'save', all of the formset objects (Response) save appropriately without issue. However, the main object (GrowthPlan) doesn't save. The form_invalid(self): method is getting called (I see my print message in terminal) but there are no errors tied to the form. The form_valid(self): method is never getting called. If I save the form in the post method, it saves as expected. But since this is an UpdateView I'd like to handle that with the form_valid and form_invalid; or is that the wrong way to go about this? The UpdateView looks like this: class GrowthPlanUpdateView( LoginRequiredMixin, UserIsObserverOrObserveeMixin, UpdateView ): model = GrowthPlan template_name = "commonground/growthplan_form.html" form_class = GrowthPlanForm pk_url_kwarg = "growthplan_id" def get_object(self): return get_object_or_404(GrowthPlan, pk=self.kwargs["growthplan_id"]) def post(self, request, *args, **kwargs): self.object = get_object_or_404( GrowthPlan, pk=self.kwargs["growthplan_id"] ) regular_form = GrowthPlanForm( request.POST or None, instance=self.object ) # IF I UNCOMMENT THIS - THE FORM SAVES APPROPRIATELY #if regular_form.is_valid(): # # The form saves if I put this line here # # But … -
Creating a model based on another model instances via formsets
it's my first question here! So, I'm trying to make a table with unpaid invoices (accruals model) and form fields for payment modelform. Payment model should have the same instances as amount, patient, user and be related with this accrual model. I'd like to make a table with a formset, where I can see unpaid invoices and mark paid invoices and then submit them only. The problem is that i should use two loops for unpaid invocies and formset fields to display them on the table. I've made a template with form fields in every row and it's inconvinient to reload a page after submit. And it can't make a relation between Accrual and Payment. So here is code: So, here is models.py class Accrual(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='accruals') date = models.DateField(db_index=True) amount = models.DecimalField(decimal_places=2, max_digits=10) payment = models.ManyToManyField(to='Payment', related_name='accruals', blank=True) info = models.CharField(max_length=200, blank=True, null=True) paid = models.BooleanField(default=False) patient = models.ForeignKey(to='Patient', on_delete=models.CASCADE, related_name='accruals') class Payment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='payments') date = models.DateField(db_index=True) amount = models.DecimalField(decimal_places=2, max_digits=10) method = models.ForeignKey(to='Method', on_delete=models.CASCADE, related_name='payments') info = models.CharField(max_length=200, blank=True, null=True) patient = models.ForeignKey(to='Patient', on_delete=models.CASCADE, related_name='payments') As you can see these two models are connected through m2m field "payment" in accrual model. … -
Django/ReactJS Public_URL
I have been searching for days and can't find an answer. I am trying to use tag in a component to grab a dynamic image from the public folder. The issue I'm facing is that I did a manual setup of the react app. (Side note: I tried using create-react-app and I could not get passed a message saying it needed an update to create the template. I tried deleting create-react-app and also the global install but I did not get past the error). Everything is working for the react app, I just cannot figure out how to setup the public_URL variable so I can call dynamic images from the tag. I created a folder /public/images/(files) but I cannot figure out how to setup the public_URL variable to point to the public folder. I'm not sure if I have to add something to Django routing or if there is something that just needs to be added within package.json. Please let me know what files I need to show in order to assist. -
NoReverseMatch: Reverse for 'about' not found. 'about' is not a valid view function or pattern name
I am building blog in django and stuck bcz of this error. When I click on Readmore button to load full blog post. this error appears. it should load the page which diplay blog post with detail it showed this error to me. Kindly help me i tried different solution which are available on internet but didn't get rid of this error. Here is my code! project url.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Blog_App.urls')), ] app urls from django.urls import path from . import views urlpatterns = [ path('', views.PostList.as_view(), name= 'home'), path('user/<str:username>/', views.UserPostList.as_view(), name= 'user-posts'), path('<slug:slug>', views.PostDetail.as_view(), name= 'post_detail'), path('register/', views.Register, name= 'Registration'), path('login/', views.Login, name= 'Login'), path('logout/', views.logout_view, name= 'Logout'), ] views.py from django.db import models from .forms import NewUserForm from django.shortcuts import get_object_or_404, redirect, render from django.http import HttpResponse from django.contrib.auth import login,logout, authenticate from django.contrib import messages from django.contrib.auth.forms import AuthenticationForm from django.views import generic from .models import STATUS, Post from django.contrib.auth.models import User class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'Blog_App/index.html' class UserPostList(generic.ListView): model = Post template_name = 'Blog_App/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-created_on') class PostDetail(generic.DetailView): model = Post … -
does implementing a csrf token fix an idor exploit?
as ive understood you need a csrf in each post request. So is it possible to do an idor exploit if you have a csrftoken? and if it is how do you fix an idor exploit? -
"Got KeyError when attempting to get a value for field devUserId on serializer AssetSerializer. Original exception text was: 'devUserId'
models.py class User(models.Model): googleId = models.CharField(max_length=512, primary_key=True, default='') imageURL = models.CharField(max_length=512, null=True) userName = models.CharField(max_length=512, null=True) firstName = models.CharField(max_length=512, null=True) lastName = models.CharField(max_length=512, null=True) #phoneNumberRegex = RegexValidator(regex=r"^+?1?\d{8,15}$") phoneNumber = models.CharField(max_length=512, null=True) email1 = models.CharField(max_length=512, blank=False) email2 = models.CharField(max_length=512, blank=True) bio = models.TextField(blank=True) planId = models.ForeignKey('primal_user.Plans', on_delete=models.CASCADE, default="Free") password = models.CharField(max_length=512, null=True) accountCreationDate = models.DateTimeField(auto_now_add=True) coins = models.IntegerField(default=2) assetsDownloaded = models.IntegerField(default=0) assetsPurchased = models.IntegerField(default=0) class Asset(models.Model): assetId = models.CharField(max_length=20, primary_key=True) devUserId = models.ForeignKey(User, on_delete=models.CASCADE) keywordId = models.ForeignKey(Tags, on_delete=models.CASCADE) assetName = models.CharField(max_length=50, null=False) description = models.TextField(blank=True) features = models.TextField(blank=True) uploadedDate = models.DateField(auto_now_add=True) typeId = models.BooleanField(default=True) paidStatus = models.BooleanField(default=False) price = models.IntegerField(null=True) size = models.FloatField(null=False) downloadCount = models.BigIntegerField(null=True) version = models.CharField(max_length=10) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = 'all' class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = 'all' views.py class UserAsset(APIView): def get(self,request,devUserId): try: user = Asset.objects.filter(devUserId=devUserId).values() serializer = AssetSerializer(user, many= True) return Response(serializer.data) except Asset.DoesNotExist: raise Http404 KeyError I am a beginner in Django, so am unable to figure out what the issue is. I tried looking for solutions to similar questions but could not resolve the issue. I was getting attribute error, then it was resolved after I entered many=True in AssetSerializer but now I am stuck … -
How can access programmatically to Django related_name QuerySet of objects
I have this models and relations class Address(models.Model): .. content_type = models.ForeignKey(ContentType, verbose_name=_('Content Type'), on_delete=models.CASCADE) object_id = models.PositiveIntegerField(verbose_name=_('Object ID')) content_object = GenericForeignKey() class SocialNetwork(models.Model): .. content_type = models.ForeignKey(ContentType, verbose_name=_('Content Type'), on_delete=models.CASCADE) object_id = models.PositiveIntegerField(verbose_name=_('Object ID')) content_object = GenericForeignKey() class Company(models.Model): addresses = GenericRelation('Address') social_networks = GenericRelation('SocialNetwork') I would like to access the relation programmatically through attribute name or attribute related name. Something like this element = Company.objects.get(id=1) element.addresses.clear() element.social_networks.add(*queryset) element.attribute_name.all() ... Anybody could help me please ? -
operator does not exist: character varying = integer
I am building a BlogApp and I was working on a feature and I am stuck on a error. operator does not exist: character varying = integer LINE 1: ...d" = "taggit_tag"."id") WHERE "taggit_tag"."name" IN (SELECT... I am trying to retrieve all the comments commented by user from Tags which were used in comment's post. When I access the comments then it is keep showing that error when i access the variable in template. models.py class Post(models.Model): post_user = models.ForeignKey(User, on_delete=models.CASCADE) post_title = models.CharField(max_length=30) tags = models.TaggableManager() class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_of = models.ForeignKey(Post, on_delete=models.CASCADE) views.py class page(request): tagQuery = Tag.objects.filter(post__comment__user=request.user) #this is showing error subquery = Comment.objects.filter(post_of__tags__name__in=tagQuery) context = {'subquery':subquery} return render(request, 'page.html', context) It was showing The QuerySet value for an exact lookup must be limited to one result using slicing. So i used __in but then it keep showing that error. Any help would be much Appreciated. Thank You -
How can Ajax work with a dynamic Django dropdown list? does not select every subcategory in the selected category
does not select every subcategory in the selected category. I will show you examples from my codes my models are as follows: class Category(TranslatableModel): translation = TranslatedFields( name=models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Name')) ) slug = models.SlugField(max_length=255, unique=True, blank=True, null=True) class Subcategory(TranslatableModel): translation = TranslatedFields( name=models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Name')) ) category = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(max_length=255, unique=True, blank=True, null=True) class Announcement(TranslatableModel): translations = TranslatedFields( title=models.CharField(max_length=255, verbose_name=_('Sarlavha')), description=models.TextField(verbose_name=_('Tavsif'))) slug = models.SlugField(max_length=255, unique=True) created_at = models.DateTimeField(auto_now_add=True, ) image = models.ImageField(upload_to='elonimages') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE, null=True, blank=True) is_public = models.BooleanField(default=False) full_name = models.CharField(max_length=50) address = models.CharField(max_length=250) phone = models.CharField(max_length=12) cost = models.CharField(max_length=9, blank=True, null=True) My views.py file is as follows: class AnnouncementCreateView(CreateView): model = Announcement form_class = AnnouncementForm template_name = "announcement/add.html" success_url = reverse_lazy('announcement_list') def load_category(request): category_id = request.GET.get('category') subcategory = Subcategory.objects.filter(category_id=category_id).order_by('name') return render(request, "announcement/category_dropdown.html", {'subcategory': subcategory}) My forms.py file is as follows: class AnnouncementForm(TranslatableModelForm): class Meta: model = Announcement fields = ('title', 'description', 'image', 'category', 'subcategory', 'cost', 'full_name', 'address', 'phone',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subcategory'].queryset = Subcategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields['category'].queryset = Subcategory.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['subcategory'].queryset = self.instance.subcategory_set.order_by('name') My index.html file is as follows and the … -
Update the div element by clicking the button
I just recently started learning Django and web programming. I need to update the information in my div when the button is clicked. How can this be done? Is it possible to do this only with Django? -
Django Rest Framework: Convert serialized data to list of values
I'm using a DRF ModelSerializer to serve a one-field queryset, but the response returns as a list of dicts [{"state": "AL"}, {"state": "AR"}, {"state": "AZ"}] Is there any way to return a pure string list, like ["AL", "AR", "AZ"] ? I've explored other questions, but haven't found anything useful.