Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Django OAuth toolkit on custom views
I've been using the Django OAuth toolkit to restrict access to my API. The problem is I'm not sure how to use it for my own views. It has it's own built-in "Application" views that I can see it works for but not sure how it can work for mine. I tried using their generic classes (https://django-oauth-toolkit.readthedocs.io/en/latest/views/class_based.html) but to no avail: views.py: class PostCarFax(ReadWriteScopedResourceMixin, ProtectedResourceView): queryset = CarFax.objects.all() serializer_class = CarFaxSerializer This gives me a AttributeError: type object 'PostCarFax' has no attribute 'get_extra_actions' error I wonder if it's the way it defines it's URLs? From their code: urls.py: from django.conf.urls import url from . import views app_name = "oauth2_provider" base_urlpatterns = [ url(r"^authorize/$", views.AuthorizationView.as_view(), name="authorize"), url(r"^token/$", views.TokenView.as_view(), name="token"), url(r"^revoke_token/$", views.RevokeTokenView.as_view(), name="revoke-token"), url(r"^introspect/$", views.IntrospectTokenView.as_view(), name="introspect"), ] management_urlpatterns = [ # Application management views url(r"^applications/$", views.ApplicationList.as_view(), name="list"), url(r"^applications/register/$", views.ApplicationRegistration.as_view(), name="register"), url(r"^applications/(?P<pk>[\w-]+)/$", views.ApplicationDetail.as_view(), name="detail"), url(r"^applications/(?P<pk>[\w-]+)/delete/$", views.ApplicationDelete.as_view(), name="delete"), url(r"^applications/(?P<pk>[\w-]+)/update/$", views.ApplicationUpdate.as_view(), name="update"), # Token management views url(r"^authorized_tokens/$", views.AuthorizedTokensListView.as_view(), name="authorized-token-list"), url(r"^authorized_tokens/(?P<pk>[\w-]+)/delete/$", views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete"), ] I guess I could define my own views there? Here's my urls.py: router = routers.DefaultRouter() router.register(r'post_carfax', views.PostCarFax) admin.autodiscover() from rest_framework import generics, permissions, serializers from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope urlpatterns = [ url(r'^api/v1/', include(router.urls)), url(r'^admin/', admin.site.urls), url('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), ] -
request.user.is_authenticated is always false in Django rest framework
I am using allauth for authentication in drf. I was able to register new users and login with the credentials. The login api return response something like this: { "key" : "<some token>" } Now I have 1 more API the code for which is from django.http import HttpResponse def lol(request): if request.user.is_authenticated: return HttpResponse("Authenticated") else: return HttpResponse("Not Authenticated") But this is always returning not authenticated my api call look like this Here is the list of installed apps in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', 'api.user', 'api.activity', ] -
Django return changed parameters in 200 response
I have this code that someone on the back-end team wrote. Sorry that my Django isn't that great class MerchantStampCardViewSet(viewsets.ModelViewSet): ''' A view set for listing/retrieving/updating/deleting stamp cards for the current merchant ''' permission_classes = (IsMerchantAndAuthenticated, ) def get_queryset(self): if len(MerchantProfile.objects.filter(user=self.request.user)) > 0: merchant_profile = MerchantProfile.objects.get(user=self.request.user) if merchant_profile.merchant: return StampCard.objects.filter(merchant=merchant_profile.merchant) return None def get_serializer_class(self): if self.request.method == 'GET': return StampCardSerializerWithRewards else: return StampCardSerializer He's currently busy with other things so I've taken over some of his responsibilities and I'm trying to figure out how to return the parameters changed in the 200 response when a successful patch call is made to this URL. Thanks! -
Not receive the hot and outlook mail on GCP using Send Grid
enter image description hereHello, Everyone! Looking for your kind and helpfull reply about my issue. My issue is like following: 1.I was create Django project on Google Compute engine. 2.And I was create the Goddady Domain. 3.I create the Send Grid free account. 4.So I was set the GCP "Cloud DNS" and Goddady "DNS Managements" and then Send Grid "Send Authentication". 5.But I can't send the email to Hotmail and Outlook mail. Right now, I can send the Gmail. please help me. Thanks. I will add some images for easy understanding. enter image description here enter image description here Please help me. -
json turns to a double quoted string - python django
I have a rather weird question: So, I have a simple dictionary in python, looking like so: {'Acoustics': {'Product Type': 'Acoustic Pod', 'Width [cm]': '1000', 'Noise Reduction Coefficient': '29 dB', 'Standards, Certification, and Documentation': 'PN EN-ISO 717-1:1999 ; EN 13501 B, s1, d0', 'Material': 'MDF ; Glass ; Acoustic composite', 'Color': 'NCS ; RAL', 'Installation Method': 'Own assembly ; Installation by the manufacturer', 'Facing Material': 'MDF ; Certified Paint', 'Type': 'Adjustable Ventilation ; Motion Sensor ; LED 6000K 2W ; 230V ; RJ45 or USB Charger ; Integrated seat and shelf'}} and I try to save this via django onto my pgSQL database (with jsonb column), and I somehow end up with (notice the double quote at the start and end): "{'Acoustics': {'Product Type': 'Acoustic Pod', 'Width [cm]': '1000', 'Noise Reduction Coefficient': '29 dB', 'Standards, Certification, and Documentation': 'PN EN-ISO 717-1:1999 ; EN 13501 B, s1, d0', 'Material': 'MDF ; Glass ; Acoustic composite', 'Color': 'NCS ; RAL', 'Installation Method': 'Own assembly ; Installation by the manufacturer', 'Facing Material': 'MDF ; Certified Paint', 'Type': 'Adjustable Ventilation ; Motion Sensor ; LED 6000K 2W ; 230V ; RJ45 or USB Charger ; Integrated seat and shelf'}}" So, now, I have two … -
Many HTTP 304 responses results in fewer GET requests
I have a Django development server hosting a web-page that real-time (ish) displays information gathered from numerous servers I watch over. This web-page is still in development, so I am currently using the built-in web host provided with Django, started on an Ubuntu host with: python3 manage.py runserver IP:Port On the same ubuntu host there is a python script continuously reaching out to the monitored servers and formatting the responses into a .html file which the client reloads within a <div> every minute. The general functionality of the page the client accesses is as follows: <div id="status" style="width:100%; height: 1000"></div> <script> $('#status').load("{% static 'alerts/status.html' %}"); setInterval(function() { $('#status').load("{% static 'alerts/status.html' %}"); }, 60000); </script> ...so the page loads the status.html file within the division on page-load, and then reloads it every minute. This has been working great, however, I have noticed looking at the Django log, that if status.html has not changed after ten status 304 (Not Modified) responses, the time waited between requests begins to roll-off. That is to say, instead of waiting 1 minute, it waits 2 minutes, then 5 minutes, and so on (roughly, I forget the actual rate of roll-off). Now the issue I'm facing is … -
Will setting gunicorn task setting to production mode mean that django will not run in DEBUG mode?
I have a gunicorn task running on my django application. The file looks like this: environment=IS_PRODUCTION="true",DJANGO_SETTINGS_MODULE="fn_django.settings.staging" In my settings file though, I have set DEBUG=false. Will my django application run in DEBUG mode as a result of what I wrote in my gunicorn settings file? -
Django and AWS S3: Static File Requests to Wrong URL
I'm trying to serve a Django 2.1 with Python 3.7 application with React 16.6 frontend to AWS Elastic Beanstalk. I build the React app using Create React App. So far I succesfully got the server running (I serve React's index.html via a TemplateView) and connected with the database. I'm now kinda stuck connecting the S3 bucket to my template view. Here is the issue: python manage.py collectstatic Worked correctly (when I access the default Django admin page the login is correctly styled), but when I try to access one of my React routes, the page is just blank. Using the chrome dev tools I was able to deduce that index.html was correctly loaded, but that the network request fails with: GET http://<my-eb-url>.elasticbeanstalk.com/static/js/main.a1cf6ce7.chunk.js net::ERR_ABORTED 404 (Not Found) So apparently the error is that Django doesn't look for React in the bucket, but in a relative file path. How can I change this? I mean the Python configuration should be good, since collectstatic worked. Here is React's index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="shortcut icon" href="/favicon.ico" /> <meta name="viewport" content="minimum-scale=1,initial-scale=1,width=device-width,shrink-to-fit=no" /> <meta name="theme-color" content="#000000" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700" /> <!-- <link rel="stylesheet" href="/fonts/fonts.css" /> --> <link rel="manifest" href="/manifest.json" … -
Does Django's get_queryset() in admin prevent malicious object saving?
I am developing a multi-tenant app in Django. In the Django admin, some querysets are filtered based on the user, using get_queryset(). Up till now, when a user updated an object from the Django change form, I would validate the data by creating a ModelAdmin form using a factory function to capture the HttpRequest object, then ensure that the Guest object's user was the current user: EXAMPLE models.py class Guest(models.Model): guest_name = models.CharField(max_length=64) user = models.ForeignKey(User, on_delete=models.CASCADE) admin.py @admin.register(Guest) class GuestAdmin(admin.ModelAdmin): def get_queryset(self, request) qs = super().get_queryset(request) return qs.filter(user=request.user) def get_form(self, request, obj=None, **kwargs): kwargs['form'] = _guest_admin_form_factory(request) return super().get_form(request, obj, **kwargs) forms.py def _guest_admin_form_factory(request): class GuestAdminForm(forms.ModelForm): class Meta: model = Guest exclude = [] def clean_user(self): user = self.cleaned_data.get('user', None) if not user: return user if user != request.user: raise forms.ValidationError('Invalid request.') return user return GuestAdminForm It occurred to me that Django might use the get_queryset() method to validate this for me, since some simple logging showed that the method is called twice when an object gets updated from the change form. Is this the case, or do I need to stick to validating through a ModelAdmin form? -
Checking for a member in a many to many set in django
I have the following user class, class User(AbstractBaseUser, PermissionsMixin, Base): email = models.EmailField(db_index=True, unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(db_index=True, null=False, unique=True, max_length=255) And I've the following room object, class Room(Base): name = models.CharField(db_index=True, unique=True, max_length=255) status = models.CharField(default=RoomStatus.ACTIVE, max_length=255, null=True) members = models.ManyToManyField(User) last_activity = models.DateTimeField(default=timezone.now) I'm trying to find if an user is present in the room as a member, user = User.objects.get(id=kwargs.get('user_id')) room = Room.objects.get(id=kwargs.get('room_id')) This doesn't work, member = room.members.filter(user=user) How can I do this correctly -
Why does Godaddy block Content Securuity Policy tags when using forward as mask?
It seems that the Content Securuity Policy (CSP) settings deployed in my Django app are filtered/removed when I forward to another server and use the "mask" option. Anybody know why? -
From windows linux subsytem could not connect windows 10 psql
I have install psql10 in my windows 10. It is installed successfully and running in port 5432 properly. From linux subsystem i am trying to connect my app with psql 10. But getting this error django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? One possible solution that i am thinking is to install psql in linux subsystem but i thought there might be way from that i can connect psql. I am a new user of windows10. -
How do I use TemplateHTMLRenderer for Create/Put in Django-REST-Framework?
I'm having a terrible time finding the right way to initialize the TemplateHTMLRenderer to render a form for creating an object. My API works perfectly, I can create a detail page using the docs and template packs, but I can't for the life of me initialize the same form to do the initial create. All attempts have the renderer asking for a PK. I need my PK to auto create. I don't want to have to manually write forms for creating objects when the code is there... but I'm completely at a loss. -
Django: access to user info from admin.py for methods with no request object?
Django 1.11. In admin.py I have: class AuditAdmin(DeactivateMixin, admin.ModelAdmin): """all the superclass stuff""" from which I subclass my model's stuff with various custom methods: class SomeModelAdmin(AuditAdmin): list_display = ["filed1", "filed2", "field3"] def get_queryset(self, request): if request.user.is_superuser: #do something extra def inline_add_somemodelattribute1(self, my_object): #how to access user if I don't have request ? So inside inline_add_somemodelattribute1 method I need to make decision based on the user but that method does not take request as an argument. How do I get my user data in this case? I did not find anything relevant in self or my_object Thanks -
Django + elpaginaton + ajax, didnt work detailview class
Simply my DetailView wont open new pages with enabled {% load el_pagination_tags %} {% lazy_paginate base_publications %} But, if i disable those tags everything works fine(except endless pagination ofc). Here an example: views.py class IndexPublication(AjaxListView): context_object_name = 'base_publications' template_name = 'Post/base.html' page_template='Post/base_list.html' def get_queryset(self, **kwargs): if self.request.method == 'GET': return Post_model.objects.order_by('-published_date') class PublicationDetail(DetailView): model = Post_model template_name = 'Post/post_detail.html' Base_list.html {% load el_pagination_tags %} {% lazy_paginate base_publications %} <ul class="grid-container"> {% for post in base_publications %} <li> <a class="navbar" href="{% url 'publications:detail_publication' pk=post.id %}"> <h3 class="title">{{ post.preview_title|linebreaks }}</h3> <p class="text">{{ post.preview_text|safe }}</p> </a> <img class='preview'src='{{ MEDIA_URL }}{{ post.preview_photo }}'> {{ post.published_date }} </li> {% endfor %} </ul> Post_detail.html {% extends 'Post/base.html' %} {% block content %} <div class="post"> {{ object.main_title }} {{ object.main_textbox|safe }} {% if object.published_date %} <div class="date"> {{ object.published_date }} </div> {% endif %} </div> {% endblock %} With el_pagination ive got an error if i try to click on my url. VariableDoesNotExist at /post/15/ Failed lookup for key [base_publications] in [{'True': True, 'False': False, 'None': None}, {}, {}, {'object': , 'post_model': , 'view': }] I`m kinda new for this. And give up on googling this problem. Thx for your assistance. -
Returning the last committed record
Concept: Display the last committed record to the database on a homepage. I'm using Django 2.0.6 and PostgreSQL database. The homepage is behind a user login and is not used for sensitive information. Is there a postgres way or a Django way? Additional request: Ideally I would like to be able to define which tables are used d]so the 'boring data' is filtered out. -
How to CRUD ContentType in Django admin site?
I'm reading a book about Django and I'm trying to reinterpret some content. In the book different types of contents are associated with a module, like this: class Module(models.Model): course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['order'] def __str__(self): return '{}. {}'.format(self.order, self.title) class Content(models.Model): module = models.ForeignKey(Module, related_name='contents', on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={'model__in': ( 'text', 'video', 'image', 'file')}) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['module']) class Meta: ordering = ['order'] class ItemBase(models.Model): owner = models.ForeignKey(User, related_name='%(class)s_related', on_delete=models.CASCADE) title = models.CharField(max_length=250) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True def __str__(self): return self.title def render(self): return render_to_string( 'courses/content/{}.html'.format(self._meta.model_name), {'item': self}) class Text(ItemBase): content = models.TextField() class File(ItemBase): file = models.FileField(upload_to='files') class Image(ItemBase): file = models.FileField(upload_to='images') class Video(ItemBase): url = models.URLField() In the book there are CBVs to generate the right form for content types: class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs) def … -
GDAL configuration for Django in virtualenv
I'm using windows and I'm trying to configure GDAL for Django, over the last 2 months. I have installed GDAL in C:\OSGEO4W64 Installed GDAL from the wheel file I've added the system variables: GDAL_LIBRARY_PATH = C:\OSGeo4W64\bin\ GDAL_DATA = C:\OSGeo4W64\share\gdal Any ideas where I'm going wrong? -
Django model field that's actually a reference to a field in a related model
Apologies in advance if this question is hard to follow – I'm not sure how to phrase it. Basically, I'm trying to create a sort of "pseudo-field" in a Django model that works exactly like any other Django field except that it's actually a reference to a field on a related model. As an example, suppose I am running a hotel for dogs. In my hotel, I have rooms, and each room is assigned to a customer and contains a dog. class Customer(Model): name = models.CharField(max_length=256, null=False) class Dog(Model): name = models.CharField(max_length=256, null=False) customer = model.ForeignKey(Customer, null=True, on_delete=models.CASCADE) # The dog's owner class Room(Model): customer = model.ForeignKey(Owner, null=True, on_delete=models.SET_NULL) dog = model.ForeignKey(Dog, null=True, on_delete=models.SET_NULL) The corresponding tables in the database look something like this CUSTOMER: | ID | NAME | ___________________ | 01 | John Smith | | 02 | Jane Doe | DOG: | ID | NAME | CUSTOMER_ID | ____________________________ | 01 | Rover | 01 | | 02 | Fido | 01 | | 03 | Spot | 02 | ROOM: | ID | DOG_ID | CUSTOMER_ID | _____________________________ | 01 | 01 | 01 | | 02 | 03 | 02 | So, my boss notices … -
Initial Values in Django model form
I am having a difficult time understanding the Django docs on this one. I have also come across some other threads with the same question, but I cannot seem to get the suggested answers to work for me. I think it is because I am posting text, and it is not considered "clean" data? I want to autofill two form fields, then when the user hits the submit button, it saves. But for some reason only the boolean value is working, not the text value. Any ideas? You will also see the fields are hidden from my template. When I show these fields, the initial values are set correctly as I expected, but when I hit submit, only the boolean is saved to database correctly. views.py class BuildStopView(LoginRequiredMixin,UpdateView): model = Build form_class = StopBuild template_name = 'build_stop.html' login_url = 'login' forms.py class StopBuild(forms.ModelForm): def __init__(self, *args, **kwargs): super(StopBuild, self).__init__(*args, **kwargs) self.initial['buildEndType'] = 'manuallyStopped' self.initial['buildActive'] = False class Meta: model = Build fields = ['buildEndType','buildActive'] (template) stop_build.html {% extends 'base.html' %} {% block body %} <style> div.a { text-align: center; } </style> <div class = "a"> <h3>Are you sure you want to stop this build manually?</h3> </div> <form action="" method="post">{% csrf_token … -
Access child model instances in parent model using related_name attribute in Django
Assuming the following configuration in my models.py, class Parent(models.Model): ...fields... @property def get_trone_heir_name(self): TODO: How to access to child models instances and fields? class MaleChilds(models.Model): parent = models.ForeignKey(Parent,on_delete=models.CASCADE,related_name="male_childs") name = models.CharField(max_length=100) birthday = models.DateTimeField() class FemaleChilds(models.Model): parent = models.ForeignKey(Parent,on_delete=models.CASCADE,related_name="female_childs") name = models.CharField(max_length=100) birthday = models.DateTimeField() I want to display Parent heir name, being the males prioritized over females and eldest over the youngest. I'm having difficulties on reaching the child objects in the parent property. How to refer to them? If I write: Parent.male_childs.all() I got the following exception: AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'all'. Best regards, -
I'm having hard time fetching data using request.POST.get()
I'm currently making a very basic dummy social networking site to learn Django, and I'm having trouble with request.POST.get() which is not fetching anything. As this way, I'm unable to have user inputs in my view.py. which means my site can't register any user. Please help me out as all of my further learning depends upon fetching user input. My coding is like (i know it's very basic and could look messy or somewhat outdated, sorry for that): models.py: class Users(models.Model): First_Name = models.CharField(max_length=200) Last_Name = models.CharField(max_length=200) Email = models.CharField(max_length=250) Password = models.CharField(max_length=250) Gender = models.CharField(max_length=250) flag = models.IntegerField(default=0) views.py: def register_user(request): user = Users() user.First_Name = request.POST.get('firstName') user.Last_Name = request.POST.get('lastName') user.Email = request.POST.get('email') user.Password = request.POST.get('password') user.Gender = request.POST.get('gender') user.save() When this code is run, no data entry is made. Whereas, if I run this method from shell using static values, it works fine. Thanks in advance -
django pre_save validation on m2m (many to many) fields
Apologies if this has been answered before but have been searching for hours. I am trying to do validation on a django rest model with a m2m field. I have a model that has roles assigned to it. I have some logic if the roles overlap with exisiting models and would like to throw a validation error. I have tried a pre_save signal but apparently django does not assign m2m until after save (no id). How do I access the data pre_save? Here is the model: class ActivityFactory (models.Model): """ This provides an interval over which ActivityDemands are auto-generated and ActivityStudyHours (note that activity study hours can be obsolete as all of the same information is already stored here) instead of the traditional method of inputing ActivityDemands per month. The product of Activity and ActivityDemand will still create StudySiteWorkloads. """ start_date = models.DateField() end_date = models.DateField() hours = models.DecimalField(max_digits=5, decimal_places=2) notes = models.TextField(blank=True, null=True) activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='activity_factories') roles = models.ManyToManyField(Role, blank=True, related_name='activity_factories') study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name="activity_factories") trend_curve = models.ForeignKey(TrendCurve, on_delete=models.CASCADE, related_name="activity_factories") slug = AutoSlugField(populate_from='study', db_index=True, unique=True, null=True) class Meta: verbose_name_plural = 'Activity Factories' def __str__(self): return "%s: %s : %s" % (self.study.study_name, self.activity.activity_name, self.trend_curve.denominator_name) @property def study__study_name(self): … -
Unable to link from one app to the another
I am trying to route from app Home to app Services using the following : <li><a href="{% url 'services.index' %}">Our Services</a></li> Services app: urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] view from django.shortcuts import render from django.http import HttpResponse def index(request): context = {} return render(request, 'services/index.html', context) Unfortunately I get error as: Exception Type: NoReverseMatch Exception Value: Reverse for 'services.index' not found. 'services.index' is not a valid view function or pattern name. In settings.py I have set the app in INSTALLED_APPS and also set templates folder for it. When visiting http://127.0.0.1:8000/services/ it works totally fine. -
Adding a favicon to template on Django
I want to put a favicon in the base.html in my Django project, but it doesn't seems to work. It doesn't display any errors in the browser console, but I don't get the "GET" message in python manage.py runserverconsole. <link rel="icon" href="{% static 'assets/img/favicon.ico' %}"/> Other static files such as JS and CSS are working just fine. Here is my directory print: 1 And my python shell print: 2