Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
post() missing 1 required positional argument: 'request'
I have a problem with the registry. And it is that when I make the request through postman it throws me the error: post () missing 1 required positional argument: 'request' My url: from .views import UserRegistrationView urlpatterns = [ path('register', UserRegistrationView.post), ] Url include: urlpatterns = [ path('admin/', admin.site.urls), path('api/user/', include('user.urls')), ] My View from rest_framework import status from rest_framework.generics import CreateAPIView from rest_framework.response import Response from rest_framework.permissions import AllowAny from .serializers import UserRegistrationSerializer from rest_framework.decorators import api_view class UserRegistrationView(CreateAPIView): permission_classes = (AllowAny,) @api_view(('POST',)) def post(self, request): serializer = UserRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() status_code = status.HTTP_201_CREATED response = { 'success' : 'True', 'status code' : status_code, 'message': 'User registered successfully', } return Response(response, status=status_code) My post by Postman: url: http://127.0.0.1:8000/api/user/register Body (raw): { "email":"asdf@asdf.com", "password":"123456", "profile": { "first_name": "asdf", "last_name": "asdf", "phone_number": "622111444", "age": 38, "gender": "M" } } My Error: TypeError at /api/user/register post() missing 1 required positional argument: 'request' -
Permission error with pymemcached and Django 2.2
I am updating a project to Django 2.2.3 from 2.1 and having issue (permission error) when I change from the python-memcached to the pymemcached binding. I can still use python-memcached which works but is deprecated in 2.2. My Memcached setting are (from Ansible): memcached_socket_perms: 775 memcached_socket_file: /run/memcached/memcached.sock memcached_memory_cap: 128 memcached_dependencies: - memcached memcached_user: memcache The asgi server runs under www-data under Ubuntu 20.04. I am using the Django cache setting from the Django docs (here for pymemcached): CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': 'unix:/run/memcached/memcached.sock', } } -
A sequential scan rather than index scan
I can't figure out why this query is exceptionally slow on my production database. I see two sequential scans - the first is from a filter on the dockets_table.content_type_id = 2 and the second one I can't even figure out what it's related to. This query takes many minutes on production machine and needs to be like a few seconds max. The query: SELECT DISTINCT ON (rank, "dockets_document"."id") "dockets_document"."id", "dockets_document"."title", "dockets_document"."url", "dockets_document"."content", "dockets_document"."num_tables", "dockets_document"."num_pages", "dockets_document"."tables_processed", "dockets_document"."summary", "dockets_document"."importance", "dockets_document"."title_vector", "dockets_document"."search_vector", "dockets_document"."datetime_created", "dockets_document"."datetime_modified", "dockets_document"."docket_id", "dockets_document"."docket_number", "dockets_document"."date_filed", "dockets_document"."pdf", ((1 * ts_rank("dockets_document"."search_vector", plainto_tsquery('public.bb'::regconfig, 'rendering set'))) + (0.8 * ts_rank("dockets_attachment"."search_vector", plainto_tsquery('public.bb'::regconfig, 'rendering set')))) AS "rank", ts_headline("dockets_document"."title", plainto_tsquery('public.bb'::regconfig, 'rendering set'), 'StartSel=''<mark>'', StopSel=''</mark>'', HighlightAll=true') AS "title_snippet", ts_headline(CONCAT(array_to_string("dockets_document"."content", ' ', ''), CONCAT(array_to_string("dockets_attachment"."content", ' ', ''), array_to_string(T4."content", ' ', ''))), plainto_tsquery('public.bb'::regconfig, 'rendering set'), 'StartSel=''<mark>'', StopSel=''</mark>'', MaxFragments=5') AS "content_snippet" FROM "dockets_document" LEFT OUTER JOIN "dockets_attachment" ON ("dockets_document"."id" = "dockets_attachment"."main_document_id") LEFT OUTER JOIN "dockets_table" ON ("dockets_document"."id" = "dockets_table"."object_id" AND ("dockets_table"."content_type_id" = 2)) LEFT OUTER JOIN "dockets_table" T4 ON ("dockets_attachment"."id" = T4."object_id" AND (T4."content_type_id" = 8)) WHERE ("dockets_document"."search_vector" @@ plainto_tsquery('public.bb'::regconfig, 'rendering set') OR "dockets_attachment"."search_vector" @@ plainto_tsquery('public.bb'::regconfig, 'rendering set') OR "dockets_table"."search_vector" @@ plainto_tsquery('public.bb'::regconfig, 'rendering set') OR T4."search_vector" @@ plainto_tsquery('public.bb'::regconfig, 'rendering set')) ORDER BY "rank" DESC, "dockets_document"."id" ASC LIMIT 8 Explain Analyze output: Limit … -
How to style a charfield which has choices in it django or which widget to use?
Okay so what I really want to do is to style a charfield which has choices from my forms.py modelform class. My models.py has this code it it... from django.db import models from django.contrib.auth.models import User # Create your models here. cat_choices = ( ("Stationary","Stationary"), ("Electronics","Electronics"), ("Food","Food"), ) class Product(models.Model): name = models.CharField(max_length=100,null=True) category = models.CharField(max_length=100, choices=cat_choices,null=True) quantity = models.PositiveIntegerField(null=True) class Meta: verbose_name_plural = 'Product' ordering = ['category'] and my forms.py has.... from django import forms from .models import Product class AddProduct(forms.ModelForm): class Meta: model = Product fields = ['name','category','quantity'] def __init__(self, *args, **kwargs): super(AddProduct,self).__init__(*args, **kwargs) self.fields['name'].widget = forms.TextInput(attrs={'type':'text','id':'name','name':'name','class':'form-control','placeholder':'Product Name'}) # self.fields['category'].widget = forms.Select(attrs={'class':'form-select'}) So I need a solution as to how I can style it or more appropriately which widget to use. I have already tried Select and it is not working. -
Keeping a file contents between page loads with Django
I am trying to create a page that reads information from a CSV file and then allows a user to run tests against the information in that CSV file. All of this is done on just a single page. This is my page layout: [Upload Form] [Upload Button] [Test Drop Down Selection Menu] [Data Input Text Area] [Parse Button] [Results] So basically you would upload a file. Then it would reload the page and populate the Test Drop down Selection Menu. Then you would select the test, paste the data in the text area and then click parse. Then it will display results underneath the Parse Button. Then I would like for the drop menu to still remain populated with tests so that the user can continue to just run tests and not have to continue uploaded the CSV file. This is my views.py function for this single page. def parse(request): form = CSVParseForm() if request.method == 'POST': if (request.FILES): csvfile = request.FILES.get('csv_file') reader = csv.reader(codecs.iterdecode(csvfile, 'utf-8')) tests = [] for row in reader: tests.append(row[3]) return render(request, 'cbsa/csvparse.html', {'form':form, 'tests' : tests}) else: # Read info from the session to know what to parse input_data = request.POST.get('cbstextarea') else: pass return … -
How to call View from another view in django?
I am creating a wizard using django-formtools. I have created a view for the wizard : class UserQueryWizard(SessionWizardView): template_name = "wizards/index.html" form_list = [forms.ShippingForm, forms.ExporterdetailsForm, forms.ImporterdetailsForm, ] def done(self, form_list, **kwargs): print([form.cleaned_data for form in form_list]) return render(self.request, 'wizards/index.html', { 'form_data': [form.cleaned_data for form in form_list], }) def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) I have another view that can be called with the post request path('query/', views.UserQueryView.as_view(), name='user_query'), I Want to call the 'query/' URL with Post request in my done function def done(self, form_list, **kwargs): print([form.cleaned_data for form in form_list]) return <--- here with POST data([form.cleaned_data for form in form_list]) -
form.get_user() returning None in Django
Why does form.get_user() within the if form.is_valid() statement return a value whereas form.get_user() outside of the statement returns None Values passed to form: {username='sheriffcarlos', password='Iamc@tbug'} Example 1: from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login import logging def user_login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): user = form.get_user() logger.info(user) #Logs Sheriffcarlos else: #Do Something Else #Do Something Example 2: from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login import logging def user_login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) user = form.get_user() logger.info(user) #Logs None if form.is_valid(): #Do something else: #Do Something Else #Do Something -
TAP payment gateway, trying to tokenize the credit card details
I am trying to integrate the provided UI javascript components, for capturing the credit card details and to tokenize those. But it shows the error like goSell requires server side execution, direct calls without origin not allowed. Here is my code, Moreover, TAP Payment gateway doesn't work in our region, So I have also tried by turning on the VPN, but nothing changes, it shows the same error ** I think, it is being triggered when the page loads, so it shows that not to call directly, please guide me how to trigger it. ** {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> *IT IS UNABLE TO MOUNT DATA IN THE FOLLOWING FORM* <form id="form-container" method="post" action="/charge"> <!-- Tap element will be here --> <div id="element-container"></div> <div id="error-handler" role="alert"></div> <div id="success" style=" display: none;;position: relative;float: left;"> Success! Your token is <span id="token"></span> </div> <!-- Tap pay button --> <button id="tap-btn">Submit</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script> <script src="https://secure.gosell.io/js/sdk/tap.min.js"></script> **From a survey I was asked to paste the cdns above like and paste the JS code below the above cdns like this** <script type="text/javascript"> **HERE PROVIDED PUBLIC KEY WILL BE INSERTED** var tap = Tapjsli('HERE_WILL_BE_PUBLIC_KEY'); … -
How to use the href link feature as well as pass a Django url to a view in Django?
If I have an .. Element which has a link it points to , but i also want to call a Django View ,how do i do it? <td ><a href="{{ page.url }}" >Click Here</a> But i also want to call 'updateViews' in /views.py like this <td ><a href="{% url 'updateViews' page.title %}" >Click Here</a> -
Import local settings if a command line argument is defined
I have the following code at the end of my Django settings: if not TESTING: # Don't use local settings for tests, so that tests are always reproducible. try: from .local_settings import * except ImportError: pass local_settings.py contains all the external dependencies URLs used by my Django application, such as database server URL, email server URL and external APIs URLs. Currently the only external dependency my test suite uses is the local database; everything else is mocked. However, now I'd like to add some tests that validate responses from the external APIs I use, so that I can detect quickly when an API change and the API owner does not notify me beforehand. I'd like to add a --external-deps command line argument to "./manage.py test" and only run tests that depend on external APIs if this flag is enabled. I know that I can process arguments passed to that command by overriding the add_arguments() method of the DiscoverRunner class, as described in Django manage.py : Is it possible to pass command line argument (for unit testing) , but my conditional Django settings loading are run before that, so the following won't work: if not TESTING or TEST_EXTERNAL_DEPS: # Don't use … -
Django Admin delete user exception - Django Phone number
I have a django project which was working fine. I got the requirement to include phone verification so i used twilio and used the django [phone number][1]. I did the verification part and everything is working fine until i noticed the following exception when i tried to delete a user from admin panel. I am not 100% sure if it has anything to do with phone number per this is the only new thing added to project. I tried adding and updating new user from admin panel and it worked fine. The issue is in deletion of user. Request URL: http://127.0.0.1:8000/admin/projectapp/customuser/ Django Version: 3.0.8 Python Version: 3.8.4 Installed Applications: ['django.contrib.admin', 'django.contrib.gis', 'projectapp', 'django.contrib.sites', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'verify_email.apps.VerifyEmailConfig', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "D:\installedSoft\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\installedSoft\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\installedSoft\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\installedSoft\Python\Python38-32\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\installedSoft\Python\Python38-32\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\installedSoft\Python\Python38-32\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File … -
Django Templates put quotation marks in to <noscript> tag. How to remove quotes?
I have code peace from Search System's Analyst service in my page Template in block: <noscript><div><img src="https://mc.yandex.ru/watch/75335146" style="position:absolute; left:-9999px;" alt="" /></div></noscript> But in browser it has shown like: <noscript> "<div><img src="https://mc.yandex.ru/watch/75335146" style="position:absolute; left:-9999px;" alt="" /></div>" </noscript> I tried to use {% autoescape off %} construction, but it did't helped. https://allgid.ru/al_home.html Code Validation in https://validator.w3.org/unicorn/check?ucn_uri=https%3A%2F%2Fallgid.ru&ucn_lang=ru&ucn_task=conformance# print Error: "Bad start tag in “div” in “noscript” in “head”." -
The map of google maps in a web (django) doesn't show the results in the first sending of data
I am using django and Maps Javascript API to create a website. User gives me an origen address and destination address (both with Places Autocomplete -https://developers.google.com/maps/documentation/javascript/places-autocomplete). I am trying to mark on the map both locations. Django's form: class userRequest(forms.Form): def __init__(self, *args, **kwargs): super(userRequest,self).__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Origin"}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Origin"}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Dest"}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Dest"}),required=False,initial=181) lat_currentLocat= forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_currentLocat"}),required=False,initial=181) lon_currentLocat= forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_currentLocat"}),required=False,initial=181) current_address=forms.CharField(max_length=200,widget=forms.HiddenInput(attrs={"class":"data","id":"current_address"}),initial='.') origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data","id":"origin_address"})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data","id":"destination_address"})) date=forms.DateField(widget=DateInput(attrs={"class":"data"})) Functions I am using in this process in JS: function init_autocomplete_map() { autocomplete_id("origin_address"); autocomplete_id("destination_address"); initMap(); } function initMap(){ list_address=['origin_address','destination_address'] save_lat_lon(list_address[0],'lat_Origin','lon_Origin'); save_lat_lon(list_address[1],'lat_Dest','lon_Dest'); latO=parseFloat(document.getElementById("lat_Origin").value); lonO=parseFloat(document.getElementById("lon_Origin").value); latD=parseFloat(document.getElementById("lat_Dest").value); lonD=parseFloat(document.getElementById("lon_Dest").value); let list_location=[]; let point_origin={lat:latO, lng:lonO}; let origin_exists=!(latO == 181 || lonO==181 || latD==181 || lonO==181) var map = new google.maps.Map(document.getElementById("google_map"), { scaleControl: true, center: point_origin, zoom: 6, }); if (origin_exists){ point_origin={lat:latO,lng:lonO} list_location.push(point_origin); list_location.push({lat:latD,lng:lonD}); list_location.forEach((element,index)=>{ const infowindow = new google.maps.InfoWindow(); contentString= '<div id="content-map">' + '<p>'+document.getElementById(list_address[index]).value+'</p>' + "</div>"; infowindow.setContent(contentString); const marker = new google.maps.Marker({ map, position: element }); marker.addListener("click", () => { infowindow.open(map, marker); }); }); }else{ map.setCenter({ //Madrid Coordinates lat : 40.4165, lng : -3.70256 }); } //get_currentLocation(map); } function save_lat_lon(id_address,id_latitude,id_longitude){ var address = document.getElementById(id_address).value if (id_address=='origin_address' && address==document.getElementById('current_address').value){ document.getElementById(id_latitude).value = document.getElementById('lat_currentLocat').value; document.getElementById(id_longitude).value= document.getElementById('lon_currentLocat').value; }else{ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address}, function(results, status) { document.write(status) if (status … -
Multiple field inheritance from Group excludes database fields in Django
I'm extending Django's Group class. However, after extending it a second time, the for referencing required group_ptr_id column is not created in the database table. See the following example: class MyGroup(Group): pass class AnotherGroup(MyGroup): pass Applying the migrations fails with the exception django.db.utils.OperationalError: near ")": syntax error. Printing out the query reveals that the group_ptr_id-column is not being created/missing, compared with the query for the table for the MyGroup-model: CREATE TABLE "users_mygroup" ("group_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "auth_group" ("id") DEFERRABLE INITIALLY DEFERRED) CREATE TABLE "users_anothergroup" () Why does this happen and how do I get Django creating the group_ptr_id column for the users_anothergroup-table, too? -
django reverse lookup using strings
I want to know is it possible to do reverse lookup between two tables without using foreign key in form of id. Means instead of matching between the two tables using a field id, can i make it using field values containing strings. example- if in both the tables i have column with different names but containing almost similar values in form of string. Is it then possible to reverse lookup other fields on behalf of these common string fields? table 1: SKILLS PROFILE python, R ml engineer python, java se table 2: NAME CandidateSKILLS Ajay Kumar python, java Suman python In this case is it possible to do reverse lookup using the skills and candidate skills columns if they contain almost similar string inside it. -
Same-value field in two different but related models
class Currency(models.Model): name = models.CharField(max_length=200) shortname = models.CharField(max_length=3) symbol = models.CharField(max_length=2) class Client(models.Model): name = models.CharField(max_length=200) base_rate = models.DecimalField(decimal_places=2, max_digits=15) country = models.CharField(max_length=200) currency = models.ForeignKey(Currency, on_delete=models.PROTECT) class Job(models.Model): title = models.CharField(max_length=200) start_date = models.DateField() rate = models.DecimalField(decimal_places=2, max_digits=15) client = models.ForeignKey(Client, on_delete=models.PROTECT) currency = models.ForeignKey(Currency, on_delete=models.PROTECT) I have above classes. Job and Client classes are related via the client field in the Job class. Both classes have a field called currency, which is related to the Currency class. In the current setup, obviously a Client object and a Job object that belongs to a Client can have different currency values. I want to tie these toghether so that the Job object always has the same currency value as the related Client object. How do I do this? -
Virtual Environment in Django
When we create virtual environment is it good practice to keep, our virtual environment folder and our project folder inside same root folder? If i am not wrong then every project have its own viretual environment so how can we remmember which project use which virtual environment if we have created too many virtual environment for many projects? -
django admin - custom action template
Im trying to add a custom action to django app, where i can redirect to a html (pdf) page i created. currently the html page only shows 1 result, What im trying to do is to show as many as objects i selcet from the action bar in django admin. here is my code def print_pdf(modelAdmin, request, queryset, **kwargs): from django.template.loader import get_template from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from calculator.models import Transaction from xhtml2pdf import pisa chp = [] for f in queryset: chp.append(f.chp_reference) for q in range(len(queryset)): transaction = get_object_or_404(Transaction, chp_reference=chp[1]) #im not sure what to do here template_path = 'report-pdf.html' context = {"transactions":transactions} response = HttpResponse(content_type='Application/pdf') response['Content-Disposition'] = 'filename="report.pdf' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('we had some errors' + html ) return response here is my code. I know its messed up, but i been trying to figure out to do this but im lost. help would be appreciated -
Problem with multiple file upload with formdata in django
i have an form, to take the inputs and for the multiple uploads trying with the Formdata {% load static %} {% block content %} <!doctype html> <html lang="en"> <head> <title>{{type}} | SE Learning</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="robots" content="noindex"> <meta name="googlebot" content="noindex"> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <!-- Fonts and icons --> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- Material Kit CSS --> <link rel="stylesheet" href="{% static 'assets/css/material-dashboard.css' %} "/> <link rel="stylesheet" href="{% static 'assets/css/main.css' %} "/> <link rel="stylesheet" href="{% static 'assets/css/vendor.css' %} "/> <link rel="stylesheet" href="{% static 'assets/css/jquery.dataTables.min.css' %} "/> <link rel="stylesheet" href="{% static 'assets/fonts/font-awesome.min.css' %} "/> </head> <body> <div class="wrapper "> <!-- Tip 1: You can change the color of the sidebar using: data-color="purple | azure | green | orange | danger" Tip 2: you can also add an image using data-image tag --> <section ng-include="'views/partials/header.html'" id="header" class="ng-scope"> <header class="clearfix ng-scope"> <!-- Branding --> <div class="row headrow"> <div class="branding col-md-3"> <a class="brand" ui-sref="app.dashboard" href="#"> </a> <a href="javascript:;" class="offcanvas-toggle visible-xs-inline" offcanvas-sidebar=""> <i class="fa fa-bars"></i></a> </div> <!-- Branding end --> <div class="col-md-9"> <a class="nav-log" href="/logout">Logout<span class="sr-only">(current)</span></a> </div> </div> </header></section> <div class="sidebar" data-color="purple" data-background-color="white"> <div class="sidebar-wrapper"> <ul … -
Django many to many field not being saved correctly in database
When I try to save many to many field in django. It only save one item , even when I have selected 2 items from the template. My views.py looks like this @login_required() def create_class(request): tea_user = request.user.username validate = teacher_validation(tea_user) if validate: if request.method == 'POST': Link = request.POST.get('link') Subject = request.POST.get('Subject') Class = request.POST.getlist('Class') print(Class) teacher_user = Teacher.objects.get(User=request.user) teacher = Teacher.objects.get(id=teacher_user.id) created_class = Online_Class.objects.create( Link=Link, Subject=Subject,Created_by =teacher ) for classes in Class: created_class.Class.set([classes]) return redirect('home') return render(request, 'online_class/Teacher/class-create.html') else: messages.warning(request, 'Sorry You Dont have Permission to access this page') return redirect('logout') My models.py looks like this class Online_Class(models.Model): Created_by = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING) Class = models.ManyToManyField(Classes) Subject = models.CharField(max_length=100) Link = models.CharField(max_length=200) Joined_by = models.ManyToManyField(Student, blank=True) created_at = models.DateTimeField(auto_now_add=True) choice = (('Yes','Yes'),('No', 'No')) Class_Ended = models.CharField(choices=choice, default='No', max_length=10) My template looks like this {% extends 'dashboard/teacher/base.html' %} {% block title %} Create Class {% endblock title %} {% block class %} active {% endblock class %} {% block body %} <div class="pc-container"> <div class="pcoded-content"> <div class="row"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label >Zoom Link</label> <input type="url" class="form-control" name="link" placeholder="URL" required=""> </div> <div class="form-group"> <label>Subject</label> <select class="form-control" name="Subject" required=""> {% for subject in teacher.Subject.all %} <option>{{subject}}</option> {% endfor … -
How to Model Authenticated User Metadata in Django
I'm using Django (Django Rest Framework) and I'd like to design an API that outputs songs as JSON when the user is not authenticated and additional (meta data) fields when authenticated. Non authenticated: GET: /songs/{song_id} ... class Song(models.Model): created_at = models.DateTimeField(auto_now_add=True) composed_year = models.PositiveIntegerField( blank=True, null=True) title = models.CharField(max_length=50) lyrics = models.TextField(max_length=10000) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) key = models.CharField(blank=True, null=True, max_length=2) Authenticated: GET: /songs/{song_id}/{user_id}/ This endpoint would return all the original song data PLUS an additional key field for the authenticated user and an arbitrary number of fields (e.g. notes). How would I model this? I would need a table mapping user ID to song ID plus additional fields. Is this what a through table is for? This doesn't seem like a many to many...rather one-to-one: one song has one user preference (per user), and one user preference has only one song... -
Django Query ManyToMany
I want to do a query to select top 5 users with more likes in their posts. My models are: class Post(ModelBase): title = models.CharField('Title', max_length=255) description = models.TextField() finished = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') likes = models.ManyToManyField(User, through='PostLike',) tags = models.ManyToManyField(Tag, related_name='tags') def total_likes(self): return self.likes.count() class PostLike(ModelBase): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) I have this, but it does not work for me correctly. Instead of telling the Likes of the users' post, count the Likes that each user has given. users = User.objects.annotate(likes_count=Count('postlike', Q(post__is_active=True)))\ .order_by('likes_count').reverse()[0:5] -
Show only link to file which exists Django Python
I have a four FileFields in my models.py like 2 below: file_1 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 1") file_2 = models.FileField(blank=True, upload_to='PN_datoteke/%Y/%m/%d/', verbose_name="Datoteka 2") Each time different number of files is uploaded and some are left empty. I use following in my .html page to offer a download option of the file which is uploaded: <p class="article-content mb-1"><strong>Datoteka 1: </strong><a href="{{post.file_1.url}}" download>Preuzmi</a></p> <p class="article-content mb-1"><strong>Datoteka 2: </strong><a href="{{post.file_2.url}}" download>Preuzmi</a></p> Problem is, I have 4 upload options and if some are not used I get following error: The 'file_2' attribute has no file associated with it How can I suppress the empty fields (.destroy, .remove) before they are generated on the page, if file doesn't exist? I guess I must use a javascript? How to check and not display a if a file doesn't exist? -
Django -JSON not serializable type-error while integrating paypal
Whenever I try to pay using paypal on my website it throws an error Internal Server Error: /paypal/create/18/ Traceback (most recent call last): File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\ukfle\Documents\pro\a\views.py", line 69, in create response = client.execute(create_order) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypalhttp\http_client.py", line 52, in execute data = self.encoder.serialize_request(reqCpy) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypalhttp\encoder.py", line 15, in serialize_request return enc.encode(httprequest) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\site-packages\paypalhttp\serializers\json_serializer.py", line 7, in encode return json.dumps(request.body) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\ukfle\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Decimal is not JSON serializable here are my views: def pay(request, pk): client_id = settings.PAYPAL_CLIENT_ID course = get_object_or_404(t_data,pk=pk) context={'course':course, 'client_id':client_id } return render(request, 'pay.html',context) def create(request,id): if request.method =="POST": environment = SandboxEnvironment(client_id=settings.PAYPAL_CLIENT_ID, client_secret=settings.PAYPAL_SECRET_ID) client = PayPalHttpClient(environment) course = t_data.objects.get(pk=id) create_order = OrdersCreateRequest() create_order.request_body ( { "intent": "CAPTURE", "purchase_units": [ { "amount": { "currency_code": "USD", "value": course.file_price, "breakdown": { "item_total": { "currency_code": "USD", "value": course.file_price } }, }, } ] } ) response = client.execute(create_order) data = response.result.__dict__['_dict'] return JsonResponse(data) else: … -
django.core.exceptions.FieldError: Unknown field(s) (phone) specified for User
Iam adding a new data storage in my models.py of django but this is not working I have make migrations and everything. models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length= 1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=10, default="Integer") def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) And this is my forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email','password1','password2','phone'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','phone'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile field = ['image'] exclude = ['fields'] Please help me find a solution for this this is really stopping me to build my own website. Please tell if I should add any other details to it I will definetly do that.