Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mail account used by django for password reset?
I am deploying my django project. Having secured a domain name, i am now at the stage of Implementing a proper password reset mechanism on the deployed site. I need to use an email service in order to do this, and having looked around, there seem to be many options for an email provider. I could use mailgun, or gmail, or even the people who sold my domain offer a couple of email addresses along with it. I was thinking i should maybe just go with gmail, as its free and forever, and probably pretty secure, probably reliable. Can someone who knows about these matters, please advise me on what email provider i should use, or any issues i may have overlooked. I glanced at mailgun, and it seems there is a limitation on amount of emails, so maybe that is a bad idea, i dont think gmail has a limitation. If so why do people use mailgun in the first place. Surely i must be missing something. Thanks in advance. -
I am creating a Basic authentication in Django Rest Framework in Django 2.1 version.But it shows '.authenticate() must be overridden' error
Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':('rest_framework.authentication.BasicAuthentication',), 'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAuthenticated',) } models.py from django.db import models class Emp(models.Model): eid = models.IntegerField() ename = models.CharField(max_length=30) sal = models.IntegerField() def __str__(self): return self.ename admin.py from django.contrib import admin from .models import Emp class AdminEmp(admin.ModelAdmin): list_display = ['eid','ename','sal'] admin.site.register(Emp,AdminEmp) serializers.py from .models import Emp from rest_framework import serializers class EmpSerializer(serializers.ModelSerializer): class Meta: model = Emp fields = ('eid','ename','sal') views.py from .serializers import EmpSerializer from .models import Emp from rest_framework import viewsets from rest_framework.authentication import BaseAuthentication from rest_framework.permissions import IsAuthenticated class EmpViewSet2(viewsets.ModelViewSet): authentication_classes = (BaseAuthentication,) permission_classes = (IsAuthenticated,) queryset = Emp.objects.all() serializer_class = EmpSerializer app level urls.py from django.conf.urls import url,include from .views import EmpViewSet2 from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('emp_viewset',EmpViewSet2,base_name='emp_viewset2') urlpatterns = [ url(r'',include(router.urls)) ] Project level urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('Basic_Authentication_App.urls')) ] Username and password window Django Rest Framework window but when i click on this link "emp_viewset":"http://127.0.0.1:3499/api/emp_viewset/" it shows like below: NotImplementedError at /api/emp_viewset/ .authenticate() must be overridden. -
Django leaflet map url
Hello guys I am creating a map and I would like to set up a dynamic url so that lets say when I run 127.0.0.1:8000/20.123, 42.123 and the map to pan in that certain location. I have certain workorders for certain layers and I would like that the user doesn't pan manually to map but the map pans itself by getting the coordinates of the layer. In order to achieve this I should set a url that consists the coordinates. It would be great if I can also display a certain zoom in the url lets say 13. index.html {% extends 'workorders/base.html' %} {% block jumbotron2 %} <div class="jumbotron"> <h1>Navbar example</h1> <p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position and moves with the rest of the page.</p> <a class="btn btn-lg btn-primary" href="../../components/navbar/" role="button">View navbar docs &raquo;</a> </div> {% endblock %} {% block content %} <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> {% leaflet_js %} {% leaflet_css %} <title>Map</title> <style type="text/css"> #gis {width: 100%;height:600px;} </style> <style type="text/css"> #map { width: 100%;height:725px; } </style> </style> <link rel="stylesheet" type="text/css" href="{% static 'dist/leaflet-groupedlayercontrol/leaflet.groupedlayercontrol.min.css' … -
django models save a table using json or any other method how to save in backend
Here is my html code i want to save this table in Django database but dont know how to do this i mean how to save in models i think json is work hear but i dont use json earlier for django models.py class Mvouchar(models.Model): related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True) bill_no = models.CharField(max_length=80, null=True, blank=True) bill_details = models.CharField(max_length=1000, null=True, blank=True) am = models.CharField(max_length=30, null=True, blank=True) views.py def mvouchar(request): if request.method == "POST": userdata = User.objects.get(username = request.user) accountdata = Signs.objects.get(relation_id=userdata.id) b_no = request.POST['billno'] b_details = request.POST['billdetails'] at = request.POST['amount2'] .css: table { width:50%; align: center; } table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 12px; text-align: left; } table#t01 tr:nth-child(even) { background-color: #eee; } table#t01 tr:nth-child(odd) { background-color: #fff; } table#t01 th { background-color: grey; color: white; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script src="jquery-1.10.2.js"></script> <script> var i = parseInt(0); var sum = parseInt(0); $(document).ready(function () { var i = parseInt(0); $("#Button1").click(function () { var name1 = $("#billNo").val(); var name2 = $("#billDetails").val(); var name3 = $("#amnt").val(); sum += parseInt(name3); var markup = "<tr id='" + i + "'><td>" + name1 + "</td><td>" + name2 + "</td><td>" + name3 + "</td><td><input id='Button" + i + "' … -
Dynamic Form With Autocomplete use jQuery
I use the Django framework for my Project .I want to "Add" the form bellow the old form. The form contain the input field that can "Autocomplete" use jQuery.This is my code... HTML <div id="history_education_form"> <div id="1" class="his_edu"> <div class="row"> <div class="col-sm-12"> <div class="input-group"> <span class="input-group-addon"> <i class="material-icons">school</i> </span> <div class="form-group label-floating"> <label class="control-label">Institute Name</label> <input type="text" class="form-control" name="edu_instituteName" id="institute2"> //This is the Autocomplete that I want to add </div> </div> </div> <div class="col-md-12 text-center"> <button type="button" id="1" class="btn btn-simple btn-xs btn_hisedu_remove"><i class="material-icons md-18 icon-delete">delete</i></button> </div> </div> </div> </div> <div class="col-md-12 text-center"> <div class="form-group"> <div class="col-md-12"> <p><button type="button" id="add_hisedu" class="btn btn-simple">Add More Institute</button></p> </div> </div> </div> The script in html <script> $( function() { $( "#institute2" ).autocomplete({ source: "{% url 'get_institute' %}", minLength: 1, }); } ); </script> This is JS code to append new form bellow the old form $(document).ready(function(){ var i=1; $('#add_hisedu').click(function(){ i++; var j=i+1; var append_text = ''; // Head (Filter Select + Add More button) append_text += 'bra....bra...<input type="text" class="form-control" name="edu_instituteName" id="institute'+j+'"bra... bra...'; $('#history_education_form').append(append_text); $( "#institute"+j ).each(function(){ $(this).autocomplete({ source: "{% url 'get_institute' %}", minLength: 1, }); }); }); // Remove w/ Jquery Style $(document).on('click', '.btn_hisedu_remove', function(){ var button_id = $(this).attr("id"); $.confirm({ title: 'Delete this History Education … -
Django-Filters with class-based views: Apply Django FilterSet dynamically
I am using django-filters for filtering data on Class Based Viewset. I am using a filter_class on the class-based view which does the initial filtering of the viewsets. And I have a separate filter which filters output on demand. filters.py class FilterOne(filters.FilterSet): title = filters.CharFilter(method=filter_booking_title) class Meta: model = models.Booking fields = [ 'title', 'state', 'client', ] class FilterTwo(filters.FilterSet): client = filters.ModelMultipleChoiceFilter(queryset=users_models.Client.objects.all()) state = filters.MultipleChoiceFilter(choices=constants.BookingState) camera_operator = filters.ModelMultipleChoiceFilter(queryset=users_models.UserManager.camop_users()) date_start = filters.DateFilter(name='date', lookup_expr='startswith') date_end = filters.DateFilter(name='date', lookup_expr='endswith') class Meta: model = models.Booking fields = [ 'state', 'client', 'camera_operator', 'date_start', 'date_end', ] api.py class MyViewSet( MultipleSerializerMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet ): lookup_field = 'uuid' queryset = models.Booking.objects.all() filter_backends = [filters.BookingFilterBackend, DjangoFilterBackend, ] filter_class = filters.BookingFilter pagination_class = BookingViewSetPagination serializer_class = serializers.BookingDetailSerializer serializer_classes = { ... } @list_route(methods=['POST'], url_path='export-bookings') def export_bookings(self, request, *args, **kwargs): queryset = self.get_queryset() // just some debugging code query_dict = request.data print(query_dict.get('state', [])) print(query_dict.get('clients', [])) print(query_dict.get('camera_operators', [])) print(query_dict.get('from_date', '')) print(query_dict.get('to_date', '')) // Apply the filter set - FilterTwo - on my model objects -> Booking. Something like this: // filtered_queryset = filters.FilterTwo(queryset, query_dict) - ?? return response.NoContent() However, I can't figure out how to write that statement which calls the FilterTwo with the query dictionary (received in the … -
Django: two tables or backref parameter
I have two model at the moment. class ServiceProvider(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=256) email = models.CharField(max_length=256) class Services(models.Model): plumbing = models.IntegerField(default=0) cleaning = models.IntegerField(default=0) handy_man = models.IntegerField(default=0) electrician = models.IntegerField(default=0) door_repair = models.IntegerField(default=0) fan_install = models.IntegerField(default=0) service_provider = models.ForeignKey( ServiceProvider, related_name="ServiceProvider", on_delete=models.CASCADE) I am able to get ServiceProvider from Services but how can I get Services while having ServiceProvider. Something like ServiceProvider.Services. There is a parameter in flask backref = true. It fulfill the task there but this is missing in django. -
How JWT works with django-phonenumber-field
I have used django-phonenumber-field as my Phone number model field and serializer. It worked and everything was okay. Now, I am trying to implement Json Web Token in Django Rest Framework of these two package, djsoer and djangorestframework-jwt. I am managing and migrating an old (django 1.11) codebase to Django2. Right now, whenever I am trying to create a new auth token, I am getting an internal server error. Error message: TypeError: Object of type 'PhoneNumber' is not JSON serializable I know PhoneNumber object from Django-phonenumber-field package is responsible for this. However, The error stack is in djangorestframework-jwt. How can I add/pass PhoneNumber serializer on JWT? [ I don't get which codebase is necessary, so I have not added any. Ask me, I will describe/add later.] TIA. -
Django Custom Auth Backend is_authenticated always false
Im writing an app where a user can login with 3 different informations: customerkey, username, password. Every customerkey leads to a seperate database. so i wrote a customauthbackend for it but run into a problem i cant really solve. The Authentication works fine as long as i hardcode the customerkey into the get_user function with return User.objects.using('505473').get(pk=user_id) but when i dont do that i always get false in my templates when i call {% if user.is_authenticated %}. Is there an option to say which db he needs to call when you call {% if user.is_authenticated %}? customAuthBackend: class CustomAuthBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): user = User.objects.using(request.POST['customerkey']).get(username=username) if user is not None: return user def get_user(self, user_id): try: return User.objects.using('505473').get(pk=user_id) except User.DoesNotExist: return None -
Getting FieldError in modelformset factory in django view.py
I am getting FieldError as : Unknown field(s) (notedate) specified for AssistantNotes When i call the page. It throws this error. I am using Django 1.9.5 and python 2.7. I have notedate field in the AssistantNotes table in my db. If i delete "notedate" from modelformset_factory row in my view, it works. I couldnt solve why it is not showing notedate although it is in DB and in model. And generating error. The field is already in the model. My view is : def edit_assistant_notes(request): isassistantsuperadmin = getUserPermissions(request) #Yes if 1, no if 0 list = getUserType(request) userisassistant = list[2] if userisassistant == "YES" or isassistantsuperadmin ==1: list = getUserType(request) type = list[0] usertype = list[1] #"Nöbetçi Muavin":1 , "Yetkili":2 if request.method == 'GET': if AssistantNotes.objects.filter(notedate=nicosia_date(datetime.today()).date()).count() == 0: AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('time', 'notedate', 'categories', 'type', 'dailynote',)) else: AssistantNotesFormsetFactory = modelformset_factory(AssistantNotes, fields=('time', 'notedate', 'categories', 'type', 'dailynote',), can_delete=True) if usertype == 1: formset = AssistantNotesFormsetFactory(queryset=AssistantNotes.objects.filter(notedate=nicosia_date(datetime.today()).date(), type=type)) elif usertype == 2: formset = AssistantNotesFormsetFactory(queryset=AssistantNotes.objects.all().order_by("notedate", "time")) helper = TableInlineHelper() return render(request, 'edit-assistant-notes.html', {'formset': formset, 'helper': helper}) My model is : class AssistantNotes(BaseModel): categories = models.CharField(choices=CATEGORIES, default="GENERAL", max_length=100, verbose_name=_("CAT")) time = models.CharField(choices=TIME, default="-------------", max_length=20, verbose_name=_("Time")) dailynote = models.TextField(null=True, blank=True, verbose_name=_("Add Note")) writer = models.TextField(null=True, blank=True, … -
Invalid data. Expected a dictionary, but got str error with serializer field in Django Rest Framework
I'm using Django 2.x and Django REST Framework. I have two models like class Contact(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, blank=True, null=True) modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class AmountGiven(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) contact = models.ForeignKey(Contact, on_delete=models.PROTECT) amount = models.FloatField(help_text='Amount given to the contact') given_date = models.DateField(default=timezone.now) created = models.DateTimeField(auto_now=True) the serializer.py the file has serializers defined as class ContactSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Contact fields = ('id', 'first_name', 'last_name', 'created', 'modified') class AmountGivenSerializer(serializers.ModelSerializer): contact = ContactSerializer() class Meta: model = AmountGiven depth = 1 fields = ( 'id', 'contact', 'amount', 'given_date', 'created' ) views.py class AmountGivenViewSet(viewsets.ModelViewSet): serializer_class = AmountGivenSerializer def perform_create(self, serializer): save_data = {} contact_pk = self.request.data.get('contact', None) if not contact_pk: raise ValidationError({'contact': ['Contact is required']}) contact = Contact.objects.filter( user=self.request.user, pk=contact_pk ).first() if not contact: raise ValidationError({'contact': ['Contact does not exists']}) save_data['contact'] = contact serializer.save(**save_data) But when I add a new record to AmountGiven model and passing contact id in contact field it is giving error as {"contact":{"non_field_errors":["Invalid data. Expected a dictionary, but got str."]}} When I remove contact = ContactSerializer() from AmountGivenSerializer, it works fine as expected but then in response as depth is set to 1, the contact … -
How Can we Create a plugin and Play Architecture in Django?
Actually, I want to create a plug and play architecture in Python Django. I have a different kind of scrappers and I am writing more scrappers too. Whenever I build a new scrapper I have to again publish my repo in production. What I need I just want to plug that new scrapper without actually again deploying my code. I have already used the GitHub versioning system but I am in need of a more clean way. Thanks in advance. -
django backend doesn't support absolute paths
I am working Crop Images in a Django Application using this tutorial Crop Images in Django Myform: class UploadImageForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) primaryphoto = forms.ImageField(required=False, error_messages={'invalid': _("Image files only")}, widget=forms.FileInput) class Meta: model = User fields = ['primaryphoto', 'x', 'y', 'width', 'height',] def save(self): user = super(UploadImageForm, self).save() x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(user.primaryphoto) cropped_image = image.crop((x, y, w + x, h + y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(user.primaryphoto.path) return user myview: def upload_image(request): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect('/profile') else: form = UploadImageForm(instance=request.user) return render(request, 'student/uploadimageform.html', {'form': form}) storage_backend.py: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False However, when I uploaded it to run on AWS, I got the error message that the backend does not support absolute paths (in reference to primaryphoto.path in the form where the photo is cropped). I was wondering what I have to change to get it working with S3. I've found some resources that say change primaryphoto.path to primaryphoto.name, but that hasn't worked for me. I was wondering if you had any … -
Variable not showing value in template tag
I have the following segment of code in view: image = [ 'register.png', 'checkin.png', 'checkin.png' ] imagetext = [ 'Register Patient', 'Checkin Patient', 'Checkin Patient' ] link = [ '/clinic/%s/register' % cliniclabel, '/clinic/%s/checkin' % cliniclabel, '/clinic/%s/checkin' % cliniclabel ] zipsidebarstuff = zip(image, imagetext, link) return render(request, 'clinic/cliniccurrent3.html', {'rnd_num': randomnumber(), 'clinic': clinicobj, 'checked_list': checkedin_list, 'patientcount': patientcount, 'type':'live', 'ClinicUserName': name, 'showhelp': helpneeded, 'NumUnconfirmedAppts': NumUnconfirmedAppts(clinicobj), 'zipsidebarstuff': zipsidebarstuff}) In my template I have: <div class="col-md-6"> <div class="sidebar-nav-fixed pull-right affix"> <div class="row"> <div class="d-inline-flex flex-row flex-wrap"> {% for image, imagetext, link in zipsidebarstuff %} <div class="p-2 bd-white"> <div class="d-inline-flex flex-column"> <div class="p-2 flex-fill bd-highlight"> <a href="{{ link }}"><img class="imgsidebtn" src="{% static 'clinic/img/{{ image }}' %}" /></a> </div> <div class="p-2 flex-fill bd-highlight"> <a href="{{ link }}" class="btn btn-primary">{{ imagetext }}</a> </div> </div> </div> {% endfor %} </div> </div> {% include "clinic/helpbar.html" with location="livelist" foo=bar %} </div> </div> The problem is in showing the tag <a href="{{ link }}"><img class="imgsidebtn" src="{% static 'clinic/img/{{ image }}' %}" /></a> in the rendered html. It is shown as: <a href="/clinic/jeslineye/checkin"><img class="imgsidebtn" src="/appointments/static/clinic/img/%7B%7B%20image%20%7D%7D"></a> Why is this happening? How can I fix this? -
Can I use unique_together on ManyToMany field?
I have a model Order which is manytomany to Site. In Django admin, I want to restrict the selection of sites(Site belong to existing Order can not be selected again). Can I do it with unique_together ? I get an error with following model ManyToManyFields are not supported in unique_together class Order(models.Model): description = models.CharField(max_length=255, blank=False) sites = models.ManyToManyField(Site) def __unicode__(self): return '' class Meta: unique_together = (('id', 'sites'),) -
How can I list the group names that only the authenticated user belongs to while editing a user on the Django's admin panel?
I am trying to find out to restrict the group names for an admin user on Django. There are two groups in the system; "School One" and School "Two". The picture below shows the users belonging only to the "School Two" group (including me as John Doe). For example, if I click the user "Josh Doe", I am directed to this page: What I want is to display the groups that the current authenticated user (John Doe) belongs only. That way I can assign a group (or groups) to a particular user. So, here I want to see only "School Two" option as I (John Doe) belong only to that group (added by superuser). How can I accomplish that? Let me share my source codes with you: admin.py file from django.contrib import admin from .models import User from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminCreationForm, UserAdminChangeForm class MyUserAdmin(BaseUserAdmin): form = UserAdminChangeForm add_form = UserAdminCreationForm list_display = ('email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_email_verified') def get_list_filter(self, request): if request.user.is_superuser: return ['groups'] else: return ['is_staff', 'is_active', 'is_email_verified'] readonly_fields = ('last_login', 'date_joined',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name','last_name')}), ('Permissions', {'fields': ('is_active','is_staff', 'groups')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), … -
Django translation makemessages missing #. in .po file
I'm experiencing syntax error when i run manage.py compilemessages. I opened the .po file and found out that some line doesn't have #: at the beginning of the line. he translation code was implemented correctly in the source file. It was replaced with a space. I've checked the source file's translation code and it was implemented correctly. What is causing this? Expected line code: #: .\source\of\the\file.py Actual line code: .\source\of\the\file.py Thanks in advance! -
How to display data in line by line in django
I am building a application in django using "ping command" and I want to display data in line by line into textarea such as using commmand in terminal. How can I do it ? -
Django creating model instances - Validation before creation? In manager class? What is manager class for?
Say I have a class "Book" and I want to hit an API to verify the book exists before creating my model. Do I create my "BookManager" class, override create, hit the api, and throw an exception if not valid or create if valid? Then in Book I'd write objects = BookManager() And create a book with. new_book = Book.objects.create(name)? Basically, this feels like a good way to organize my code, but I'm not sure if this is intended use for the Manager class as opposed to only modifying the queryset. Additionally, does anyone have a good reference on how to structure your django rest framework app? Folder structure etc -
Getting error when trying to migrate in django
Hey I'm trying to migrate my project using the command "python manage.py makemigrations" in django and I keep getting this error: File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax I have already found similar answers on it but nothing has worked. I am currently in the virtual environment already and changing the command to "python3 manage.py makemigrations" also prompts the same error. -
Chained Select/Dependent Drop-down in Django Admin
I have a model in Django, Model A. Very typical, it has various fields, some choice fields, some boolean, some character fields. I have another model, Model B, in this model, the intended functionality is that in Django Admin the first field is a select, where the user can choose from any field that exists in Model A. This is implemented already. What I need help figuring out is how to make the second field of Model B Mimic the options of Model A. If Model A has a choice field named 'Meat', and it's choices are 'Beef, Turkey, and Chicken', If the user adding an entry to Model B selects 'Meat' in field 1, field 2 will be a choice field with 'Beef, Turkey, and Chicken'. If Model A has a character field named 'Anything Goes', If the user adding an entry to Model B selects 'Anything Goes' in field 1, field 2 will be a standard text-input field. If Model A is a boolean field named 'Yes/No', If the user adding an entry to Model B selects 'Yes/No' in field 1, field 2 will be a standard boolean select field. I believe the main thing I'm looking for … -
Django Graphene - Pass info.context to a decorator on a Query or a Mutation
I am trying to pass a resolve function in a Query to a custom decorator. While **kwargs are getting passed to the decorator function, it looks like the info object is not getting passed. When I try to read the info in the decorator I get a value of None. Without the decorator, I am able to read the info object, directly in the resolve function. Please note the decorator shown below is a test code to read the info object and does not serve any other purpose. I understand there are defined decorators available in the django/graphene framework, but I'd like to understand how to pass the info object correctly to a decorator, for custom code. Thanks! Query class Query(object): all_users = graphene.List(UserNode) all_roles = graphene.List(UserRoleNode) @authenticate_role def resolve_all_users(self,info,*args,**kwargs): return User.objects.all() Decorator def authenticate_role(func): def wrap(info, *args, **kwargs): print (info) print(kwargs.get('id')) auth_header = info.context.META.get('HTTP_AUTHORIZATION') print (auth_header) return wrap -
Use of Global queryset in Django REST ViewSet Views/Actions
Concerning the following Django REST code: class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer When I try to use queryset in actions of this viewset, the following error is thrown: name 'queryset' is not defined The Django REST documentation states that queryset should be declared outside views/actions so it can be used by all of them. Is this not the case? Any help would be appreciated. Thanks. -
Django Database configuration file
I need to refer it from an external config file like 'NAME': 'name' instead of the actual database name DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD':'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Taking input in form and then comparing it with values stored in databse in django
!!URGENT!! I was working on a project where the user inputs the answer to the question and then the user input needs to be checked on clicking submit button. If input matches the answer stored in database in django.admin portal then it should redirect it to a new page else it should give an error wrong answer. Whats happening is that for every user input i am redirected to the other page. But never shows Wrong Answer even if input other than that in database answer is entered. how to tackle this?? forms.py from django import forms from .models import Answer from django.core.exceptions import ObjectDoesNotExist class CheckAnswer(forms.Form): your_answer=forms.CharField(label='Answer') def clean(self): cleaned_data=super(CheckAnswer,self).clean() response=cleaned_data.get("your_answer") try: p = Answer.objects.filter(answer__contains=response) except Answer.DoesNotExist: raise forms.ValidationError("Wrong Answer") models.py from django.db import models from django.contrib.auth import get_user_model User=get_user_model() users=User.objects.all() class Answer(models.Model): name=models.CharField(max_length=10,unique=True) answer=models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering= ["-name"] views.py from django.shortcuts import render,redirect from django.views.generic import * from . import models from django import forms from .forms import CheckAnswer def Arena1(request): if request.method=='POST': form = CheckAnswer(request.POST) if form.is_valid(): return redirect('thanks') else: form=CheckAnswer() return render(request,'levels/arena1.html',{'form':form})