Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template tags nested if statment error
I have a sign up form and i want the user when clicks submit the invalid fields borders becomes red with my "danger-borders" class and an error message appears under it , in order to do that i used django template tags but it gave an error saying Invalid block tag on line 88: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? i double checked but everything seem ok here is the code: {% if signup_form.errors %} {% for field in signup_form %} {% if field.errors %} <input type="text" class="danger-borders" name="{{field}}" > <p class="text-danger ml-2">{{ field.errors | striptags }}</p> {% elif not field.errors %} {{field}} {% endif %} {% elif not signup_form.errors %} {% field %} {% endfor %} {% endif %} also i'm not sure that this is how to check if the errors doesn't exist in those two lines "{% elif not signup_form.errors %}" and "{% elif not field.errors %}" -
Django: Cannot assign string: class must be a class instance
This is my first Django's page. I know that it exists many reported problems like this but I haven't found the correct answer. I have a database that I can show perfectly, and I wannna allow to users to add new entries. models.py class Server(models.Model): client = models.ForeignKey(settings.AUTH_USER_MODEL, null=False, blank=False, on_delete=models.CASCADE) name = models.CharField(primary_key=True, max_length=20) ip = models.CharField(max_length=13) class Usuario(models.Model): id = models.AutoField(primary_key=True) servidor = models.ForeignKey(Server, null=False, blank=False, on_delete=models.CASCADE) correo = models.EmailField() fpago = models.DateField('Fecha de pago', auto_now_add=True) And views.py @login_required(login_url='login/') def suscripciones(request): obj_usuarios = Usuario.objects.all() if request.method == 'POST': servidor = request.POST.get('servidor') correo = request.POST.get('correo') consulta = Usuario(servidor=servidor, correo=correo) consulta.save() return render(request, 'APP/suscripciones.html', {'obj_usuarios': obj_usuarios}) The model works when without the request.method and consulta but with this code I get this error: Cannot assign "(string with the server's name)": "Usuario.servidor" must be a "Server" instance. Thanks so much. -
Pass arrays from django to js with ajax
I'm trying to pass 2 arrays via ajax from my views to my javascript. When I console.log my arrays i get 2 empty ones. I feel like I know what the error is but I can't solve it. I'm going to include my code first, than my toughts. views.py: In my first method, I want to pass my data to 2 arrays (dates,weights). In get_data is where I want to send my data to js. from django.shortcuts import render from django.contrib import messages from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import get_object_or_404 from users import models from users.models import Profile from .forms import WeightForm import json dates = [] weights = [] dates_queryset = [] def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) dates_queryset = Profile.objects.filter(user=request.user) dates = dates_queryset.values_list('date', flat=True) weights = dates_queryset.values_list('weight', flat=True) return render(request, 'Landing/index.html',{'form':form}) def get_data(request, *args,**kwargs): data = { 'date': dates, 'weight': weights } return JsonResponse(data) url: url(r'^api/data/$', get_data, name='api-data'), Ajax call: var endpont = '/api/data' $.ajax({ method: 'GET', url: endpont, success: function(data){ console.log(data); }, error: function(error_data){ console.log("Error"); console.log(error_data); } }) Js console.log output: {date: Array(0), … -
How can I see a translation in my website
I am currently working on my website, which is a translator which you input a phrase and it gets translated into an invented language. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py: from .translate import translator def translator_view(request): return render(request,'main/translator.html') def translated_view(request): text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') Here's the template where you introduce the text: <form action="{% url 'translated' %}" method= "get"> <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> … -
How to pass a url parameter into the views to be used by other class functions and the template
Please I have a serious problem that has left me with all kinds of errors for days. There are some functionalities I want to implement but don't know how to. Any help would be greatly appreciated. I want to create a register form that registers a user and sends them to their profile page after they have registered. I tried doing this by trying to pass the username the user filled in the form into the urls argument for my profile view. However, I don't know exactly how to do this and each code I find online only leads me to error. I am new to django. In addition to this, I want to create my profile view such that if a user searches their own template, then they can edit it, I used UpdateView for this and if it is not their profile then they can only view it as read only, I used the detailView for this. Also, please can someone also help me understand how to pass a url parameter into a class based view, how can all the functions in the view access this parameter. How can I use a variable from a function in a … -
How to Reformat the value of serializable django response?
I am newbie to django. I was following the following tutorial enter link description here All the steps are doing good. Suppose I have the following code from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser snippet = Snippet(code='foo = "bar"\n') snippet.save() serializer = SnippetSerializer(snippet) serializer.data I get the following output {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'foo: u'bar'....} I want to return back the just created data in the database (from the api) to the client. So, my question are: What is the best strategy to do that?I mean in the views what I should do. If i want for example the return data has the following format { "answer": "data saved:<bar>, 'pk': 2 } -
Django modify Many to Many relation
I have 4 Tables as follows: class Problem(models.Model): id = ... description = ... # A problem will have multiple languages class Language(models.Model): id = ... language = ... problem = models.ForeignKey(Problem, null=False, on_delete=models.CASCADE) # test table. Each test will have multiple problems class Test(models.Model): id = ... title = ... problems = models.ManyToManyField(Problem, through='testProblemRelation') below table defines the relation between Test and Problem. Here I want to define a field "allowed_languages" which will control the relationship between Problem table and language table only for a given test instance without affecting the general relationship between the problem language class TestProblemRelation(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE) test = models.ForeignKey(Test, on_delete=models.CASCADE) allowed_languages = models.JsonField(...) # languages which are allowed for each problem. #field will contain multiple problem ids and a list of language ids associated to each problem id . What to write here??? For example a problem 'Shortest Path' has 3 languages related to it which are C,C++ and Java. I use a post api to create a test such that it contains 'Shortest Path' problem with only java language related to it. However the problem outside this test should still have all 3 languages. I am not getting any idea on … -
Colapsable Button Bootstrap Django
I'm trying to create a social media news feed, with the posts, but I dont want to show the comments just if the user presses the button Show Comments. The problem is that when I press the button of one post, all the post will extend comments. I don't really know how to solve this... {% for post in posts %} <div class="container"> <div class="row"> <div class="[ col-xs-12 col-sm-offset-1 col-sm-5 ]"> <div class="[ panel panel-default ] panel-google-plus"> <div class="panel-heading"> <img class="[ img-circle pull-left ]" width="50" height="50" src="{{post.author.profile.image.url}}" alt="Mouse0270" /> <h3 class="author">{{post.author}}</h3> <h5><span>Shared publicly</span> - <span><a href="{% url 'post-detail' post.id %}"> {{post.date_posted}} </a></span> </h5><br> </div> <div class="panel-body"> {% if user == post.author %} <a class="text-right" href="{% url 'post-update' post.id %}"><p>Update</a> <a class="text-danger text-right" href="{% url 'post-delete' post.id %}">Delete post</a> {% endif %} <p>{{post.content}}</p> {% if post.image %} <img src ="{{post.image.url}}" width="300" height="300" border="0" class="img-thumbnail"> {% endif %} {% if post.video %} <video width="250" controls > <source src="{{post.video.url}}" type="video/mp4" > </video> {% endif %} </div> <br/> <div class="container" > <a href="{% url 'add-comment' post.id %}"><button class="btn btn-primary">Add comment</button></a> </div> <br> <button type="button" class="btn btn-danger btn-block" data-toggle="collapse" data-target="#demo">See comments</button> <div id="demo" class="collapse"> {% for comment in post.comments.all %} <div class="container"> <div class="row"> <div … -
Unique email verification to social-django
I have this webapp that has three login options (the normal method, google, facebook). The email is defined as unique, so I put this verification in the normal method, but I don't have that in the Facebook and gmail login methods, so when I log in to Google and try to log in to Facebook, it gives an error because it is the same email. I used AbstractUser to create a new user model. The error: How can i fix this? i want to show a error message on the login with the django messages if possible -
wrong response format django-rest-framework
iam creating a music web app using react-redux and django and i have function that returns single playlist it returns html response instead of json knowing that its working right when the two apps are seperated but when iam using django routs as my main routs and react like an interface only using this line: urlpatterns += re_path(r'', TemplateView.as_view(template_name='index.html')), here is my function **django** class getplaylist(APIView): renderer_classes = [JSONRenderer] def get(self,request): id=request.META.get('HTTP_ID',None) plst=playlist.objects.get(id=id) return Response(plst) **react** export const getPlaylist=(id)=>{ return dispatch=>{ dispatch(getPlaylistStart()) axios.get('http://127.0.0.1:8000/songs/getplaylist/',{headers:{ 'id':id}}) .then(res=>{ console.log(res); dispatch(getPlaylistSuccess(res.data)) }) } } and this is the response playlist(pin):"<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link rel="apple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.json"/><title>Songs App</title><link href="/static/css/2.3327982c.chunk.css" rel="stylesheet"><link href="/static/css/main.18cf81d6.chunk.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script>!function(e){function r(r){for(var n,f,l=r[0],i=r[1],a=r[2],c=0,s=[];c<l.length;c++)f=l[c],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n]);for(p&&p(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,l=1;l<t.length;l++){var i=t[l];0!==o[i]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var l=this.webpackJsonpfrontend=this.webpackJsonpfrontend||[],i=l.push.bind(l);l.push=r,l=l.slice();for(var a=0;a<l.length;a++)r(l[a]);var p=i;t()}([])</script><script src="/static/js/2.25085612.chunk.js"></script><script src="/static/js/main.dc42ca8e.chunk.js"></script></body></html>" -
How to show django form in bootstrap modal
I have a model called Folder and with this model i have CreateView, for that i have created a folder_form.html file. So right now if a user want to create folder they have to click on the click folder button on the homepage, the folder_form.html page will load. What i want to achieve is that load this form on the homepage inside a Bootstrap Modal instead of loading a new page.I tried doing this but it doesn't worked. **views.py** import requests from django.shortcuts import render from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.generic.list import ListView from ahmed_drive.models import Folder, Fileshare from . import models from django.views.generic.detail import DetailView from django.db.models import Q from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.http.response import HttpResponseRedirect #### Normal Pages Related Views #### class HomeView(TemplateView): template_name = "ahmed_drive/home.html" #### Pages Related Folder Model #### @method_decorator(login_required, name="dispatch") class FolderCreate(CreateView): model = Folder fields = ["name", "parent"] def formvalid(): if form.is_valid(): form.save() return redirect('home.html') else : return render(request,{'form': form}) folder_form.html {% extends 'base.html' %} {% block content %} {% load crispy_forms_tags %} <main class="p-5"> <div class="row"> <div class="col-sm-6 offset-sm-3"> <h1 class="myhead2">Create Folder</h1> <hr> <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{form | … -
Django Template > checking condition on button click
On my template i have a button to collect fee that takes the user to next screen. However, i want a check on this button's click event if the fee is already paid-in-full and prompts the user via message on screen. In related model i have method that checks if fee is paid in full. I had added the condition on template like this and it disabled the button <td><a href="{% url 'add_fee' student.id %}" class="btn btn-secondary btn-sm {% if student.get_remaining_fee == 0 %}disabled {% endif %}">Add Fee</a></td> but this increases the number of queries as i have a many students records on current view. In general if i want such validations before user can go to new/assigned view, what would be the best practice. -
How to Optimize Data Importing to a Django Model using django-import-export library
I have been using django-import-export library to upload my data as excel to the Django model and it has been working fine till i had to Upload an excel with 20,000 rows and it just took infinite time to get this action done. Can you please suggest the right way to optimize data Uploading to the Django model, where i can easily upload excel files and have that data saved in my Database. Please support. -
Images not Loading after Changing database from Sqlite3 to Postgres
I am working on a Django based application which has many applications in it I just thought of switching the database because there are any great software available for rescue light and also the DB browser software is really early and very less of features and is not user friendly so I thought of using postgres as it is one of the most highest rated so when I change the database everything works fine but the thing happened that most of my images didn't load some of them loaded but most of the images didn't load so please tell me what changes should I make to do to make all the images load as well as what has happened actually because all the code is working fine the the landing pages and the login and logout system but many of the images are not loading please tell me what should I do for what changes have to make in the code or if I have made any mistake -
Django Email Service
I want to send an activation Email your account is successfully created This is my views.py class UserAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin): permission_classes = [permissions.AllowAny] serializer_class = UserSerializer queryset = User.objects.all() lookup_field = 'id' filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['email', 'first_name', 'last_name', 'roles', 'id', 'contact', 'profile'] search_fields = ['email'] ordering_fields = ['first_name'] def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) # return Response("Required Id") def post(self, request): return self.create(request) def put(self, request, id=None): return self.update(request, id) This is settings.py STATIC_URL = '/static/' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '#####@gmail.com' EMAIL_HOST_PASSWORD = '##########' Please mention where to add the email thing. -
I can get user details but I can't work out how to change them?
So, I can get data and it all works but I can't seem to work out how to update it without updating everything, just what the user wants to update, I came up with this 'update' method below but I can't seem to get it to work. Any help would be greatly appreciated. Thanks, George. views.py class UserDetailsAPIView(CreateAPIView): serializer_class = UserDetailSerializer queryset = User.objects.all() permission_classes = (IsAuthenticated,) def get(self, request): serializer = UserDetailSerializer(request.user) return Response(serializer.data) def update(self, validated_data): email = validated_data['email'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] phone_number = validated_data['phone_number'] password = validated_data['password'] user_obj = User( email=email, first_name=first_name, last_name=last_name, phone_number=phone_number ) user_obj.set_password(password) user_obj.save() return validated_data serializers.py class UserDetailSerializer(ModelSerializer): class Meta: model = User fields = [ 'first_name', 'last_name', 'email', 'phone_number', 'is_active', 'email_confirmed', 'phone_number_confirmed', 'date_joined', 'last_login', 'nick_name', 'id' ] -
In Django 3, how do I build an AND query based on an array of conditions?
I'm using Python 3.8 and Django 3. I have the following model ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() I want to build an advanced search where I can search for one or multiple attributes, based on whether they are supplied. I have class CoopManager(models.Manager): def find(self, name, type, enabled): if name: qset = Coop.objects.filter(name=name) if type: qset = Coop.objects.filter(type__name=type) if enabled: qset = Coop.objects.filter(enabled=enabled) return qset but the above is flawed because it will only search on one attribute. How do I create an array of conditions and pass them to my query? For example, if "enabled" and "name" are supplied, then the query should only search by those two things. If "type" and "name" are supplied, ti should only search by those two things. -
Django AttributeError: 'str' object has no attribute 'pk'?
I have this error in my django project where I'm trying to connect django User model and a custom Profile model with a one to one relationship. Any help would be great and highly appreciated. Thank you! Here I have even tried WritableNestedModelSerializer, but that doesn't work either! Here is my code. Serializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'owner', 'title', 'body'] class ProfileSerializer(WritableNestedModelSerializer): class Meta: model = Profile fields = ['user', 'aboutMe', 'lastAccessDate'] class UserSerializer(WritableNestedModelSerializer): profile = ProfileSerializer('profile') class Meta: model = User fields = ['pk', 'username', 'first_name', 'last_name', 'email', 'profile'] def update(self, instance, validated_data): profile_data = validated_data.pop('profile') # Unless the application properly enforces that this field is # always set, the following could raise a `DoesNotExist`, which # would need to be handled. profile = instance.profile instance.pk = validated_data.get('pk', instance.pk) instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.save() profile.save() return instance Profile Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) aboutMe = models.TextField(max_length=500, blank=True) lastAccessDate = models.DateTimeField() @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: instance.profile.save() I just want to update profile deails and here is my UserUpdateView, class UserUpdateView(UpdateAPIView): #authentication_classes = … -
django not recognized as internal or external command
Though I have installed django, when I run django -admin startproject projectfirst, it is showing django is not recognised as internal or external command. -
Delete from one to many field django
I am trying to do a delete request in Django from many to one field. I am trying to get the user id and delete a particular task assigned under it with foreign key. Here is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Favourites(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) favourites = models.CharField(max_length=30, null =True) def __str__(self): return self.favourites Here is my views: @csrf_exempt def delete(requests): if requests.method == 'POST': username = requests.POST['uname'] fav = requests.POST['fav'] remove = Favorites.objects.filter(favourites=fav).delete() print(remove) print(all_favourites) return JsonResponse({"message": "done"}) I am new to django please help. -
Django field level permission in the admin
I have a Django project that is required to use field level permissions. Let's say I have model called books. The books model has 2 fields, title and content. I also have 2 groups of users. Group1 has the permission to only view the title field in my book model and Group2 can only view the content field in my book model. If userA is in Group1 and has the status of staff, is their a way to only show the title field when userA logs into the admin panel. I'd prefer an implementation that does not involve adding additional apps to my project. Thanks in advance. -
Running Django with Pyto on iPad
I am trying to build my first Webb app using Django. I’m using my iPad because I am on the move a lot. Anyways, I’m trying to follow Django’s instructions for building a poll application. I got the server running but when i made the changes that should have printed the Hello World but its now its giving me a ModuleNotFoundError. I’ve tried copy and pasting the lines of code from Django’s website and I’ve tried to type it in on my own. ModuleNotFoundError: No module named 'WellnessApp' import os `import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WellnessProject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) #if __name__ == '__main__': # main() if __name__ == '__main__': import background as bg with bg.BackgroundTask() as b: main()` -
Get keys and values of JSONField
I want to pass keys and values of my list of dicts from JSONField to XHR as JSON. The content of JSONField looks like: [{'q1':'12'},{'q2':'22'},{'q3':'11'}] And I want to pass them as same as list above. models.py: class User1(models.Model): history = models.JSONField(blank=True, null=True) class UserForm(ModelForm): class Meta: model = User1 fields = '__all__' views.py: class ArticleUpdateView(UpdateView): model = User1 template_name = None ... def get(self, request, *args, **kwargs): if request.headers.get('x-requested-with') == 'XMLHttpRequest': if request.headers.get('Get-History') == 'History': form = UserForm(request.POST or None) self.object = self.get_object() data = { 'history': str(form.fields['history']) } return JsonResponse(data, safe=False) Result: {"history": "<django.forms.fields.JSONField object at 0x109d03080>"} -
Django " AttributeError: 'function' object has no attribute 'as_view' "
I am trying to make an index page with class based views that will have menu bar and with that menu bar it will redirect to new pages and takes forms as post requests. But whatever i do i always get the same error. Here is the error ; Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\berat.berkol\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line … -
How to bind a comment form to one pot without a choice (Django)
When writing a comment under the article, it becomes possible to choose which post to bring the comment to. How to make comments automatically attach to the post under which it is written. **views.py** class AddCommentView(CreateView): model = Comment template_name = 'main/post_detail.html' form_class = CommentForm #fields = '__all__' success_url = reverse_lazy('barbers') **models.py** class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30, null=True, blank=True) description = models.TextField() def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=30) body = models.TextField(null=True) add_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) **forms.py** class CommentForm(ModelForm): class Meta: model = Comment fields = ( 'post', 'name', 'body')