Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get exact object in django rest framework using class based view?
i am trying to create comment for every single post from flutter front end but i dont know how to provide the exact post i wanted t comment django:2.2 models.py class Comment(models.Model): id = models.UUIDField(default=uuid.uuid4,primary_key=True,editable=False) author = models.ForeignKey(Account,on_delete=models.CASCADE,related_name='comments') post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') comment_content = models.TextField(max_length=400) commented_at = models.DateTimeField(auto_now_add=True) edited_at = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to=random_url,blank=True,null=True) parent = models.ForeignKey('self',null=True,blank=True,on_delete=models.CASCADE,related_name='replies') active = models.BooleanField(default=True) this is the serializers.py class CommentCreateSerialzier(ModelSerializer): class Meta: model = Comment fields = [ 'comment_content','image' ] and this is my views.py class CommentCreateSerializer(CreateAPIView): serializer_class = CommentCreateSerialzier message = 'you dont have permission to comment' permission_classes = [IsAuthenticated] def perform_create(self): serializer.save(author=self.request.user) how to add default post object in every single post ? and does it the same for replies as well thanks for replying -
How to get the data from database between the input dates in Django
I have two attributes in my database fromDate = models.CharField(max_length=100) toDate = models.CharField(max_length=100) By taking user input as <input type="date" name="fromDate"> <input type="date" name="toDate"> I want to get all the data from database between this two dates. -
How to do custom validation in my Django Modelform?
I have a ModelForm for this model, with this unique_together: class Registration(models.Model): student_name = models.CharField(max_length=50) selected_season = models.CharField(max_length=2) selected_subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student_address = models.TextField() student_phone = models.CharField(max_length=11) class Meta: unique_together = (('student_name', 'selected_season', 'selected_subject'),) The modelform is like this: class RegistrationForm(forms.ModelForm): student_address = forms.CharField(label='', widget=forms.Textarea(attrs={'class':'materialize-textarea'})) class Meta: model = Registration fields = '__all__' How do I raise a validation error if the unique_together requirement is not met? -
Django-rest-framework : create serializer for registration of two diferent user-type foreignkey relation with one custom user model
I want to create two user registration using one custom user. MODELS.PY class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True ) phone_number = PhoneNumberField(_("Phone number"),unique=True, blank=True, null=True) username = models.CharField(_("Username"),max_length=254,unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) full_name = models.CharField(_("Full Name"), max_length=50, null=True) date_of_birth = models.DateField(_("Birth date"), auto_now=False, auto_now_add=False, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] class Aesthete(models.Model): basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_verified = models.BooleanField(_("Verified"), default=False) class Artist(models.Model): basicuser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_verified = models.BooleanField(_("Verified"), default=True) debutsong = AudioField(upload_to='songsfile', blank=True, ext_whitelist=(".mp3", ".wav", ".ogg"), help_text=("Allowed type - .mp3, .wav, .ogg")) How can I create registration serializer and view please help. Thank you. -
Storing the Django project with the PostgreSQL database on GitHub
I changed the database from SQLite3 to PostgreSQL in my Django project. Is it possible to store my new database in the GitHub repository so that after cloning and running by the command python manage.py runserver the project has started with the whole database? -
Exclude python file from executions with server start in Django
I have some separate python file which fetches data from GitHub and store as dictionary. Execution of these files consumes times which makes django server to run or restart slower. This delay makes development time consuming. What is the proper way to organize external python files in project. Execution of these file is not required to be executed each time. Fetched can be stored in database and executions can be weekly. myProject> home> -views.py -urls.py -ABC.py (file need to exlude) -
How to customize Django ModelForm fields?
Hi I am trying to customize my ModelForm in Django. The form looks like this: class RegistrationForm(forms.ModelForm): class Meta: model = Registration fields = ['name', 'age', 'details'......] I am trying to add different classes to different fields, along with placeholders and no labels. How do I do that? Is there a way to carry this out in the templates? -
How to correctly override account-confirm-email view for django-rest-auth package
I try to write api using djangorestframework and django-rest-auth. Almost all the urls working correctly, but account-confirm-email. So in the registration.urls I see: urlpatterns = [ url(r'^$', RegisterView.as_view(), name='rest_register'), url(r'^verify-email/$', VerifyEmailView.as_view(), name='rest_verify_email'), # This url is used by django-allauth and empty TemplateView is # defined just to allow reverse() call inside app, for example when email # with verification link is being sent, then it's required to render email # content. # account_confirm_email - You should override this view to handle it in # your API client somehow and then, send post to /verify-email/ endpoint # with proper key. # If you don't want to use API on that step, then just use ConfirmEmailView # view from: # django-allauth https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'), ] I understand that I should to override the last url view. But I don't understand how I can do it. I also fount the same problem Django Rest Auth - Key error on Email Confirmation But I don't understand that code. Maybe someone's going to help me with the problem and explain what happens. -
DJANGO - Multiple Users
I am building a platform in django and for the User registration I followed some tutorials, at this point I think it would be nicer if I can add a "new user registration". In my case "students" can register, login and navigate the platform but I would like also to make a new type of user ( staff) where they can registrate as staff, login and visit only one page where they can create some new quiz. I tried to look online but I can't figure out how to do it from this point I have already created. Could you please give me some advice/resources on how can I solve this problem? account/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class FormRegistrazione(UserCreationForm): email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] account/views.py from django.shortcuts import render, HttpResponseRedirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from accounts.forms import FormRegistrazione # Create your views here. def registrazioneView(request): if request.method == "POST": form = FormRegistrazione(request.POST) if form.is_valid(): username = form.cleaned_data["username"] email = form.cleaned_data["email"] password = form.cleaned_data["password1"] User.objects.create_user(username=username, password=password, email=email) user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect("/") else: form … -
ValueError: Cannot assign "'auth.User'": "Token.user"
i am getting error while i generating token with user id. it's showing me error ValueError: Cannot assign "'auth.User'": "Token.user" must be a "User" instance. it would be great if anyone could figure me out where should i make changes in my code. thankyou so much in advance. views.py from rest_framework.authtoken.models import Token class Product_CategoryCreateAPIView(generics.CreateAPIView): # token = Token.objects.get_or_create(user=settings.AUTH_USER_MODEL) token = Token.objects.create(user=settings.AUTH_USER_MODEL) print(token.key) model = Product_Category queryset = Product_Category.objects.all() serializer_class = Product_CategoryAdd_Serializer -
I m getting error while am using crispy forms,
CrispyError at /cpm/domestic |as_crispy_field got passed an invalid or inexistent field views.py def Travel(request): form=forms.Travelform() if request.method=='POST': form=forms.Travelform(request.POST) if form.is_valid(): print("data inserted") return render(request,'Travelform.html',{'form':form}) return render(request,'Travelform.html',{'form':form}) Travelform.html {% extends 'base1.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container text-center"> <h1>Domestic Travel Requisition</h1> </div> <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-2 mb-0"> {{ form.Mobile_No|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Request_Date|as_crispy_field }} </div> </div> {{ form.Trave_Type|as_crispy_field }} {{ form.Purpose_Description|as_crispy_field }} <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.Travel_Date|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.Journey_Type|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.From_Place|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.To_Place|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Class|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Booking_Type|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Mode|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0"> {{ form.Total_Period|as_crispy_field }} </div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock %} can you please help me i am getting same: error in raise CrispyError("|as_crispy_field got passed an invalid or inexistent field") crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field -
Django search form autocomplete
I have a code that queries multiple database tables. def search_view(request): models = [Item, Category, SubCategory] template_name = 'home-page.html' query = request.GET.get('q') print('query: {}'.format(len(query))) if len(query): item_items = models[0].objects.filter( Q(title__icontains = query) | Q(item_code__icontains = query) | Q(description__icontains = query) ) category_items = models[1].objects.filter( Q(title__icontains = query) ) subcategory_items = models[2].objects.filter( Q(title__icontains = query) ) return render(request, template_name, context={'item_items': item_items, 'category_items': category_items, 'subcategory_items': subcategory_items, 'query': query}) return redirect('/') But I want to make autocomplete when I type in the search box. I tried to do it through djando-autocomplete-light but couldn't implement it in my code. So, maybe someone can help with this. -
How to load Keras Model in Django rest API views
api_views.py from keras.models import load_model model = load_model('saved_finger_print_model.h5') And I got this error! OSError: Unable to open file (unable to open file: name = 'saved_finger_print_model.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0) -
Django. Conditions in a queryset
I have a table "Table" and a field "field". I need to filter the table with the following condition: if (field.isdigit() and len(strip(field)) <= 4): do somethimg or if (field.isdigit() and int(field) <= 10000): do somethimg How would it look like in a query? Table.objects.filter(condition).update(field="xxx") Thank you -
Django authentication for Zoom Meetings
I have a django project which is being used as centralised user authentication for most of our applications. The project is customised as per our requirements to allow mobile and OTP authentication. Can we use this authentication for Zoom meetings? I came across this Zoom SSO. But not able to understand what changes I will have to make in the existing django application. Any guidance will be a great help. -
Django request.POST.get() returns None
I face a problem and I can't find a solution. I'm trying to redirect to the previous page after login. Somehow the ?next=request.path returns none when trying to request.POST.get() after submission. This is my Html code that directs the user to the login page, taking the request.path as "next page after login" value. {% if user.is_authenticated %} <button class="btn" data-toggle="modal" data-target="#inquiryModal"> <a class="btn btn-primary border rounded-0" role="button" href="#">Make an Inquiry</a> </button> {% else %} <a class="btn btn-primary border rounded-0" role="button" href="{% url 'login' %}?next={{ request.path|urlencode }}" >Make An Inquiry</a> {% endif %} This is the login page html code. <div class="login-clean" style="background-color: #fff;"> <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <!--- ALERTS --> {% include 'partials/_alerts.html' %} <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="Email"></div> <div class="form-group"> <input class="form-control" type="password" name="password" placeholder="Password"> </div> <div class="form-group"> <button class="btn btn-primary btn-block" type="submit">Log In</button> </div> </form> </div> Views.py file def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] valuenext = request.POST.get('next') print(valuenext) user = auth.authenticate(username=email, password=password) # if user is found and not from listing page login and redirect to dashboard if user is not None and valuenext == "": auth.login(request, user) messages.success(request, 'You are now succesfully logged in') … -
map anonymous user data when user login/register using session_key in django
I Have an app where anonymous user comes select item and add to cart and see the total price of the item selected i store these with a session_key , NOW after adding to cart user proceed to login and register , so after getting register/login i want to map the data user selected as an anonymous. views.py def ResultTest(request): request.session.create() var = request.POST.get('selectedTests') abc = UserSelectTest() abc.session_key = request.session._session_key #abc.user = request.user abc.testselected = request.POST['selectedTests'] abc.save() models.py class UserSelectTest(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) session_key = models.CharField(max_length=32, null=True) testselected = models.TextField() here in views i have commented request.user as anonymous user doesn't have any user instance providing user null is equal to true doesn't work So how can i map session_key after user login/register ? -
if column have same name then return one of same kind. django
database img now by doing something like this datatotemplates= playlist.objects.filter(playlist_name=playlist_name) I want output as 1st hello1 gfh ertr dg all i want is not to repeat same name. thank you -
Django/Pythons is Messages - Unique Error displays the field
I am very new to Django/Python programming so hopefully this is a simple fix. I have created a Model that when I try and add a duplicate record (via a ModelForm), the message that is returned to my template displays the unique field twice in the message. It appears like : "fieldname" "classname" with this "fieldname" already exists. How do I display the fieldname once. The message currently displayed is : FirstNamePerson with this FirstName already exists. What I would like to see is : Person with this FirstName already exists. Any assistance would be greatly appreciated. Thanks Models.py: class Person(models.Model): FirstName = models.CharField(max_length=20, primary_key=True) Template.html {% for message in messages %} <div class="alert alert-{{ message.tags }}"> message: {{ message | striptags }} </div> {% endfor %} -
Passing The ID of a Field in another Field of the same model Django
Hello, I am trying to pass the ID of a Model in an Image Field URL(upload_to) and then access it Through a URL unique to The instance. Here's What I did (Amature); class User(models.Model): serial = models.AutoField(primary_key=True) profile = models.ImageField(upload_to=f"profiles/{serial}/") But all I'm Getting is OSError. I wanted to save the file to profiles/{serial}/ directory in the app. So Every Instance of the Model has its own Directory. And Then access it Through host:port/api/users/{serial}/profile.jpg My View Set is served through host:port/api/users Is there a way I can Do it? Any Help is Highly Appreciated. A Detailed Explaination is Even more Appreciated. -
How to import a dictionary to templates using django?
So I am tying to make minesweeper for a school project using python django. My plan is to call a function onclick that would send the button id to views.py and find the corresponding number (number of bombs surrounding it) and return it to templates. I tested to see if my function is sending the id to views.py and it works but when i try to print the corresponding value through templates, it doesnt print anything. I'm wondering why and how do I fix it? Here's my code in templates: <body> <form id='klik' method='POST' action='{% url "klik" %}'> {% csrf_token %} <input type='hidden' name='ID' id='ID' value='{{ID}}' /> </form> <script> var docFrag = document.createDocumentFragment(); for (var i=0; i < 3 ; i++){ var row = document.createElement("tr") for (var j=0; j < 3 ; j++){ var elem = document.createElement('BUTTON'); elem.type = 'button'; elem.id = 'r'+i+'s'+j; elem.value = 'r'+i+'s'+j; elem.onclick = function () { document.getElementById("klik").value = this.id; document.getElementById("ID").value = this.id; document.getElementById("klik").submit(); print({{vrijednost}}); docFrag.appendChild(elem); } document.body.appendChild(docFrag); document.body.appendChild(row); } document.body.appendChild(docFrag); </script> </body> And my code in python: def klik(request): ID = request.POST['ID'] vr = r[ID] d = dict() d['vrijednost']= vr print(d) return render(request,'index.html', d) -
linking to the index.html to other html page in Django
I am new to django project. what I was trying to do is when user press the " Call us now" button on my nav-bar it links to the other html pages ( here: contact.html) in the index.html code: </ul><a href="contact.html"><button class="btn btn-primary" type="button">call us now!</button></a></div> in the views.py from django.shortcuts import render def index(request): return render(request, 'jobs/index.html') def contacts(request): return render(request, 'jobs/contact.html') in the urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.index, name='index'), path('contact/', jobs.views.contacts, name='contact'),] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)** -
Product matching query does not exist Django
i am trying to insert product in my database using django custom fields, but it's showing me error that Product matching query does not exist. it would be great if anybody could figure me out where should i make changes in my code. thank you so much in advance. views.py class ProductAdd(APIView): def post(self, request, format=None): data = request.data title = data['title'] slug = data['slug'] description = data['description'] # created_on = data['created_on'] # status = data['status'] queryset = Product.objects.filter(title__contains=title,slug__contains=slug,description__contains=description) query_slug = Product.objects.get(slug__exact=slug).first() try: if query_slug == None: # queryset.annotate(Count(title,slug,description,created_on,status)) queryset.annotate() Response({"msg":"product added succesfully!"}, status=HTTP_201_CREATED) else: print("query already exist!") except ValueError: return Response(status=HTTP_400_BAD_REQUEST) -
How do I solve this django-private-chat error?
so I've been trying to implement django-private-chat into an existing problem but always encountered an error. So, I tried to run the example project found on under django-private-chat on Github and I received the same error. Thanks for the help! 25.04.20 10:45:49:ERROR:Error in connection handler Traceback (most recent call last): File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/websockets/server.py", line 191, in handler await self.ws_handler(self, path) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/handlers.py", line 259, in main_handler user_owner = get_user_from_session(session_id) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/utils.py", line 15, in get_user_from_session session = Session.objects.get(session_key=session_key) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get num = len(clone) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql cursor = self.connection.cursor() File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. 25.04.20 10:45:49:DEBUG:server ! failing OPEN WebSocket connection with code 1011 25.04.20 10:45:49:DEBUG:server - state = CLOSING 25.04.20 10:45:49:DEBUG:server > Frame(fin=True, opcode=8, data=b'\x03\xf3', rsv1=False, rsv2=False, rsv3=False) 25.04.20 10:45:49:DEBUG:server x half-closing TCP connection 25.04.20 10:45:49:DEBUG:server - event = connection_lost(None) 25.04.20 10:45:49:DEBUG:server - state = CLOSED 25.04.20 10:45:49:DEBUG:server x … -
How to link static files in django, if the path is provided by the context in html?
Here is my views.py file: from django.shortcuts import render def page(request): css = 'temp/css.css' return render(request, 'temp/index.html', {'css': css}) and templates/temp/index.html file: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static '{{ css|safe }}' %}"> </head> <body> Hello Page </body> </html> and static/temp/css.css file: * { width: 100vw; height: 100vh; background: red; } After rendering source of the page is: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="/static/%7B%7B%20css%7Csafe%20%7D%7D"> </head> <body> Hello Page </body> </html> but I am expecting ... <link rel="stylesheet" type="text/css" href="/static/temp/css.css"> ... Why it is not working? Is there any way to do this? How to link a static file if the path is provided by the context in html?