Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to set an API on django rest framework just like it https://docs.microsoft.com/en-us/rest/api/power-bi/reports/get-reports-in-group#code-try-0
I want to set an API on django rest framework which take sheet_id of google drive. I want same functionality but google.drive. https://docs.microsoft.com/en-us/rest/api/power-bi/reports/get-reports-in-group#code-try-0 -
Django Middleware user is always anonymus (REST, SimpleJWT)
I am using Django REST Framework alongside with rest_framework_simplejwt and trying to write my own middleware, that will update user.last_request every time user performs one. from django.utils.timezone import now class LastRequestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: request.user.last_request = now() request.user.save() response = self.get_response(request) return response``` But every time `user.is_authenticated` returns `False' -
subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method
I am working on a Django project integrated with MongoDB as the database. I have set up my models for a simple blog post, views(function-based views), and URLs but I experience this error when I want to add a post(from the admin area for now): NotImplementedError at /admin/mongo/post/add/ subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) verbose_name = 'Post' verbose_name_plural = 'Posts' def __str__(self): return self.title def get_absolute_url(self): return reverse("mongo:post_detail", args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) views.py from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.published.all() return render(request, 'blog\post\list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) -
What is best practice to remove values in M2M relation in DRF?
could you please point this out... What is the best practice in django rest framework should be if I wanna remove some m2m objects from base model object? Should I just be satisfied with views method PATCH and update method in serializers (orm m2m method "set" to reset and install all values from scratch) and to use obj.m2m.set(*[list_values]) OR should I implement a views action method DELETE to remove specific values (orm m2m method "remove" to remove specified in list objects) and to use obj.m2m.remove(*[list_of_values])? -
Django Modelform with one custom field doesn't save
We use a JSONField to store some dynamic data on our application. We would like to present this data in a user friendly manner and decided on a table with keys and values. For this we adjusted the ModelForm in our forms.py: class UserEditForm(ModelForm): class Meta: model = OUR_MODEL fields = ['description', 'reference'] widgets = { 'reference': CustomJSONWidget(), } The CustomJSONWidget is defined as follows: class CustomJSONWidget(Widget): template_name = 'jsonwidget.html' def get_context(self, name, value, attrs=None): return {'widget': { 'name': name, 'value': json.loads(value), 'type': 'table' }} def render(self, name, value, attrs=None, renderer=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) And finally the jsonwidget.html looks like this: <table name="{{ widget.name }}"> ... <tbody> {% for key, val in widget.value.items %} <tr> <td><input {% if key != None %} value="{{ key|stringformat:'s' }}"{% endif %} /></td> <td><input {% if val != None %} value="{{ val|stringformat:'s' }}"{% endif %} /><td> <tr> {% endfor %} </tbody> </table> It looks good on the page, exactly like we envisioned it, but the saving doesn't work: when trying to update the description it throws that reference is a required field and changing the table doesn't do anything. Where do we have to overwrite the save? Is … -
Fake installization in django
When I install django (pip install django) the cmd say Requirement already satisfied but when I do this (django-admin --version) to get the version the cmd say 'django-admin' is not recognized as an internal or external command, operable program or batch file. -
Django ORM Annotate Count Items and Order by Specific Order?
I have a graph showing different licence types by region and how many active licences there are in each region. Is there a way to order the items in a specific order in the queryset to be output to the graph? These are my models: class Licence(models.Model): status = models.CharField(choices=STATUS, max_length=1000) number = models.CharField(unique=True, max_length=1000) licence_type = models.ForeignKey( "LicenceType", on_delete=models.SET_NULL, null=True ) class LicenceType(models.Model): region = models.ForeignKey( "Region", on_delete=models.SET_NULL, null=True ) class Region(models.Model): slug = models.SlugField(primary_key=True) Here is my view: @login_required(login_url="/login/") def dashboard(request): # total number of active licences across regions active_licences = ( Licence.objects.values("licence_type", "licence_type__region") .annotate(total=Count("id")) .order_by("licence_type") ) return render(request, "dashboard.html", "active_licences": active_licences) Is there a way that I can specify the order in which the regions appear? For example, they are currently in the order (by pk) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] but I want them to appear as [1, 3, 2, 4, 5, 6, 7, 8, 9, 10]. -
Saving a list on a djago model
Hi guys I'm working with python, django and django rest framework I want to sabe the information that i have on a dictionary into a model but I don't know how to do it I would be really thankful if you explain me how can I do it This is the list [{'evolution': 'charizard', 'height': 11, 'id_pokemon': '5', 'name': 'charmeleon', 'stats': [[80, 'speed'], [65, 'special-defense'], [80, 'special-attack'], [58, 'defense'], [64, 'attack'], [58, 'hp']], 'weight': 190}, {'evolution': 'charmeleon', 'height': 6, 'id_pokemon': '4', 'name': 'charmander', 'stats': [[65, 'speed'], [50, 'special-defense'], [60, 'special-attack'], [43, 'defense'], [52, 'attack'], [39, 'hp']], 'weight': 85}, {'evolution': 'None', 'height': 17, 'id_pokemon': '6', 'name': 'charizard', 'stats': [[100, 'speed'], [85, 'special-defense'], [109, 'special-attack'], [78, 'defense'], [84, 'attack'], [78, 'hp']], 'weight': 905}] #_____________________________________ #And i want to save it on this model class Pokemon(models.Model): """Database model for pokemon information""" id_pokemon = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) weight = models.IntegerField() height = models.IntegerField() special_defense = models.IntegerField() special_attack = models.IntegerField() defense = models.IntegerField() attack = models.IntegerField() hp = models.IntegerField() speed = models.IntegerField() evolution = models.IntegerField() -
Django Rest-Framework During Validation, Check the Request Method Type
I am working on API Validation Errors to be called. I have to make sure 2 dates don't overlap when making new "POST" calls, which is working fine. I am doing a model.objects.Filter() query and if anything gets returned, I return a validation error. However, I want to return this error only during POST requests. I have tried if request.method == "POST": do something but I get errors under the "request" word saying "request" is not defined. is there another way to check the Method Type during validation? I am doing this in my serializer. Thanks! -
AttributeError: 'int' object has no attribute 'pk' - Django
I'm trying to return a very simple serialised queryset and I get this error: AttributeError: 'int' object has no attribute 'pk' Models: class Portfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) class Image(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) portfolio = models.ForeignKey(Image, related_name="images", on_delete=models.CASCADE) thumb = models.URLField(blank=True, null=True) View: class PortfolioViewSet(viewsets.ModelViewSet): serializer_class = serializers.PortfolioSerializer queryset = models.Portfolio.objects.all() permission_classes = (permissions.IsAuthenticated, core_permissions.IsMineOnly) def get_queryset(self): portfolios = self.request.user.portfolio_set.all() ser = self.serializer_class(portfolios, many=True) data = ser.data return data serialisers: class PortfolioSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True) class Meta: model = models.Portfolio exclude = ('user',) class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' I read this answer that says we should use validated_data after calling is_valid() first but I don't serialise data but a queryset so I can't call this method. -
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 …