Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What can cause MultiValueDictKeyError in Django?
i almost finished my register form, but something went wrong and i totally don't know what. It is a little difficult to describe but i will try. So, as you can see here is login form: login.html <h1>login page</h1> <table> <tr><a href="register.html">return to register page</a><br> </tr> <tr><a href="index.html">return to home page</a> </tr> </table> <br> <div> <form method="post"> {% csrf_token %} <div> <div><label>Login/Email </label><input type="text" name="login_name" placeholder="Login/Email"></div> <div><label>Password </label><input type="password" name="login_password" placeholder="enter password"></div> <div><input type="submit" value="Login"></div> </div> </form> </div> and here is register form: register.html <h1>Register page</h1> <table> <tr><a href="login.html">return to login page</a> <br></tr> <tr><a href="index.html">return to home page</a> </tr> </table> <br> <div> <form method="POST"> {% csrf_token %} <div> <div><label>Name </label><input type="text" name="registerFrom_name" placeholder="Enter the name"></div> <div><label>Surname </label><input type="text" name="registerFrom_surname" placeholder="Enter the surname"></div> <div><label>Login/Email </label><input type="text" name="registerFrom_login" placeholder="Login/Email"></div> <div><label>Password </label><input type="registerForm_password" name="registerFrom_password" placeholder="Enter password"></div> <div><label>Email </label><input type="text" name="registerForm_email"></div> <div><input type="submit" value="Register"> </div> </div> </form> </div> Bellow my own backend to handle froms: view.html # BACKEND from django.shortcuts import render from django.views import View from . import ValidateUser, RegisterUser # Create your views here. CSRF_COOKIE_SECURE = True class WebServiceView(View): # INDEX - MAIN PAGE def indexPage(self, request): return render(request, "index.html") def register(self, request): res = RegisterUser.RegisterUser("user", "user", "login", "test", "emai@email") res.createUser() return … -
Heroku error code H10, not sure what's going on
I'm still a newbie at all this, so I'm not sure what's going on. Been going through the PCC book by Eric Mathes, which is great, but, I've run into some errors here and there even when following the book to a tee due to perhaps using version 1 of the book and not the newest, version 2. Anyhow, I've been trying for days now to figure this h10 error out and I don't understand what's going on here. When I do 'Heroku open', I get an application error and when I investigate, this is what I get: Thanks in advance! (11_env) Rezas-MacBook-Pro:learning_log papichulo$ heroku logs --tail 2019-10-04T09:29:06.956667+00:00 heroku[web.1]: Process exited with status 3 2019-10-04T09:41:27.299718+00:00 heroku[web.1]: State changed from crashed to starting 2019-10-04T09:41:32.445405+00:00 heroku[web.1]: Starting process with command `gunicorn learning_log.wsgi --log-file -` 2019-10-04T09:41:35.802943+00:00 heroku[web.1]: State changed from starting to up 2019-10-04T09:41:35.155219+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-10-04T09:41:35.157841+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [4] [INFO] Listening at: http://0.0.0.0:11830 (4) 2019-10-04T09:41:35.158031+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [4] [INFO] Using worker: sync 2019-10-04T09:41:35.163938+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [10] [INFO] Booting worker with pid: 10 2019-10-04T09:41:35.181361+00:00 app[web.1]: [2019-10-04 09:41:35 +0000] [11] [INFO] Booting worker with pid: 11 2019-10-04T09:41:36.545969+00:00 heroku[web.1]: State changed from … -
Access to Postgres DB within container not working from localhost
Below is my docker-compose file. I'm not sure what I'm missing. But I'm not able to connect to the postgres from my localhost dev_db: image: postgres volumes: - ./db_data/postgres:/var/lib/postgresql/data expose: - "5432" ports: - "5433:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 10s timeout: 5s retries: 5 logging: driver: "json-file" options: max-size: "100m" max-file: "3"``` psql cmd fom loclhost ``` sitharamk$ psql -h localhost -p 5433 -U postgres -W Password: psql: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5433?``` -
How can I call the same methode calling different class inheritence in django?
I think my title might not be very clear but i don't know how to articulate it. I am using Django I have a class "spending" with different inheritance class "vehicules" and "products". I have an other class "project" that has a method callin the "spending" class to kwow what i have been spending on and how much. can i use this same method "vehicule" or "products" to get the same information but just for theese classes? -
Django rest framework ```TypeError: type object argument after ** must be a mapping, not int``` being thrown
I have a SMSMessages model that will contain all the sms sent.I'm trying access via the django-rest-framework ListCreateAPIView class, but I keep on hitting error when I try to do an OPTION request on the api via Insomnia, TypeError at /smsmessages/ type object argument after ** must be a mapping, not int. I searched on SO and found similar errors but they were caused b/c of a filter() argument, which doesn't apply to this. I'm using django 2.2.5, python 3.6.8, django-rest-framework 3.10.3 and a mysqlclient 1.4.4. this is the model of SMSMessages from django.db import models from django.contrib.auth.models import AbstractUser from rest_framework.authtoken.models import Token class SMSMessages(models.Model): sms_number_to = models.CharField(max_length=14) sms_content = models.CharField(max_length=160) sending_user = models.ForeignKey("SMSUser", on_delete=models.PROTECT, related_name="user_that_sent", limit_choices_to=1) sent_date = models.DateTimeField(auto_now=True) delivery_status = models.BooleanField(default=False) class Meta: verbose_name_plural = "SMSMessages" def __str__(self): return self.sending_user and this is this the urls.py file: from django.urls import path from rest_framework.authtoken import views from rest_framework.routers import DefaultRouter from notification.apiviews import SMSendView, SMSMessagesView app_name = "notification" router = DefaultRouter() urlpatterns = [ path("smsmessages/", SMSMessagesView.as_view(), name="sms_messages"), ] so the way I access it is by sending an OPTION request to http://localhost:8000/smsmessages/. This the SMSMessagesview class that is used for the api view: from rest_framework import generics, status, … -
Uses of for row loop in template
I searched in the docs but could not find tag mentioned below . I want to know where can we use it and Please provide link so i can read more about this tag. {% for row in qs %} {{ row.total_income }} {% endfor %} -
my django code displaying html tags as text
I have been developing an app using python django and beautifulsoup. I want show product data in a html page. but as I return the result with html tags in the html file it's display html tags inside of quotation. here is the image of result that I get I tried many different methods but result are same. I really don't figure out what's the issue maybe my methods are wrong, please help. my codes are below: #myscraper.py def prdTmplt(imgsrc, title, price, link): w = '' w += '<div class="search-img-div">' w += '<img src="'+imgsrc+'">' w += '</div><div class="search-info-div">' w += '<a href="'+link+'"><h3>'+title+'</h3></a>' w += '<span>'+price+'</span>' w += '</div>' return w def scrapeData(query): """ Some unnecessary codes..... """ items = soup.find('ol', {"class":"sku-item-list"}) prdList = [] for item in items.find_all("li", {"class":"sku-item"}): """ scarping data from soup..... """ prdList.append(Scraper.prdTmplt(imgsrc, title, price, link)) allProduct = prdList return HttpResponse(allProduct) #views.py def search(request): context = {} """ my other codes """ context['bb'] = Scraper.scrapeData(search_query) return render(request, 'pages/search.html', context) #views.html <div class="row mt-4"> {% for prd in bb %} {{prd}} {% endfor %} </div> I am beginner at python so, please help me to solve this. -
Retrieve record from two Django models in single template
I'm trying to retrieve the records from two Django models. The retrieval should be like all records from first model and then records from second models based on the username of first models's username. Models are: class Nodes(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, default=1) node_name = models.CharField(max_length=50) node_mob = models.PositiveIntegerField() node_image = models.ImageField(upload_to='nodes_pics/', blank=True) def __str__(self): return self.user.username class DocchainUser(models.Model): docchainuser = models.OneToOneField(User, on_delete = models.CASCADE) address = models.CharField(max_length=64,unique=True) def __str__(self): return self.address Views are: def universityUsers(request): queryset = Nodes.objects.all() context = { 'user_list': queryset, } return render(request,'universityUsers.html',context) Templates: {% for p in user_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ p.node_name }}</td> <td>{{ p.user.email }}</td> <td>{{ p.node_mob }}</td> <td> ADDRESS FROM DOCCHAINUSER MODEL </td> </tr> {% endfor %} I want to retrieve the address from DocchainUser model based on the username from Nodes model. Example: test username exists in both the models. I am supposed to retrieve the record from both the models for test user. And same for all the other users. How it can be done? I'm stuck here. Thanks in advance! -
Modify django admin form "save and add another" function
In my admin forms I have some default submit actions e.g. "save", "save and continue", "save and add another". I want to modify the last one adding some prepopulated fields, so the form will open with some fields filled according to the previous object. Is there a way to do so? -
Scrapy Item pipelines not enabling
I am trying to set up a Scrapy spider inside Django app, that reads info from a page and posts it in Django's SQLite database using DjangoItems. Right now it seems that scraper itself is working, however, it is not adding anything to database. My guess is that it happens because of scrapy not enabling any item pipelines. Here is the log: 2019-10-05 15:23:07 [scrapy.utils.log] INFO: Scrapy 1.7.3 started (bot: scrapybot) 2019-10-05 15:23:07 [scrapy.utils.log] INFO: Versions: lxml 4.4.1.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.7.0, Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)], pyOpenSSL 19.0.0 (OpenSSL 1.1.1c 28 May 2019), cryptography 2.7, Platform Windows-10-10.0.18362-SP0 2019-10-05 15:23:07 [scrapy.crawler] INFO: Overridden settings: {} 2019-10-05 15:23:07 [scrapy.extensions.telnet] INFO: Telnet Password: 6e614667b3cf5a1a 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2019-10-05 15:23:07 [scrapy.middleware] INFO: Enabled item pipelines: [] 2019-10-05 15:23:07 [scrapy.core.engine] INFO: Spider opened 2019-10-05 15:23:07 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2019-10-05 15:23:08 [scrapy.extensions.telnet] INFO: Telnet console … -
How to have a listbox with 'add' and 'remove' buttons as a field in Django admin panel
It is rather easy to store a list of strings (csv for example) in Django models using fields such models.TextField or models.CharField; but is there any module or method that can render that list as a listbox in Django admin panel (probably with add and remove button besides the listbox)? -
Vue Warn: property "search" is not defined on instance
i'm creating a web app with a Django server with api from rest_framework and Vue as frontend (Nuxtjs in particular). Trying to create a "search filter bar" i've got this error and i don't know why: ERROR [Vue warn]: Property or method "search" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. This is my file.vue <template> <div> <v-text-field v-model="search" label="search conditions" outlined dense></v-text-field> </div> <div> <v-list v-for="condition in filteredConditions" :key="condition.id" > <v-list-item> <condition-card :onDelete="deleteCondition" :condition="condition"></condition-card> </v-list-item> </v-list> </div> </div> </template> <script> import ConditionCard from "~/components/ConditionCard.vue"; export default { head() { return { title: "Conditions list", search: "" }; }, components: { ConditionCard }, async asyncData({ $axios, params }) { try { let query = await $axios.$get(`/conditions/`); if (query.count > 0){ return { conditions: query.results } } return { conditions: [] }; } catch (e) { return { conditions: [] }; } }, data() { return { conditions: [] }; }, ... ... computed: { filteredConditions: function(){ return this.conditions.filter((condition) => { return condition.name.toLowerCase().match(this.search.toLocaleLowerCase()) }); } } }; </script> <style scoped> </style> The api is: {"count":15, "next":null, "previous":null, … -
Encoding error when trying to open json file from django app
I have a json file in the same directory with my app where i have saved some names and passwords. When a user clicks a button, i m trying to retrieve these data and compare it with the input he gave. However, i get an encoding error JSONDecodeError: Expecting value: line 1 column 1 (char 0) The thing is i can normally run the code and read from the json without problems when i dont use Django, so it has to do with it probably. I tried adding errors='ignore' and change encoding withotu succcess My login function which opens the json file: def login(name,password): with open('data.json', 'r', encoding='utf-8', errors='ignore') as f: try: data = json.loads(f.read()) print(data) except ValueError: # includes simplejson.decoder.JSONDecodeError print('Decoding JSON has failed') return False f.close() -
Do checkboxes have to be under one div to work properly?
I have some checkboxes which are generated dynamically with django template. Some of them are under one div and some under another. When making the first or last one required and clicking submit on my form it says that at lease one of the checkboxes from the second div has to be checked and vice versa. The name of the checkboxes are the same. Here's the code <div class="row"> <div class="col"> {% for value in key.categories %} #code.. if first half of items <input type="checkbox" name="{{ key.id }}[]" value="{{ value.id }}" id="{{ value.id }}"> <label for="{{ value.id }}">{{ value.value }}</label><br> #code.. if middle item <input type="checkbox" name="{{ key.id }}[]" value="{{ value.id }}" id="{{ value.id }}" required> <label for="{{ value.id }}">{{ value.value }}</label><br> </div> <div class="row"> #code.. if second half of items <input type="checkbox" name="{{ key.id }}[]" value="{{ value.id }}" id="{{ value.id }}"> <label for="{{ value.id }}">{{ value.value }}</label><br> {% endfor %} </div> </div> As stated on the question, my question is whether the checkboxes have to be under one div. If so, how can I print the items in two columns of the same length? -
cant see my blog post on my django website
im trying to follow this django tutorial, there a three section on my website called home blog and content. what should happen, is i click on blog and it list out the blog post i made in the admin and i can click on the post and read what the blog post says, but when i click on blogs nothing shows up, its just blank. i have already installed apps in settings i added the url in the url.py folder urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), I went into the models folder and created a model from django.db import models class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __str__(self): return self.title in my blogs/urls folder i have from django.conf.urls import url, include from django.views.generic import ListView, DetailView from blog.models import Post from django.urls import path urlpatterns = [ path('', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="blog/blog.html")), path('<int:pk>/', DetailView.as_view(model=Post, template_name='blog/post.html'))] in my blog folder i made a new directory called templates and in templates i made another directory called blog and in the folder i made an html file called blog.html and it is in a notepad++. this is what is in that blog.html notepad {% extends "personal/header.html" %} … -
Searching data stored in Dictionary and Display in same HTML document
This is attendance.html file I want to display details of the student on the right side, searched as per their Class and Roll number displayed on the left column ( from a dictionary) Searched data is to be displayed here on click of search button.(on the same page) HTML code : <HTML> <BODY bgcolor='cyan'> {% block content %} Showing student data ... <br><br> <div> <table style="width:100%"> <td> <table border=1 align=center> <tr> <th>Roll</th><th>Class</th><th>Student name</th><th>Father's name</th> {% for record in records %} <tr> <td>{{record.RollNo}}</td><td>{{record.ClsName}}</td><td>{{record.StudentName}}</td><td>{{record.FatherName}}</td> </tr> {% endfor %} </table> </td> <td> <form action="#" method="POST"> {% csrf_token %} Select your class : <select name="class"> <option value="IX">IX</option> <option value="X">X</option> <option value="XI">XI</option> <option value="XII">XII</option> </select> Enter roll number :<input type="text" name = "roll" size="4"/><br><br> <button type="button">Search student</button> <br> <br> Date : {{ mydate }} Select <b>(if present)</b> <input type="checkbox" name ="attd" value="1"/> <button type="submit" name="submit">Submit data</button> </form> </td> </table> </div> {% endblock %} </BODY> Code in views.py def output(request): with open('./studata.csv', 'r') as csvfile: csv_file_reader = csv.DictReader(csvfile) records = list(csv_file_reader) mydate = datetime.datetime.now() return render(request,'attendance.html',{'records':records,'mydate':mydate}) studata.csv file :- StudentName,FatherName,ClsName,RollNo Nancy Saha,Kuch Bhi Saha,XII,46 Maitreyee Sarkar,Nahi Pata Sarkar,XII,32 Ayush Gupta,Unknown G,XII,45 Tapan Gogoi,Mr Gogoi,X,11 Nirmit Chaliha,Mr Chaliha,IX,29 After the name of the student is displayed I … -
Django, setting custom password field after creating a custom user model from existing database table
I have to integrate my application with an existing one. The user table in the existing database (postgresql) is this: code: Integer (Primary key) login: varchar (actual username) pwd: varchar (the password field) I ran a python manage.py inspectdb and modified the auto-created model like this: class LegacyDBUsers(AbstractBaseUser): code = models.AutoField(primary_key=True) login = models.CharField(max_length=255) pwd = models.CharField(max_length=255) objects = MyUserManager() USERNAME_FIELD = 'login' REQUIRED_FIELDS = ['login', 'pwd'] class Meta: managed = False db_table = 'legacy_db_users' Created MyUserManager() as per documentation (https://docs.djangoproject.com/en/2.2/topics/auth/customizing/) and added AUTH_USER_MODEL in settings.py when I try to authenticate like this: user = authenticate(username="test", password="123") I get this error: django.db.utils.ProgrammingError: column legacy_db_users.password does not exist How can I set the 'pwd' column to be the 'password' column? -
Django rest serializer JSON field sets field to None on valid data
I have a model named project that contains a JSON field named pilot_circles, I am trying to patch that field using a detail_route view, and a model serializer that only contains that field. When the serializer is provided with invalid data, which is invalid JSON, the response is 400 then, but when the provided data is valid, the value of pilot_circles in the validated_data dict is None. here is my detail_route view: @detail_route( methods=['PATCH'], serializer_class=PilotCirclesSerializer,) def my_view(self, request, pk=None): project = self.get_object() serializer = self.get_serializer(project, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializer: class PilotCirclesSerializer(serializers.ModelSerializer): pilot_circles = serializers.JSONField() class Meta: model = Project fields = ('pilot_circles',) model field: from jsonfield import JSONField pilot_circles = JSONField(verbose_name='Pilot Circles', null=True, blank=True) test that's sending the data: def test_endpoint(self): valid_data = { 'circle_1': { 'long': 25, 'lat': 50, 'radius': 2}, 'circle_2': { 'long': 100, 'lat': 250, 'radius': 10} } self.assertIsNone(self.project.pilot_circles) response = self.client.patch(path=self.draw_guide_path, data=valid_data, format='json') self.assertEqual(200, response.status_code) self.project.refresh_from_db() self.assertIsNotNone(self.project.pilot_circles) I am using a 3rd party library called jsonfield, that helps with representing a json field in django models. I am using python 3.5.5, django 1.11 and djangorestframework 3.7.7 My question is: What is causing this behavior of having pilot_circles to be None in the validated … -
Impossible to export static in django production
I'm trying to put in production a website using nginx and gunicorn but after a lot of attempt, my css and js are not visable. The project root is /root/ouverture My static files root is /root/ouverture/coloc/static here it's what i have written in my settings.py STATIC_ROOT = "/static/" STATIC_URL = '/static/' here is my /etc/nginx/sites-available/coloc server { listen 80; server_name 51.91.111.135; root /root/ouverture/; location /static { root /root/ouverture/coloc/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://127.0.0.1:8000; } } Can you help me please, I don't see where is my error. Thank you -
Change readonly fields inside django adminmodels based on a condition
I need to Change readonly fields inside django adminModel based on a condition.. There is a BooleanField inside this mode. I want to check if it is valued is True then show a list of read-only field. if it is false should show another list. here is my ModelAdmin code: @admin.register(PurchaseRequest) class PurchaseRequestAdmin(admin.ModelAdmin): change_form_template = 'prc_custom_change_admin.html' form = PurchaseRequestForm ordering = ['-date_solicited'] # list_filter = (StatusFilter,) autocomplete_fields = [ 'project', 'budget', 'company', 'branch', 'location', 'management', 'effort_type' ] fieldsets = [ ('General', {'fields': [ 'project', 'budget', 'company', 'etp', 'branch', # 'region', # 'management', 'effort_type', 'observations', 'solution_description', 'justifications', 'provisioned_capex', 'contact_information' ]}), ('Status', {'fields': [ 'solicitor', 'date_solicited', 'analizer', 'receiver', 'issuer', 'approver', 'date_approval', ]}), ] readonly_fields = [ 'date_solicited', 'solicitor', 'approver', 'date_approval', ] inlines = [PRCItemInline, ] list_display = ( 'project', 'prc_status', 'check_analizer', 'approval_view', 'issued', 'received', 'installed', 'id', 'budget', 'company', 'branch', 'item_count', 'print_link') search_fields = ['items__product__product_code__oracle_code', 'branch__name'] list_filter = ( 'completed', 'is_received', 'is_approved', 'is_issued', ) list_per_page = 10 I've used get_readonly_fields to let admin able to change anything: def get_readonly_fields(self, request, obj=None): user = request.user if user.is_superuser: # Admin can change anything return self.readonly_fields return self.readonly_fields # + list(disabled_fields) but the problem is that i need to access the current changing object to check … -
DRF POST Request return 201 but nothing get's created
I'm trying to create a new Attendance object using the POST method through the python requests library. Here's part of my model: class Attendance(models.Model): class Meta: verbose_name = 'Attendance' verbose_name_plural = 'Attendances' work_employee = models.ForeignKey('Employee', on_delete=models.CASCADE, verbose_name='Employee') work_start_time = models.DateTimeField(verbose_name='Clock-in Time') work_end_time = models.DateTimeField(null=True, verbose_name='Clock Out Time') My standard serializer: class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields = ("work_employee", "work_start_time", "work_end_time") This is what my view looks like: class AttendanceView(viewsets.ModelViewSet): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = AttendanceSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) And here's my python code sending the request: timezone = "Europe/Berlin" tz = pytz.timezone(timezone) def add_attendance(employee_id): set_headers() #Gets the tokens, sets the headers timezone_now = datetime.now(tz) #Speaks for itself. #timezone_now = str(timezone_now).split("+")[0].split(".")[0] (Ignore this) now = datetime.strftime(timezone_now, "%Y-%m-%d %H:%M:%S") print(now) request = server + "/time/api/attendance/" #The url. response = req.post(request, data={"work_employee":employee_id, "work_start_time":now}, headers=headers["AUTH"]) return response print(add_attendance(2)) Now, I can tell you one thing that the headers are just fine and working dandy. I do get a 201 response and when I do the same thing using post man, it also returns the object just created. But when I … -
Django Djoser: Email address reset
I am using username for primary identification. However, users also have email addresses. I would like to know how can I set up "email address reset" so that users can change their email addresses. This functionality seems obvious to me but I did not find anything - am I missing something or maybe my approach is not correct? Oh, and I would like to keep the username as is, I just want to make it possible to change the email with confirmations etc. I think it is important to have an email sent to the new address first and only then change it. Any help will be much appreciated. Thank you in advance. -
How to define model clean method if a modelform does not include some fields of the model?
I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] IELTS_TYPE_CHOICES = [('General', 'General'), ('Academic', 'Academic'), ] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) overall = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) # This should be changed to autmoatic calculation or for validation exam_type = CharField(max_length=10, null=True, blank=True, choices=IELTS_TYPE_CHOICES, ) exam_date = DateField(null=True, blank=True, ) file = FileField(upload_to=student_directory_path, null=True, blank=True, ) student_ielts_non_empty_fields = \ { 'listening': 'please enter your listening score', 'reading': 'please enter your reading score', 'writing': 'please enter your writing score', 'speaking': 'please enter your speaking score', 'overall': 'please enter your overall score', 'exam_type': 'please enter your exam type', 'exam_date': 'please specify your exam date', } def clean(self): errors = {} if self.has_ielts: for field_name, field_error in self.student_ielts_non_empty_fields.items(): if getattr(self, field_name) is None: errors[field_name] = field_error if errors: raise ValidationError(errors) and have this modelform class StudentIeltsFilterForm(ModelForm): class Meta: model = StudentIelts exclude = ('file', 'exam_date', 'student', ) when I submit this form in template, I get the below error: ValueError at / 'StudentIeltsFilterForm' has no field named 'exam_date'. and During handling … -
Am i missing something?
cmd showing failed to push some refs to 'https://git.heroku.com/sibnathweb.git I have updated "setuptools" and done all the requirements in requirements.txt -
Azure login using Django webapp
So, here is my question's overview:- I basically want to login into azure account. I have created my azure login credentials from azure portal. And now i want to login into azure account but not from portal.azure.com site, I want to login through a webapp which i have developed using Django. I have a webapp developed which has login and password textbox on my django site, now i want to enter my azure credentials here on this webapp and it should also get logged in on azure portal, rendering azure portal after login is not necessary. Could anyone help me out here? Thank you in advance.