Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is gettext_lazy used in offical Django models?
I was looking at Django code that comes with the package, such as contrib.auth.models, and I noticed that the first argument in almost every field definition is using gettext_lazy along with the name of the field. Something like this: from django.utils.translation import gettext_lazy as _ class MyModel(models.Model): my_field = models.IntegerField(_('my field')) Why is this done? Is it part of some best practice habit? -
Django: cannot register model in admin panel
I've various models in my apps. However, there is this one that I cannot register so I can see it in the admin panel. So in my cart app, I can use: from django.contrib import admin from .models import Cart, CartItem # Register your models here. admin.site.register(Cart) But not: from django.contrib import admin from .models import Cart, CartItem # Register your models here. admin.site.register(Cart, CartItem) Because I get this error: File "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/django/contrib/admin/checks.py", line 26, in check_admin_app errors.extend(site.check(app_configs)) File "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 81, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'CartItem' object has no attribute 'model' models.py: from django.db import models from shop.models import Product # Create your models here. class Cart(models.Model): cart_id = models.CharField(max_length=250, blank=True) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() active = models.BooleanField(default=True) class Meta: db_table = 'CartItem' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product -
uWSGI issue: dyld: Library not loaded: @rpath/libpcre.1.dylib
I've plugged in uwsgi to my Django application. I'm using macOS Mojave - 10.14.1 . Application runs fine with the below command. python manage.py runserver But when I use uwsgi to start the server. It fails. $uwsgi --socket 127.0.0.1:3031 --chdir /Users/antonybritto/mysite/mysite/ --wsgi-file mysite/wsgi.py --master --processes 4 --threads 2 --status 127.0.0.1:9091 dyld: Library not loaded: @rpath/libpcre.1.dylib Referenced from: /anaconda3/bin/uwsgi Reason: image not found Abort trap: 6 Can someone help me figure out what is wrong? -
Virtual filesystem for users on website with Django backend
What is a reasonable way to provide a virtual file system on a website with Django backend on a per-user-basis? Since a lot of websites (e.g. Overleaf, Cloud9 IDE) have such a feature I assume there is a feasible and ready-to-use solution? -
JSONDecodeError at /pro/product/5/
whenever i run the server at localhost i got this error cant figure out what the issue is here is the code of the request @api_view(['GET','POST']) def ProductView(request,id): # status = get_object_or_404(id=request.POST.get('id', '')) stat = get_object_or_404(Product,id=id) serializer =ProductSerializer # serializer = serializers.statusSerializer(stat,many=True) nice=stat.name # nice = str(stat.total) print(nice) # return Response(json.loads(reade r(nice))) return Response(json.loads(nice)) this the error JSONDecodeError at /pro/product/5/ Expecting value: line 1 column 1 (char 0) -
Customizing django admin
This is my Quiz model, class Quiz(Base): name = models.CharField(max_length=512, null=True, blank=True) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="", ) This is a Question, class Question(Base): text = models.TextField() quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to=question_image_path, null=True) And this is an answer, class Answer(Base): text = models.TextField(null=True) question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True, blank=True) correct = models.BooleanField(default=False) Instead of the regular django admin display I want to display the entire quiz creation form in one page. How can I customize django admin to do this. -
Django REST framework: How can I associate with other model in POST request?
I'm really new to creating API and I might misunderstand a lot. I want to associate an object with other model in POST request as I do when posting as a form data in astual site. How can I do using rest framework? my api view is like this @api_view(['GET', 'POST']) def list_comment(request, pk): """ List all comments that belong to an entry or add a comment to the entry """ entry = get_object_or_404(Entry, id=pk) comments = Comment.objects.filter(entry=entry) if request.method == 'GET': serializer = CommentSerializer(comments, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CommentSerializer(data=request.data) # I want to associate the comment with 'entry' here if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Also the rest framework page's form is kind of hard to experiment something and I want to change it to form. How can I change it? Even if I select form data, the content form doesn't change. -
SocialConnectView of django-rest-auth not working to connect existing user to social account
Im trying to connect social account to existing user. Social login works great, the problem is to connect an already registered user. as the docs: #views.py from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from rest_auth.registration.views import SocialLoginView, SocialConnectView class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter class FacebookConnect(SocialConnectView): adapter_class = FacebookOAuth2Adapter and #urls.py ... from .views import FacebookLogin, FacebookConnect urlpatterns = [ .... path('facebook/connect/', FacebookConnect.as_view(), name='fb_connect'), path('facebook/', FacebookLogin.as_view(), name='fb_login'), .... ] on my fronend, when the user is logged in and try to connect his account to facebook: axios.post('auth/v1/facebook/connect/', { // token is access_token from facebook response access_token: token, }) but the backend response is: ... status: 401 statusText: "Unauthorized" detail:"Authentication credentials were not provided." ... my settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } ... # allauth settings ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False SOCIALACCOUNT_QUERY_EMAIL= True Am I missing something that I should send to '...facebook/connect/' besides access_token ? PS: Im using separated frontend with webpack -
Listing all movies of a specific cinema - Foreign Key Django
I am new to Django and I have a question regarding the models and foreignkeys. I have two models: Cinema and Movie. One Cinema can have multiple movies, so I placed the foreign key of cinema in the Movie model. class Cinema(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=255) posting_cinema = models.ForeignKey('cinemas.Cinema', on_delete=models.CASCADE, null=True) Now I want to list all the movies of a specific Cinema. How can I do it? The idea is the following: The user clicks on a cinema, it opens a page with the cinema details and a button "see movies". If the user clicks this button, a new page opens and I want to have listed there the movies of that specific cinema. I tried to figured out some solutions but sadly I am stuck. I was thinking about Movie.objects.filter(#something) but I am not sure -
Django admin. TabularInline. How to show ForeignKey related model in TabulatInline view
I trying to show in my django-admin, related model of related model. Right now my models and admin.py looks like: class CharacterChoiceInline(admin.TabularInline): model = CharacterModel fields = ['nickname', 'gender', 'image'] extra = 1 class UserModelAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': [ 'username', 'email', ... ] }) ] inlines = [CharacterChoiceInline] admin.site.register(User, UserModelAdmin) My CharacterModel is related with another model RaceModel. class RaceModel(models.Model): name = models.CharField("Race", max_length=254) character = models.ForeignKey("CharacterModel", null=True, blank=True, on_delete=models.SET_NULL, related_name='+') class CharacterModel(models.Model): nickname = models.CharField("Character nickname", max_length=254) gender = models.CharField(choices=GENDER, max_length=10, default='male') image = models.URLField(blank=True) In Admin it looks like so: How can I add this additional RaceModel field as part of CharacterChoiceInline(admin.TabularInline):? -
Django | CKEditor - Image Upload option not showing in App
In admin all CKEditor option is showing and working properly. I can upload image in main admin dashboard. But in App in Image "Uoload" option is not showing. Please see those images than you have a clear view, Image 1 Image 2 Others option is working properly without image Upload. settings.py THIRD_PARTY_APPS = [ 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', ] INSTALLED_APPS += THIRD_PARTY_APPS + LOCAL_APPS # CkEditor Upload path CKEDITOR_UPLOAD_PATH = 'uploads/' # CkEditor Custom Configuration CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'width': 680, 'extraPlugins': ','.join(['codesnippet']), }, } template.html <form method="post" enctype="multipart/form-data">{% csrf_token %}> {{ form.media }} {{ form.as_p }} <button type="submit">Submit</button> </form> -
Django apps aren't loaded yet when using asgi
I'm tring to run my django project with usage of asgi instead of wsgi. I have set up my routing.py and asgi.py as follows: routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator from channels.auth import AuthMiddlewareStack from some.consumers import SomeConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r'^some_url/$', SomeConsumer), ] ) ) ) }) asgi.py import os from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") application = get_default_application() Now, as you can see it's standard setup and it works fine with default django server but when I try to run with some other (daphne or uvicorn) it's throwning this exception. Here is my INSTALLED_APPS INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_jenkins', 'easy_thumbnails', 'image_cropping', 'allauth', 'allauth.account', 'and_rest_of_my_own_apps', ] Has anyone had problem like this? -
Django queryset filtering and annotate
How to write in Django query that? I write in sql something like that: select distinct tt.client_id from (select tk.client_id, min(tk.changedon) min_date from app_tickets_ticket tk where tk.status_id=7 and tk.active=FALSE group by tk.client_id) tt, app_tickets_ticket tr where tr.client_id=tt.client_id and tr.status_id in(5,6) and tr.active=FALSE and tt.min_date::DATE between '2018-12-05'::DATE and '2018-12-06'::DATE and tr.changedon::DATE<=tt.min_date::DATE and tt.client_id not in(select tm.client_id from app_tickets_ticket tm where tm.active=FALSE and tm.changedon::DATE between '2018-12-05'::DATE and '2018-12-06'::DATE and tm.changedon<=tt.min_date and tm.status_id in(8,10,11,12,13,14,15,16,17)) -
Why sites served with nginx have no styling applied
I try to put build of react app on localhost/ using nginx. As far as i understand this, i need to build app with "npm run build" and then serve build dir with static content. After many hours i managed to get it into work with docker and my django service as a api under localhost/api/. But what is not working is css and js on this sites. On any page neither is it react or django endpoints there is only raw html with attached css but not working. After many attempts with changing configs etc. I ended with same raw html. Why on nginx there is no styling on sites even if with inspecting these pages there is linked css to them. This is my nginx.conf http { server { listen 80; listen [::]:80; root /var/www/html; server_name localhost; index index.html index.htm; location /api/ { proxy_pass "http://web:8000/"; } location / { include /etc/nginx/mime.types; try_files $uri $uri/ /index.html; } location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { root /var/www/html; expires 1M; access_log off; add_header Cache-Control "public"; } } } This is part of docker-compose nginx: image: nginx:latest ports: - 80:80 - 443:443 volumes: - ./nginx_conf/:/etc/nginx/ - ./frontend/build/:/var/www/html/ depends_on: - web When i run this app … -
How to create a user voter to vote for one single choice in a poll in Django
class Poll(models.Model): question = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) expire_date = models.DateTimeField(blank=True, null=True) slug = models.SlugField(max_length=100) def _get_unique_slug(self): slug = slugify(self.question) unique_slug = slug num = 1 while Poll.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): self.slug = self._get_unique_slug() super().save(*args, **kwargs) def __str__(self): return self.question class Meta: ordering = ('-pub_date',) class Choices(models.Model): poll = models.OneToOneField(Poll, related_name='choices') choice_text = models.CharField(max_length=200) voter = models.OneToOneField(User, on_delete=models.CASCADE, related_name='voters', blank=True, null=True) vote_count = models.PositiveIntegerField(default=0) def __str__(self): return self.choice_text def save(self, *args, **kwargs): self.vote_count += 1 super().save(*args, **kwargs) class Meta: pass # order_with_respect_to = 'poll' It doesn't allow user to vote more than one poll. and if I change it to voter = models.Foriegnkey(User, on_delete=models.CASCADE, related_name='voters', blank=True, null=True) It allows users to vote more than a single option in a poll which is not the intended behaviour. I will appreciate if I can't get help to fix this. Thank you. -
Page not found (404) after running the url of API
I have an django app,But i want to make its API so just i created it after runing the server Page not found (404) But my django app is running,After the running the url of API i got the error of Page not found views.py from django.http import Http404 from django.shortcuts import render from django.views.generic import ListView,DetailView from .models import List from django.http import HttpResponse,JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from List.serializers import ListSerializers class MainListView(ListView): queryset = List.objects.all() # temp = List.objects.all() template_name = "main_list.html" def get_context_data(self, *args, **kwargs): context = super(MainListView, self).get_context_data(*args, **kwargs) context['temp'] = List.objects.all() return context class MainListView(ListView): queryset = List.objects.all() # temp = List.objects.all() template_name = "List/list.html" def get_context_data(self, *args, **kwargs): context = super(MainListView, self).get_context_data(*args, **kwargs) context['temp'] = List.objects.all() return context class MainDetailSlugView(DetailView): queryset = List.objects.all() template_name = "news/detail.html" @csrf_exempt def list_list(request): if request.method == 'GET': queryset = List.objects.all() serializer = ListSerializer(queryset, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ListSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def list_detail(request, pk): try: list = List.objects.get(pk=pk) except List.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ListSerializer(list) return JsonResponse(serializer.data) elif request.method … -
Error on dynamic link libraries (dll) when using GDAL of OSGeo4W in Django
I'm trying to install GeoDjango in my Django project and got weird errors with GDAL. Following Django documentation, I installed GDAL, GEOS, PROJ using OSGeo4W64, for specific, these are packages I selected to install on OSGeo4W64 setup: gdal v2.3.2-2 geos v3.7.0-1 proj v5.2.0-1 I also set my environment variables as documented. When I started my Django project (using runserver), python tried to look for gdal202.dll and raised error Entry Point Not Found: The procedure entry point sqlite3_column_origin_name could not be located in the dynamic link library ...\osgeo4w64\bin\gdal202.dll And one more error with libcurl.dll (installed by OSGeo4W as dependencies): The ordinal 361 could not be located in the dynamic link library ..\osgeo4w64\bin\libcurl.dll I fixed the first error by download latest curl Windows binary version and replaced the existed on in OSGeo4W but still can not figure out how to solve the first error. As the error said, it seemed that there were some code require for sqlite3_column_origin_name function in gdal202.dll. In addition, OSGeo4W also install sqlite3 as dependencies in its bin directory, and I also checked the dll too, it did contain an entry point for function sqlite3_column_origin_name. So it seemd that the entry point sqlite3_column_origin_name was required directly from gdal202.dll, … -
DRF post request multiple inner serializers
i have three models named Smoker,Switch,Survey i have smoker as foreign key in Switch model and switch as foreign key in Survey model class Smoker(models.Model): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) mobile = models.IntegerField(null=True, blank=True) gender = models.BooleanField(blank=True, null=True) age = models.ForeignKey(Age,models.DO_NOTHING,blank=True, null=True) occupation = models.ForeignKey(Occupation, models.DO_NOTHING, blank=True, null=True) class Switch(models.Model): time = models.TimeField(blank=True, null=True) count_outers = models.IntegerField(blank=True, null=True) count_packs = models.IntegerField(blank=True, null=True) smoker = models.ForeignKey(Smoker, models.DO_NOTHING, blank=True, null=True) new_brand = models.ForeignKey(NewBrand, models.DO_NOTHING, blank=True, null=True) new_sku = models.ForeignKey(NewSku, models.DO_NOTHING, blank=True, null=True) # def __str__(self): # return self.time.strftime("%H:%M") class Survey(models.Model): user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True) date = models.DateField(null=True, blank=True) bool_switch = models.BooleanField(null=True, blank=True) reason = models.ForeignKey(Reason, models.DO_NOTHING, null=True, blank=True) shift = models.ForeignKey(ShiftingTime, models.DO_NOTHING, null=True, blank=True) current_brand = models.ForeignKey(CurrentBrand, models.DO_NOTHING, null=True, blank=True) current_sku = models.ForeignKey(CurrentSku, models.DO_NOTHING, null=True, blank=True) pos = models.ForeignKey(Pos, models.DO_NOTHING, null=True, blank=True) switch = models.ForeignKey(Switch, models.DO_NOTHING, null=True, blank=True) and here i have my serializers: class SmokerSerializer(serializers.ModelSerializer): class Meta: model = Smoker fields = '__all__' class SwitchSerializer(serializers.ModelSerializer): smoker = SmokerSerializer() class Meta: model = Switch fields = '__all__' def create(self, validated_data): smoker_data = validated_data.pop('smoker', None) if smoker_data: smoker = Smoker.objects.create(**smoker_data) validated_data['smoker'] = smoker class SurveySerializer(serializers.ModelSerializer): switch = SwitchSerializer() class Meta: model = Survey fields = '__all__' … -
Slow down the rate of requests in Vue.js updated method in Django web application
I have a Vue.js view in a Django template. Vue pulls the data to display in the view from a Django Rest Framework endpoint. My code follows: const app = new Vue({ el: '#app', delimiters: ["[%", "%]"], data: { dedicated_server: [], }, created() { fetch('/api/dedicated-server/{{ object.id }}/') .then(response => response.json()) .then(json => { this.dedicated_server = json; }) }, updated() { /* TODO: Try and limit the number of requests to the API */ fetch('/api/dedicated-server/{{ object.id }}/') .then(response => response.json()) .then(json => { this.dedicated_server = json }) }, }); As you can see I have an updated method which polls the Restful endpoint to update the page if the data changes. This all works fine but it seems to poll the Restful API endpoint about 3 to 5 times a second. This is fine in development but if I have 100 people visiting this page then it is going to kill my server with requests. Is there a way to limit the number of times Vue.js checks to see if the data has been updated? It would be great if you could say check once every 5 seconds. -
How to restrict edit link being shown in template, based on whether the current user is the owner of a blogpost?
I am new to Django and attempting to create a a test blog. Everything is working except I cannot restrict the editing of a blog post to the blog post's owner. My first attempt was successful, but all I did was "Raised 404" in the view function after comparing whether, or not, the current user was the same as the blog post's owner. My second attempt involved adding a comparison in the template. But, all that did was remove the edit link for all users, even the owner. The template code is below. {% extends "blogs/base.html" %} {% block content %} <h3>My Posts</h3> <p> <a href="{% url 'blogs:new_blogpost' %}">Add a new blog post:</a> </p> <ul> {% for blogpost in blogposts %} <li><strong>{{ user.username }} : {{ blogpost.owner }}</strong> <br> <strong>{{ blogpost.title }}</strong> - {{ blogpost.date_added }} <br> {{ blogpost.text }} <br> <p> {% if user.username == blogpost.owner %} <a href="{% url 'blogs:edit_blogpost' blogpost.id %}">edit blog post</a> {% endif %} </p> </li> {% empty %} <li>No posts have been added yet.</li> {% endfor %} </ul> <a href="{% url 'blogs:new_blogpost' %}">Add a new blog post:</a> {% endblock content %} Note, I am using Django 1.8. And, for testing purposes, I included both … -
Django: how to log every app to a separate file
i've my log definition as below: LOG_DIR = '/var/log/myapp/' LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.NullHandler', }, 'logfile': { 'level':'DEBUG' if DEBUG else 'WARNING', 'class':'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + "/application.log", 'maxBytes': 1024 * 1024 * 10, #Max 10MB 'backupCount': 3, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG' if DEBUG else 'WARNING', 'propagate': False, }, '': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, } } Now, i have several applications in this project, and i have to organize the logging of them in a simple way, creating a separate log from each other, i mean: Project general logs My_App1 logs My_App2 logs My_App3 logs Is this possible in a easy way with Django? -
Django ForeignKey Constraint Failed error
I am creating a simple blog site with multi-user facility using django framework. In my project, If the admin deletes any user, all of that user's blogs should not be deleted, I've tried using models.ForeignKey(django.contrib.auth.models.User,on_delete=models.CASCADE) but it obviously deletes all the blogs if the admin deletes the user. Can anyone help me please? Thank in advance... -
Django csrfmiddlewaretoken shown as hidden input tag in browser
I have {% csrf_token %} in my html file form. It renders nicely. But when I click on view source in a browser it shows as <input type="hidden" name="csrfmiddlewaretoken" value="SkXIYIpbfiaGWZImnFHoiausd3Q0NK098qw1MgrJ54f55nmG7VXrnHqSpsw9yU8C"> Is this safe for anyone to be able to access csrfmiddlewaretoken value? I am currently on development server provided by Django. Thanks -
ValueError: Cannot use object with type datetime for a spatial lookup parameter
During makemigrations it's okay but when i'm gonna migrate here title exception raised. models.py from django.contrib.gis.db import models class Restaurant(models.Model): restaurant = models.CharField(max_length=254) rating = models.FloatField() type = models.CharField(max_length=254) cuisines = models.CharField(max_length=254) cost = models.CharField(max_length=254) address = models.CharField(max_length=254) features = models.CharField(max_length=254) latitude = models.FloatField() longitude = models.FloatField() point = models.PointField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.restaurant Not only Pointfield. That exception raised in case too MultiPolygonField, MultiPointField and such like this field. -
How to get the currently logged in user (from auth) and display his name on the post
How can I get the Username and save it to auhtor model in discussion and then display it in template. i tried a few things but it doesn't work. Any help is appreciated. thanks models class Discussion(models.Model): author=models.CharField(max_length=15,null=True) title=models.CharField(max_length=50) argument=models.CharField(max_length=350) slug=models.SlugField(max_length=31,unique=True) created_on=models.DateField(auto_now=True) def get_absolute_url(self): return reverse('discussion_detail',kwargs={'slug':self.slug}) def __str__(self): return self.title Form class DiscussionForm(forms.ModelForm): class Meta: model=Discussion fields=['title','argument','slug'] Views: class NewDiscussionView(LoginRequiredMixin,View): template_name='Discussion/new_discussion.html' form_class= DiscussionForm def get(self,request): return render(request,self.template_name,{'form': self.form_class()}) def post(self,request): bound_form = self.form_class(request.POST,instance=request.user) if bound_form.is_valid(): new_discussion=bound_form.save() return render(request,'Discussion/discussion.html',{'discussion':Discussion.objects.all()}) else: return render(request,self.template_name,{'form': bound_form})