Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django get() got an unexpected keyword argument 'pk'
Using Django version 3.2.4 I'm following the django documentation https://www.django-rest-framework.org/tutorial/3-class-based-views/ rest > urls.py from django.urls import path from rest import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('', views.SnippetList.as_view()), path('<int:pk>/', views.SnippetList.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) rest > views.py class SnippetDetail(APIView): """ Retrieve, update or delete a snippet instance. """ def get_object(self, pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http404 def get(self, request, pk, format=None): snippet = self.get_object(pk) serializer = SnippetSerializer(snippet) return Response(serializer.data) def put(self, request, pk, format=None): snippet = self.get_object(pk) serializer = SnippetSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): snippet = self.get_object(pk) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT) On request url http://127.0.0.1:8000/snippets/1/, I get this error: TypeError at /snippets/1/ get() got an unexpected keyword argument 'pk Am I missing something here? -
Django what to do when 2 people simultaneously purchase
I was wondering if anyone know what to do when I have a physical product and 2 people simultaneously purchase at the same time with the stock of 1? How do I make sure that even if they have the product in their cart they can't keep going forward with the payment process if the other person payed before them. Also if they haven't started the payment process and they just logged back into the website and they checked their cart(if they had the product in their cart already) I want it where they inform the users why they deleted the product from their cart. Something like this Ex:"Due to the product being out of stock we placed it in your wishlist...". Don't have a wishlist so just saying we deleted it from your cart. If anyone can help me with this I would be grateful because everytime I look this up I can't find any info about it. Only about other stuff and I'm thinking Im the only one going through this. Can someone explain what to do like really how to do it. This is my github if anyone just wants to help on their and check my … -
what is this Keep the license and copyright notice included in Bootstrap’s CSS and JavaScript files when you use them in your works?
I have developed a website using django and I have used getbootstrap4.3 in my website. In the offcial website ,they have stated like this: It requires you to: Keep the license and copyright notice included in Bootstrap’s CSS and JavaScript files when you use them in your works I really dont uderstand this,what is copyright notice and where i should include ??????? -
I have imported app1's models into app2's views.py and trying to create a new row to insert like this but its not showing any new rows in db..why?
import datetime curr_datetime=datetime.datetime.now() from subcriptions.models import childtransactions obj1=childtransactions.objects.filter(outlet_id=outlet_id).last() obj2=childtransactions(transaction_no=obj1.transaction_no,plan_subcription=obj1.plan_subcription, plan_deduction_type=obj1.plan_deduction_type,payment_status=obj1.payment_status,payment_date=curr_datetime,original_balance_amount=obj1.original_balance_amount,debit_amount=5, balance_amount=float(obj1.balance_amount)-float(obj1.debit_amount), credit_amount=obj1.credit_amount,outlet_id=outlet_id,kit_id=obj1.kit_id,remarks=obj1.remarks, is_paid=obj1.is_paid,customer_reach=obj1.customer_reach,own_transactions=obj1.own_transactions, topup=obj1.topup) obj2.save() whats wrong?? and how do i solve it? -
Trying to load multiple Cloudinary images in Django template
There is slightly complex logic in displaying images and I need to display another image if one does not exist. However, it's slow to put it on the backend because the object is currently a dictionary. Is there a way that I can find workable images with the HTML image tag? <picture> <source srcset="https://res.cloudinary.com/.../{{ object.id }}.png" > <source scrset="https://res.cloudinary.com/.../{{ object.system }}.png"> <source scrset="https://res.cloudinary.com/picture.svg"> <img src="https://res.cloudinary.com/.../{{ object.id }}.png" class="mx-auto" width="250px" alt="" /> </picture> The problem is that only the default image shows up and the other source images do not. Is there another way that I could display another image if one fails? -
Put items on top in django template for loop
The model has a field named "is_highlighted", i want to put all items on top if is_highlighted == True when iterate thru the object list. -
How to make Django Webpage run real-time data from Firebase?
I'm having problem on making real-time data temperature data on DJANGO website, I am able to retrieve the data from Firebase by using Raspberry Pi + MLX90614 IR sensor to push temperature data to Firebase and display on DJANGO webpage. website showed my mlx90614 sensor temperature data But I'm unable to make it real-time, the temperature data only updated when I refreshed the browser, I want to make it in real-time which I use the If-else statement in views, where the strings can updated instantly but not manually refreshing the browser. In below is my code VIEWS & TEMPLATES (HTML): Sample Code Sample Code2 I'm making a E-health website for my Final Year Project with DJANGO & Raspberry Pi. Please give me some advice to me, Thank you! (>_<) -
Django nested model rest frame wrok
Models.py class Persion (models.Model): name = models.TextField(max_length=300) age = models.IntegerField() class Address(models.Model): city = models.TextField(max_length=300) state = models.TextField(max_length=300) Serializer.py: class AddressSerializer(serializers.ModelSerializer) : class Meta: model = Address fields ='__all__' class PersionSerializer(serializers.ModelSerializer): address = AddressSerializer( required= True) class Meta: model = Persion fields = ['name', 'age' , 'address'] Error Message: Got AttributeError when attempting to get a value for field address on serializer PersionSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Persion instance. Original exception text was: 'Persion' object has no attribute 'address'. What am i missing? I need output like this [ { name:"nikhil", age: 24, address:{ city:"coimbatore", } }] -
Django form validation ran before calling to_python
Background: I have a model with a CharField that should be limited to let's say 100 characters. I render it with Textarea, which allows for newlines as expected. However, different browsers handle the maxlength attribute and newline character differently, sometimes posting them as \r\n (2 characters) but counting as only 1 character when entered. To deal with this, I want my server to strip \r from the field before validating to standardized across different browsers and for a better user experience, i.e. allow users to enter the full 100 characters, counting newlines as only 1 character. After reading Django documentation on Form and field validation and various stackoverflow posts, it seems pretty clear that Field.to_python(self, value) on the model is run before ANY form validations. Thus, it would be the best place for me to do this and keep my code DRY. However, it seems like there are some other validation running that I wasn't able to track down, before the call to to_python. Since if I pass exactly 100 characters in the browser (when newline is still counted as \r\n), I still get the error Ensure this value has at most 100 characters (it has 109). To test out … -
Redirect to login view when logout button is clicked in different app
There are two apps in my Django project: account and boards. In account, I have login and logout views as following: #account/views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from .forms import LoginForm def user_login(request): login_msg = "" if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): cleaned_data = login_form.cleaned_data user = authenticate(request, username=cleaned_data['username'], password=cleaned_data['password']) if user is not None: if user.is_active: login(request, user) return redirect('boards:home_board') else: login_form = LoginForm() return render(request, 'account/login.html', {'login_form': login_form, 'login_msg': login_msg}) def user_logout(request): logout(request) return redirect('login') #account/urls.py from django.urls import path from . import views app_name = 'account' urlpatterns = [ path('login/', views.user_login, name='login'), ] There is only a login template, no logout template. The intention is to redirect back to the login template when logout event happens. In the other app boards, in the template home_board, there is a Logout button as following: home_board.html <div id="nav-bar">&nbsp; <button id="logout-button" class="nav-bar-button">Logout</button> </div> How do I call the view function account/logout when this button is clicked, either through Javascript or inline onclick? There is no url to pass to an onclick here. Note that if I do this: <button id="logout-button" class="nav-bar-button" onclick="location.href='{% url 'account:login' %}'"> Logout </button> It will redirect to the … -
Error when returning multiple return statements in a Django view, 'tuple' object has no attribute 'get.'| cs50 web project 4 (network)
I am working on CS50 Network and am supposed to design a Twitter-like social network website for making posts and following users. In my view's return statement I am trying to render a page and a jsonrespone. The JsonResponse is so javascript can access it. The error I get is: 'tuple' object has no attribute 'get.' view (this shows a page of all the posts specific to a user. When a logged in user clicks on the username of a post it passes values. This is how the parameters in the view gets its values.): def profile(request, user_id, username): # list number of followers and following profiles = Profile.objects.all() # get all posts and order them posts = Post.objects.filter(user=user_id).order_by('-timestamp') # pagination pagination = Paginator(posts, 10) page_num = request.GET.get('page') try: pages = pagination.page(page_num) except EmptyPage and PageNotAnInteger: pages = pagination.page(1) # serialize json_posts = serializers.get_serializer("json")().serialize(posts) return render(request, "network/profile.html", { "posts": pages, "user_id": user_id, "username": username, "profiles": profiles, "currentUser": request.user, }), JsonResponse(json_posts, safe=False) models: from django.contrib.auth.models import AbstractUser from django.db import models from django.utils import timezone class User(AbstractUser): pass class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Followers_user") followers = models.ManyToManyField(User, blank=True, null=True, related_name="Followers_followers") following = models.ManyToManyField(User, blank=True, null=True, related_name="Followers_following") def __str__(self): return str(self.user) … -
Navigating Django Apps with home page buttons and page buttons
Quick question and I don't know why this isn't easier to find but how do I switch between the home page index to another app's index page. My current setup: kkquit/index.html - homepage pack/index.html - page I want to link What is the proper way to label a button to go from my index home page to another apps index page? -
AWS EC2 ubuntu python pypi server not getting ConnectTimeoutError
I have a ec2 instance of ubuntu and i am running a dockerized django application. every setup is okey but i see pypi server not getting. Can anyone please tell me what is the possible solution to fix it? I don't have any issue with docker. Also i tried to run pip3 install django outside out docker, yet it's not working. Can anyone please tell me what is the possible solution for this? -
Django project with Javascript function doing nothing
I'm trying to create some Javascript functions to manipulate an HTML page within a Django project, but literally nothing is happening when I create my functions and I can't understand why. I have the feeling it's something extremely basic that I'm missing - I'm brand new to working with Javascript within a Django project. The code below mostly provided by the instructor for a course I'm in and it all works just fine. But when I try to add to the javascript file, I can't get it to do anything. Specifically I'm just trying to create a button that will run a function (compose_email). The function in question has been created for me by the course instructor, and works just fine when the "compose" button is clicked. When I try creating a "test" button to call the compose_email function, literally nothing happens when I click the button. Any tips on what I'm missing here? Again, I feel like it's probably something simple I'm overlooking. Here is the button I added to the HTML file: '<button class="btn btn-sm btn-outline-primary" id="test">TEST</button>' Here is the full HTML file: ''' {% extends "mail/layout.html" %} {% load static %} {% block body %} <h2>{{ request.user.email … -
django-ajax-selects - How to keep the selected option
I was able to successfully deploy django-ajax-selects. When I search for a value on my form I'm able to find it and "lock" that value on the below "display deck" (that's how it's called in the documentation), save everything as expected when I submit the form, however as you can see the text field goes empty. Therefore, the fact that the value I selected disappears from the actual text field is quite confusing to the average person, so I'd like guidance on how I could keep the selected value in both, the "display deck" and the actual text field. I would also like to delete the selected value from both places after clicking on the trash icon (if i needed to). This is how it currently looks when I have selected a value from the dropdown and it's ready to be submitted. Can anyone please provide guidance on how to do that please? My guess is that a customization needs to happen in the Customizing Template documentation. Here's my fairly standard forms.py class StartConversationForm(forms.ModelForm): class Meta: model = Conversation fields = ('circle','conversation', 'detail','conversation_type') circle = AutoCompleteSelectField('circles', required=True, help_text=None) Thanks so much in advance -
'opts = self.remote_field.model._meta' 'AttributeError: 'str' object has no attribute '_meta''
I am somewhat new to django, and I'm trying to build an airbnb clone to better understand django. I keep receiving an error when I attempt to start my server. I'm confused on how to resolve the error. It traces back to my virtual environment file, but I have never wrote any code directly into it. I have found that if I delete the contents of my admin.py file and my models.py file, it silences the error, and my server starts. I assume this suggests the error could be coming from one of those files. Here is the error code: Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/contrib/admin/checks.py", line 54, in check_admin_app errors.extend(site.check(app_configs)) File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 92, in check errors.extend(modeladmin.check()) File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/contrib/admin/options.py", line 122, in check return self.checks_class().check(self, **kwargs) File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/contrib/admin/checks.py", line 648, in check *self._check_list_filter(admin_obj), File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/contrib/admin/checks.py", line 804, in _check_list_filter return list(chain.from_iterable( File "/Users/AUTH_SYSTEM/backend/venv/lib/python3.9/site-packages/django/contrib/admin/checks.py", line 805, … -
How do I set up Postgresql on Django Heroku?
Can someone please provide steps on how to set up a postgresql database to connect to my site? I have a model that I need to create "instances" of. I need them to stay. I was told I need to use a database. I'm having trouble figuring out the right way to set it up. -
Django Rest Framework won't serialize GeoJSON properly
I am trying to calculate a polygon based on latitude/longitude of center point, radius, and number of sides in Django Rest Framework to expose an API. I have it mostly working, but the serializer doesn't convert the property model into a geoJSON properly. I have included my code below Serializer.py from rest_framework import serializers from django.core.serializers import serialize from .models import Circle from rest_framework_gis.serializers import GeoFeatureModelSerializer class CircleSerializer(GeoFeatureModelSerializer): class Meta: model = Circle fields = ('lat', 'lng', 'radius', 'resolution', 'id', 'polygon') geo_field = 'polygon' Views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import CircleSerializer from .models import Circle from django.core.serializers import serialize from django.http import HttpResponse # Create your views here. class CircleViewSet(viewsets.ModelViewSet): queryset = Circle.objects.all().order_by('id') serializer_class = CircleSerializer urls.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'Circle', views.CircleViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] models.py # from django.db import models from django.core.validators import MinValueValidator from django.contrib.gis.db import models from django.contrib.gis.geos import Point import math import decimal # Create your models here. class Circle(models.Model): lat = models.DecimalField(max_digits=10, decimal_places=8) lng = models.DecimalField(max_digits=11, decimal_places=8) radius = models.DecimalField(max_digits=14, decimal_places=8) resolution = models.PositiveIntegerField(validators=[MinValueValidator(3)]) id = models.CharField(max_length=6, primary_key=True) polygon = … -
why do i keep getting this error( Field 'id' expected a number but got ''. ) each time users like a post from their own timeline?
Here is the users account view that i want users to be able to like their post from, it has really been a challenge to get my head around this. would appreciate some help. def account_view(request, *args, **kwargs): """ - Logic here is kind of tricky is_self is_friend -1: NO_REQUEST_SENT 0: THEM_SENT_TO_YOU 1: YOU_SENT_TO_THEM """ context = {} user_id = kwargs.get("user_id") try: account = User.objects.get(pk=user_id) except: return HttpResponse("Something went wrong.") if account: context['id'] = account.id context['username'] = account.username context['bio'] = account.bio context['get_full_name'] = account.get_full_name context['email'] = account.email context['profile_pic'] = account.profile_pic.url context['cover_image'] = account.cover_image.url context['city'] = account.city context['country'] = account.country context['gender'] = account.gender context['hide_email'] = account.hide_email post_id = request.GET.get("likeId", "") try: post_id = Post.objects.get(pk=post_id) except Post.DoesNotExist: liked= False like = Like.objects.filter(user=user, post=post) try: post_list = Post.objects.filter(user_name=account) except Post.DoesNotExist: post_list = Post(user_name=account) save.post_list() posts = post_list.all() context['posts'] = posts Here is my like view, how best do can i accomplish users and friends being able to like their post from their own profile or timeline ? def like(request): post_id = request.GET.get("likeId", "") user = request.user post = Post.objects.get(pk=post_id) liked= False like = Like.objects.filter(user=user, post=post) if like: like.delete() else: liked = True Like.objects.create(user=user, post=post) resp = { 'liked':liked } response = json.dumps(resp) return … -
Problem in embedding an IDE to my website
I've been watching youtube videos on embedding the repl.it IDE to my website. The problem is, in the repl.it IDE, the save option is not available and let alone the copy embed code is also not available. I am in urgent need of an IDE like repl.it, progamiz, etc for my website. Any solution is appreciated. I've tried almost all the online IDEs so far. -
How to start a Dockernized Django server with custom ip address?
When we want to run a bare Django app we use the term: python manage.py runserver <ip>:<port> to start a web server with the desired IP address. I tried to do a similar thing with Docker and Django inside the docker-compose file: version: '3.1' volumes: init-db: data-db: services: mongo: image: mongo restart: always environment: MONGO_INITDB_ROOT_USERNAME: <name> MONGO_INITDB_ROOT_PASSWORD: <password> ports: - 27020:27020 command: mongod --quiet --logpath /dev/null splash: image: scrapinghub/splash ports: - "8050:8050" restart: always web: build: . restart: unless-stopped command: > bash -c "pip install -r requirements.txt && python manage.py makemigrations && python manage.py migrate && python manage.py runserver <some_ip>:<some_port>" tty: true volumes: - .:/usr/src/app ports: - 8000:8000 depends_on: - mongo Now after running it is giving me web_1 | Error: That IP address can't be assigned to. -
Can't get proper response from `issubclass()` when called with Django's `__fake__` model type inside migration
I'm trying to generate UUIDs for some models in a migration. The problem is that the models returned from apps.get_app_config(app_name).get_models() are these __fake__ objects, they are what Django calls historical models, so calling issubclass(fake_model, UUIDModelMixin) returns False when I am expecting True. Is there anyway to determine what parent classes these historical model objects actually inherited from? Relevant Django docs: https://docs.djangoproject.com/en/3.1/topics/migrations/#historical-models And here is the full function being called in a migration: from os.path import basename, dirname import uuid from common.models.uuid_mixin import UUIDModelMixin def gen_uuid(apps, schema_editor): app_name = basename(dirname(dirname(__file__))) models = apps.get_app_config(app_name).get_models() uuid_models = [m for m in models if issubclass(m, UUIDModelMixin)] for model in uuid_models: for row in model.objects.all(): row.uuid = uuid.uuid4() row.save(update_fields=['uuid']) -
How to choose appreciate AWS EC2 instance
I want to deploy a website that uses Django on the server side and reactJs Frontend on AWS. I'm estimating traffic of about 40,000 per month. It happens that Amazon has several hosting packages. I like the EC2 instances but I don't know which particular instance that'll be suitable for me and being cost effective. I want to host for 6 months to get to understand the platform and later extends it if I'm comfortable with their services. The database isn't that robust. I'll also like to add updates at least two times a week. Honestly, I haven't used AWS before and I don't even know if EC2 is the best for my project. Which of the packages will be best for my project? -
Using integers and strings together in Django choice field
I am trying to use the new Enum types in the latest Django version for the choice field. Specifically I am trying to store the various states of United States as follows: class States(models.TextChoices): ALABAMA = 'AL', 'Alabama' ALASKA = 'AK', 'Alaska' ..... ..... WISCONSIN = 'WI', 'Wisconsin' WYOMING = 'WY', 'Wyoming' class PersonalInfo(models.Model): state = models.CharField(max_length=2, choices=States.choices, default=States.ALABAMA) Works as expected. Now, I am also trying to make the max_length variable also a class attribute of the choice class to make the code more modular by doing the following: class States(models.TextChoices): ALABAMA = 'AL', 'Alabama' ALASKA = 'AK', 'Alaska' ..... ..... WISCONSIN = 'WI', 'Wisconsin' WYOMING = 'WY', 'Wyoming' MAX_LENGTH = 2 class PersonalInfo(models.Model): state = models.CharField(max_length=States.MAX_LENGTH, choices=States.choices, default=States.ALABAMA) This gives me an error as follows: if self.max_length is not None and choice_max_length > self.max_length: TypeError: '>' not supported between instances of 'int' and 'States' I understand that Django also provides an alternative IntegerChoices for integer but how do I use both text and integer choices together. -
Can't serialize foreignKey object data
I have one-to-many relation Developer and Constructions I want to serialize all Developer field when I serialize Construction object For request { "developer": 1, "name": "as2", "address": "ZZZZZZZZZZZZZsdf", "deadline": "2020-05-13 14:26:58", "coordinates": { "latitude": 49.8782482189424, "longitude": 24.452545489 } } I have an error: { "developer_data": [ "This field is required." ] } It's strange for me because developer_data marked as read_only How can I fix the error? I thin that problem deals with serializer models.py class Developer(models.Model): name = models.CharField(max_length=100) ... def name_image(instance, filename): return '/'.join(['images', str(instance.name), filename]) class Construction(models.Model): developer = models.ForeignKey( Developer, related_name="constructions", on_delete=models.CASCADE ) name = models.CharField(max_length=100) image = models.ImageField(upload_to=name_image, blank=True, null=True) ... serializers.py class DeveloperSerializer(serializers.ModelSerializer): constructions_number = serializers.SerializerMethodField() workers_number = serializers.SerializerMethodField() machines_number = serializers.SerializerMethodField() class Meta: model = Developer fields = ('id', 'name', ...) def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance class ConstructionSerializer(serializers.ModelSerializer): coordinates = PointField() deadline = serializers.DateTimeField(format=TIME_FORMAT) cameras_number = serializers.SerializerMethodField() developer_data = DeveloperSerializer() class Meta: model = Construction fields = ( 'id', 'developer', 'developer_data', 'name', 'image', 'address', 'coordinates', 'deadline', 'workers_number', 'machines_number', 'cameras_number', ) read_only_fields = ('workers_number', 'machines_number', 'cameras_number', 'developer_data') def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance def get_cameras_number(self, obj): return obj.cameras.count() I use standard ModelViewSet for the models in views.py and i …