Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku release phase commands are not executed
I try to deploy a django application on heroku using a build manifest. The application seems to be deployed correctly, but the commands in the release phase do not seem to be executed. This is my heroku.yml: build: docker: web: Dockerfile release: image: web command: - python manage.py migrate - python manage.py collectstatic --noinput run: web: gunicorn hello_django.wsgi:application --bind 0.0.0.0:$PORT This is my Dockerfile: FROM python:3.9-slim ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONBUFFERED 1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app # install dependencies RUN pip install --upgrade pip COPY requirements.txt ./ RUN pip install -r requirements.txt # copy source code to container COPY ./src . # create directory for statics RUN mkdir staticfiles The commands specified in the release phase are not executed. I know that, because the database is not being migrated and the staticfiles directory is empty. I also know that the rest of my application is actually configured correctly, because when I include this line in my Dockerfile at the end: RUN python manage.py collectstatic then the statics are collected and the application is running. I also installed the plugin heroku-manifest with this command: heroku plugins:install @heroku-cli/plugin-manifest … -
How to filter on date in Django Rest Framework
I wrote the following code, trying to filter on dates using DRF: class FixtureFilter(django_filters.FilterSet): date = django_filters.DateFilter('date__date', lookup_expr='exact') class Meta: model = Fixture fields = ['date'] class FixtureViewSet(viewsets.ReadOnlyModelViewSet): queryset = Fixture.objects.all().order_by('-date') serializer_class = FixtureSerializer permission_classes = [permissions.IsAuthenticated] filter_class = FixtureFilter When I make a call to the API like http://localhost:8000/api/v1/fixtures?date=2021-11-29 it returns me more than 1 object whereas it should just return 1 object. How do I implement this properly? -
Edit Django objects with bootstrap modal form
This is something I've not done before as I'm still a beginner. Am using bootstrap form (class="modal fade") to add new objects into my model with Ajax. Now my problem is how I can edit objects with this same form. Also, I'm using django_tables to render the objects in my html. Below is my tables.py file class ObjectTable(tables.Table): class Meta: attrs = {'class': 'table table-bordered table-striped mb-0'} name = tables.Column(accessor=A('name'), verbose_name='Name') address= tables.Column(accessor=A('url'), verbose_name="Address") edu_level= tables.TemplateColumn('{{record.level}}') created_at = tables.Column(accessor=A('created_at'), verbose_name="Date Created") options = tables.TemplateColumn( '<button class="btn btn-info btn-sm" data-toggle="modal" data-target="#link-edit"><i class="feather ' 'icon-edit"></i> &nbsp;Edit </button> ' '<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#link-delete"><i class="feather ' 'icon-trash-2"></i> &nbsp;Delete </button>') Below is part of the form.html ... <div class="modal fade" id="link-edit" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Edit Link</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form class="edit-link-form"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label class="floating-label" for="Name">Name</label> <input required type="text" name="name" class="form-control" id="EditName" placeholder="Enter the name of the link here"> </div> ... -
Is there any reason why Git erasing my Django templates content?
Before I commit, I run—'git status', and I see Git erased my Django templates content (if that makes any sense). This strange behavior happens occasionally. Can somebody explain what's going on? -
Django template slow to render: caching helps subsequent loads, but can I help the first?
I have a django app hosted on heroku, and I have a 'family album' page that loads a bunch of image thumbnails which link to a larger image detail page. (And the set of pictures can be different per user). Each of these thumbnails uses an image_link.html template. At the most there can be up to ~1100 of these thumbnails on the family album page, and it loads peachy in production. The problem: I wanted to add the option to have a little hover overlay, so that when you mouse over a thumbnail you can see an overlay of who the picture contains. (This is returned by a function on the Image class). I started with the image overlay code from w3schools here, and updated to show the list of people in each picture (instead of static text). This works great, but locally that page can take around 4-5 seconds to load, and when I deploy it to production (on heroku), it's taking forever: ~22 seconds on average, sometimes surpassing the 30 second timeout. (I'm using one Hobby Dyno). So I've done a couple things: cached the code in views.py that grabs all the images that'll display then I added … -
Make Django/DRF accept urls without trailing slash
Is it possible to avoid url redirections to url/ in Django/DjangoRestFramework? My point is that some frontend developers use url without trailing slashes and Django redirects such requests to url/ which slows down the API. Adding APPEND_SLASH = False to settings doesn't solve the problem as it returns 404 responses. -
Django many-to-many relationship with through table, how to prevent it doing a lot of queries?
I am working on an API for a D&D tool where I have campaigns, and people can be members of campaigns. I need to store extra information for each member of the campaign, so I am using a through model. class Campaign(models.Model): name = models.CharField(max_length=50) description = models.TextField() owner = models.ForeignKey(User, related_name='owned_campaigns', on_delete=models.CASCADE) members = models.ManyToManyField(User, related_name='campaigns', through='Membership') class Membership(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) is_dm = models.BooleanField(default=False) If I want to fetch all campaigns that the user is a member of, I can simply do something like this: >>> from auth.models import User >>> user = User.objects.get(pk=1) >>> campaigns = user.campaigns.select_related('owner') >>> print(campaign) This does an INNER JOIN to fetch the owner of the campaign, so that prevents having to do an extra query. Great! However, when I also want to return the array of members (with the nested user info for each member), then it does one extra query to fetch the members, and then one extra query for every member to fetch the user object. I am noticing this specifically in Django REST Framework where I have serializers like this: class MembershipSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Membership fields = ["is_dm", "user"] … -
saving events in fullcalendar using django
I am trying to create a calendar but I can't save any event I want to save to my sqlite db I am using django and django reset framework i think the problem is with the serializer this is the request data it may help <QueryDict: {'title': ['test'], 'start': ['1630627200000'], 'end': ['1630713600000'], 'url': ['test']}> view.py class SnippetSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) url = serializers.URLField(required=False, allow_blank=True) start = serializers.DateField(required=False) end = serializers.DateField(required=False) def create(self, validated_data): return CalendarEvent.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title',instance.title) instance.url = validated_data.get('url',instance.url) instance.start = validated_data.get('start',instance.start) instance.end = validated_data.get('end',instance.end) instance.save() return instance class addDateEvents(APIView): authentication_classes = [] permission_classes = [] def post(self,request,**kwargs): serializer = SnippetSerializer(data=request.data) 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) js $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay', }, defaultDate: get_current_data(), navLinks: true, // can click day/week names to navigate views selectable: true, selectHelper: true, editable: true, eventLimit: true, // allow "more" link when too many events select: function(start, end) { var title = prompt('Event Title:'); var url = prompt('Event Url') var eventData; $.ajax({ url : 'http://127.0.0.1:8000/api/add/event', data :'title='+ title+'&start='+ start +'&end='+ end+'&url='+url, type : 'POST', success:function(json){ $('#calendar').fullCalendar('refetchEvents'); console.log('Event Added') } }) if (title) { eventData = { title: title, url … -
Get all information on 1 QueryDjango
I am trying to get all values in a single queryset, i have the following model: class Temporal(model.Models): id = models.UUIDField(default=uuid.uuid4, primary_key=True) value=models.CharField(max_length=60) created_at = models.DateTimeField(auto_now_add=True) date_start = models.DateTimeField(auto_now_add=True) date_end = models.DateTimeField(auto_now_add=True) rate_name = models.ForeignKeyField("RateName") concept_payment = models.CharField(max_length=60) order = models.IntegerField(null=True, blank=True) and some other fields... I am getting all the diferente concept_payment this way: energy_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Energy').first() demand_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Demand').first() other_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Others').first() taxes_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Taxes').first() and so on where the only difference is the concept_payment, So I was wonder if there is a way to get them all, using annotate instead of getting one by one, the concept payment are dynamic so I think I would have to get all the differents concetps first. Thanks in advance -
Invalid Credential Provided error on heroku
I try to link my django project to heroku and keep getting Invalid credentials provided. I have use heroku before but now I just don't understand what is happening I also get to see https://cli-auth.heroku.com/auth/cli/browser/8 which opens up in the web browser and shows bad request -
unsupported operand type(s) for -: 'method' and 'method'
I am building a Blog App and I was trying to implement up vote and downvote in blog. Than i thought about that If there are 4 upvotes and 2 downvotes then it will show only 2 votes Like :- upvotes - downvotes So I tried to implement it BUT when I try to do calculation in view than an error is keep showing unsupported operand type(s) for -: 'method' and 'method' models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') vote_up = models.ManyToManyField(User,related_name='vote_up',blank=True) vote_down = models.ManyToManyField(User,related_name='vote_down',blank=True) views.py def blogpost_detail_view(request,pk): post = get_object_or_404(BlogPost,pk=pk) upvotes_count = post.vote_up.count downvotes_count = post.vote_down.count show = upvotes_count - downvotes_count context = {'show ':show ,'post':post} Traceback from Terminal Traceback (most recent call last): File "D:\app\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\app\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app\views.py", line 31, in blogpost_detail_view show= upvotes_count - downvotes_count TypeError: unsupported operand type(s) for -: 'method' and 'method' I also tried by -= but it did show same error Than i tried by adding the calculation in brackets but same error. Any help would be much Appreciated. Thank You in Advance. -
JSONDecodeError when trying to make request counter with Django
So I wanted to make a "reqcount" thing in my django project using a JSON file but when I run it I get this error: Environment: Request Method: GET Request URL: http://localhost:8000/testing/reqcount/ Django Version: 3.2.6 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'testing'] 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 "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\chris\Desktop\WEBSITE\testing\views.py", line 17, in req_count return HttpResponse(json.load(f)) File "c:\users\chris\appdata\local\programs\python\python38\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "c:\users\chris\appdata\local\programs\python\python38\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /testing/reqcount/ Exception Value: Expecting value: line 1 column 1 (char 0) This is my views.py code (ignore the "hello" function): from django.shortcuts import render from django.http import HttpResponse import json def hello(request): return HttpResponse('Hello, World!') def req_count(request): # TODO: Update the amount of requests the "reqcount" url has gotten, then return it with open('..\\data.json', 'w+') as f: data = json.load(f) data['views']['reqcount']['reqs'] += 1 json.dump(data) return HttpResponse(data['views']['reqcount']['reqs']) NOTES: … -
How to convert an image to `InMemoryUploadedFile` when an URL of the image is received in DRF?
I have a response where the image URL is displayed, but when I try to send PUT/PATCH request then it raises an error as:- Here's the response:- { "floorplan": { "floor": 32, "image": "http://127.0.0.1:8000/media/floorplans/71d3e751-d38f-416f-ac22-d6ddb3fa3541.jpg" } } When A PUT request is sent:- { "floorplan": { "image": [ "The submitted data was not a file. Check the encoding type on the form." ] } } But when I try to send a request with an actual image uploaded, it works fine. This my serializer:- class NestedFloorplanSerializer(serializers.ModelSerializer): class Meta: model = FloorPlan fields = ( 'floor', 'image', ) I tried override the to_internal_value what is saw was in actual image is uploaded it is of the type:- <InMemoryUploadedFile: floor_1.jpg (image/jpeg)> and when the url is sent than the value I see in the to_internal_value is this http://127.0.0.1:8000/media/floorplans/71d3e751-d38f-416f-ac22-d6ddb3fa3541.jpg What I am trying to do is not do the validation when the the same url of the image is received in the to internal_value or if possible to convert the url to <InMemoryUploadedFile: floor_1.jpg (image/jpeg)> and then return it?? -
Django and postgres timezone converts to UTC
In my app users provide their timezone and saved. So I handle timezone conversion manually local_time = datetime.now(tz=ZoneInfo(self.time_zone)) Yet still when I save into postgres it is converted back to UTC 0. In the settings: # TIME_ZONE = 'UTC' #commented out USE_L10N = False USE_TZ = False That too did not work, so I made a middleware: # CUSTOM TIME ZONE HANDLER class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): time_zone = "US/Pacific" #will be changed to a fn call if time_zone: timezone.activate(pytz.timezone(time_zone)) else: timezone.deactivate() return self.get_response(request) In settings: MIDDLEWARE = [ ... 'time_log_app.utils.TimezoneMiddleware', ] That too is not working!! I'm pretty much out of hope here, what I'm doing wrong?? Or I should use raw sql for this? -
Achievements in Django
I would like to add the achievements to my website. I would like them not to be assigned automatically, but that the user would add which achievements he made. I can't make a view for it. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Achievement(models.Model): title = models.CharField(max_length=200, null=True) grand = models.IntegerField(default=10, null=True) body = models.TextField() class UserAchievement(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) user_achievement = models.ManyToManyField(Achievement, related_name='user_achievement') achievement_get = models.DateTimeField(auto_now_add=True) vievs.py def achievement_view(request): achievement_list = Achievement.objects.order_by() return render(request, 'achievement/achievement.html', { 'achievement_list' : achievement_list, }) def achievement_get(request, achievement_id): achievement_list = get_object_or_404(Achievement, pk=achievement_id) achi = get_object_or_404(Achievement, pk=achievement_id) try: selected_choice = achievement_list.score_set.get(pk=request.POST['choice']) except (KeyError, Score.DoesNotExist): # Redisplay the question voting form. return render(request, 'achievement/adetail.html', { 'achievement_list': achievement_list, 'error_message': "You didn't select a choice.", 'thanks' : "Good", }) else: a1 = get_object_or_404(Achievement, achievement_id) a1.save() a1.user_achievement.add(name=name) return render(request, 'achievement/adetail.html', { 'achievement_list' : achievement_list, }) urls.py app_name = 'achievement' # przestrzeń nazw aplikacji urlpatterns = [ # ex: /polls/ path('achievement', views.achievement_view, name='achievement'), path('<int:achievement_id>/achievement', views.achievement_get, name='achievement_get'), ] achievement.html {% for achievement in achievement_list %} <li>{{ achievement.title }}</li> <li><fieldset><a href="/{{achievement_id}}/achievement/"> {{ achievement.title }} {{ achievement.grand }}</a></fieldset></li> {% endfor %} When I click on the link, the <int: achievement_id> … -
HTML body content is blocking Nav
Currently working on my first webpage with HTML, CSS, Django and maybe Javascript soon :) My issue is that I've added some images into my main content to test all(Wanted to add a sticky nav) but the main content is somehow overlapping my NAV and i'm not able to click the links of the Nav itself anymore. Inspector where we can see clearly the overlap. HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static '/css/design.css' %}" /> </head> <body> <!--NAVBAR--> <div class="navbar"> <div class="navbar-title"> <a href="{% url 'photos:home' %}">site-name</a> </div> <div class="navbar-links"> <a href="{% url 'photos:home' %}">HOME</a> <a href="{% url 'photos:pictures' %}">PICTURES</a> <a href="{% url 'photos:album' %}">ALBUM</a> </div> </div> <div class="main-content"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> <img src="{% static '/img/1.jpg' %}"> </div> {% block content %}{% endblock %} </body> </html> CSS: body { background-color: #171717; font-family: Helvetica; } /*------------------NAVBAR------------------*/ .navbar, a { color: #FFF; text-decoration: none; font-size: large; margin: 10px; } .navbar-title { float: left; text-align: center; display: block; position: relative; padding-left: 50px; padding-top: 25px; font-style: italic; } .navbar-links { float: right; text-align: center; display: … -
Django form does not work or CSRF_token aborted
Hello I am making Django App. I have a problem with my login form. Whenever I want to login, form does not do anything or it throws csrf token error. Views: def loginView(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f"You successfully logged in {username}") return redirect('home-page') else: form = AuthenticationForm() return render(request, 'shop/login.html', {'form': form}) HTML TEMPLATE: {% extends 'shop/base.html' %} {% block content %} <div class = "form-container"> <form class="form" method="POST">{% csrf_token %} <label for="username">Email:</label> {{form.username}} <label for="password">Passoword:</label> {{form.password}} <button type="submit">Login</button> </form> </div> {% endblock content %} -
Django request.post only contains csrf field, however my form has two inputs: username and password, therefore i can not authenticate and login a user
I am trying to create a login page for my website,i am using bootstrap as css and here is my template below {% extends 'base_lean.html' %} {% block content %} <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="username">Kullanici Adi</label> <input type="text" class="form-control" id="username" placeholder="Kullanici Adinizi Giriniz"> <small id="username-help" class="form-text text-muted">Siteye kayit olduğunuz kullanici adi ile giriş yapınız</small> </div> <div class="form-group"> <label for="password">Şifre</label> <input type="password" class="form-control" id="password" placeholder="Şifreniz"> </div> <button type="submit" class="btn btn-primary">Giriş Yap</button> </form> {% endblock %} In the login screen im posting some username and password data in the input fields however my request.POST only returns: {'csrfmiddlewaretoken':[blablabla]} Therefore i can not authenticate and login users, what is the reason behind that my request.POST does not have form's username and password fields? -
How to deal with a serializer that needs context
I have a situation here where the serializer needs context, basically the request object. class ProductSerializer(ModelSerializer): distance_away = SerializerMethodField(read_only=True) class Meta: model = Product fields = [ 'pk', 'distance_away', ] def get_distance_away(self, obj): coordinates = self.context["coordinates"] distance_in_km = None if coordinates != 'null' and coordinates is not None: lat = float(tuple(coordinates.split(","))[0]) lng = float(tuple(coordinates.split(","))[1]) .... This means I have to pass a context whenever I use or call the serializer. That's fine for normal drf views. Now I am faced with a situation where I need to use the serializer in a ModelObserver class MarketplaceConsumer(GenericAsyncAPIConsumer): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [HasApiKey] @model_observer(Product) async def marketplace_activity(self, message: ProductSerializer, observer=None, **kwargs): await self.send_json(message) @marketplace_activity.serializer def marketplace_activity(self, instance: Product, action, **kwargs) -> ProductSerializer: '''This will return the product serializer''' return ProductSerializer(instance, context={'request': self.request}).data At this point I will get the following error which makes sense(self.request): 'ModelObserver' object has no attribute 'request' This ModelObserver is for handling channel websocket actions. Is there any way to solve this situation? -
'function' object has no attribute 'objects' in django
i am getting a error: AttributeError at / 'function' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.5 Exception Type: AttributeError Exception Value: 'function' object has no attribute 'objects' Exception Location: G:\PYTHON DJANGO 2021 - COMPLETE COURSE\first_django_project\devsearch\project\views.py, line 27, in projects Python Executable: C:\ProgramData\Anaconda3\envs\djangoenv\python.exe Python Version: 3.9.6 Python Path: ['G:\PYTHON DJANGO 2021 - COMPLETE COURSE\first_django_project\devsearch', 'C:\ProgramData\Anaconda3\envs\djangoenv\python39.zip', 'C:\ProgramData\Anaconda3\envs\djangoenv\DLLs', 'C:\ProgramData\Anaconda3\envs\djangoenv\lib', 'C:\ProgramData\Anaconda3\envs\djangoenv', 'C:\ProgramData\Anaconda3\envs\djangoenv\lib\site-packages'] Server time: Sat, 21 Aug 2021 13:18:04 +0000 # models.py from django.db import models import uuid # Create your models here. class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True,blank=True) demo_link = models.CharField(max_length=2000,null=True,blank=True) source_link = models.CharField(max_length=2000,null=True,blank=True) tag = models.ManyToManyField('Tag',blank=True) vote_total = models.IntegerField(default=0,null=True,blank=True) vote_ratio = models.IntegerField(default=0,null=True,blank=True) created_on = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4,unique=True,primary_key=True,editable=False) def __str__(self): return self.title # views.py from django.shortcuts import render from .models import Project # Create your views here. def projects(requests): projects = Project.objects.all() return render(requests,"project/projects.html", {'projects':projects}) -
Django: can't redirect to home page after Registration
So, there's code: views.py from .forms import RegForm, LogForm from django.contrib.auth import logout, login as auth_login # Create your views here. def reg(request): if request.method == 'POST': regform = RegForm(request.POST) if regform.is_valid(): user = regform.save() regform.save() auth_login(request, user) return redirect('/main') else: regform = RegForm() context = { 'regform': regform } return render (request, "users/registration.html", context) and forms.py from django.contrib.auth import authenticate from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django import forms from django.contrib.auth.models import User class RegForm(UserCreationForm): email = forms.EmailField() last_name = forms.CharField() first_name = forms.CharField() class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'date_joined' ] and from users.views import log, reg, loggout urlpatterns = [ path('registration/', reg, name='registration'), ] It just give error: TypeError at /registration/ getattr(): attribute name must be string Request Method: POST Request URL: http://127.0.0.1:8000/registration/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: getattr(): attribute name must be string Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/models/fields/files.py, line 453, in update_dimension_fields Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3 Python Version: 3.9.1 Python Path: ['/Users/sung/Dev/blued', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages'] Server time: Sat, 21 Aug 2021 13:12:27 +0000 /Users/sung/Dev/blued/users/views.py, line 11, in reg user = regform.save() it was working perfectly before, I don't think I changed something, in views.py I also have … -
templatedoesnot exist django
i'm currently taking online course on django, am working right now in part 3 where we deal with template i follow the instructions but everytime i go to mysite/polls i get no template exist error this is my polls/view.py from django.http import HttpResponse from .models import Question from django.shortcuts import render from django.http import Http404 def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def owner(request): return HttpResponse("Hello, world. 9d5a197b is the polls index.") def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) /polls/urls.py from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5/ path('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>/vote/', views.vote, name='vote'), path('owner', views.owner, name='owner'), ] mysite/settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in … -
Is there a way to set the id of an existing instance as the value of a nested serializer in DRF?
I'm developing a chat application. I have a serializer like this: class PersonalChatRoomSerializer(serializers.ModelSerializer): class Meta: model = PersonalChatRoom fields = '__all__' user_1 = UserSerializer(read_only=True) user_2 = UserSerializer() the user_1 field is auto-populated but the client should provide the user_2 field in order to create a personal chat room with another user. My problem is, when creating a new chat room, the serializer tries to create a new user object from the input data thus giving me validation errors. What I really want it to do is to accept a user id and set the value of user_2 field to an existing user instance that is currently available in the database and if the user is not found, simply return a validation error. (the exact behavior of PrimaryKeyRelatedField when creating a new object) I want my input data to look like this: { 'user_2': 1 // id of the user } And when I retrieve my PersonalChatRoom object, I want the serialized form of the user object for my user_2 field: { ..., 'user_2': { 'username': ..., 'the_rest_of_the_fields': ... } } How can I achieve this? views.py class GroupChatRoomViewSet(viewsets.ModelViewSet): permission_classes = [IsUserVerified, IsGroupOrIsAdminOrReadOnly] serializer_class = GroupChatRoomSerializer def get_queryset(self): return self.request.user.group_chat_rooms.all() def … -
django context processor not working on mobile device
context processor show numerical value on template, it work fine on dev and desktop production. but in mobile device the value is always 0, no error. the value shows the total amount in CART of the products added. any clue why is not working? -
Django Queryset Postgres
I am writing queryset that will return this type date total_shipping_fee 2021-04-16 5,000 2021-04-17 100,000 where class Payments(models.Model): created = models.DateTimeField() ..... SELECT DATE(created) from payment_payment .... group by 'created' -> outputs a correct query My question is how to query/ or cast Payment.objects.filter(created_range=("2021-05-14", "2021-05-14")).values('created').annotate(total_shipping_fee=Sum('total_shipping_fee')) so that I can have queryset in above raw sql. I think that is my problem to CAST DATE(created) in django queryset. Thanks