Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Rest-Framework: No Attribute HelloViewSet
I am trying to build a simple REST API. I tried adding a viewset, somehow I get an error that there is no such attribute. If I remove the viewset and just run using the APIView, it loads just fine. I am stuck. What could be the problem? What should I do to make it work? Here's the rest_profiles.views.py FILE: from django.shortcuts import render from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import HelloSerializer # Create your views here. class HelloApiView(APIView): '''Test API View''' serializer_class = HelloSerializer def get(self, request, format=None): '''Returns a list of API features''' an_apiview = [ 'Uses HTTP methods as functions (get, psot, put, patch, delete)', 'Similar to Django View', 'Mapped manually to URLs' ] return Response({'message': 'Hello from HelloAPIVIew', 'an_apiview': an_apiview}) def post(self, request): '''Create Hello Message''' serializer = HelloSerializer(data=request.data) if serializer.is_valid(): name = serializer.data.get('name') message = 'Hello {0}'.format(name) return Response({'message': message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request): '''Handles Updates''' serializer = HelloSerializer(data=request.data) return Response({'message': 'put'}) def patch(self, request, pk=None): '''Handles partial Updates''' serializer = HelloSerializer(data=request.data) return Response({'message': 'patch'}) def delete(self, request, pk=None): '''Handles deleting items''' serializer = HelloSerializer(data=request.data) return Response({'message': 'delete'}) class HelloViewSet(viewsets.ViewSet): … -
how to assign pointfield to current user location using geolocation API
i'm new to geodjango i want to make real world gis project with geodjango to find locations i tried this class Place(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) address = models.CharField(max_length=100) slug = models.SlugField(unique=True,blank=True,null=True) description = models.TextField() location = models.PointField(srid=4326) views.py class PalceCreateView(CreateView): queryset = Place.objects.all() def form_valid(self,form): lat = self.request.POST['lat'] lon = self.request.POST['long'] coords = Point(lat,lon) form.instance.location = coords form.save() return super(PalceCreateView,self).form_valid(form) my forms.py class PlaceForm(forms.ModelForm): class Meta: model = Place fields = [ 'name','description','location','city','tags' ] read_only_fields = ['location'] my template <form enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="hidden" name="lat" id="lat"> <input type="hidden" name="long" id="long"> {{form}} <input type='submit' value='submit'> </form> <script> navigator.geolocation.getCurrentPosition(function(location) { lat = location.coords.latitude; long = location.coords.longitude; document.getElementById('lat').val = lat document.getElementById('long').val = long }); </script> but when i submit the form it will raise this error Invalid parameters given for Point initialization. how to assign to location field thanks i'm new to geodjango if someone can recommend me an open source project i appreciate it -
How to display with javascript django project's image without static path?
js code on Windows: f_name = '06-55.jpg'; imga = '<img src="static/img/'+f_name+'" >'; $('#loaded').append(imga2); image is located at: /static/img/06-55.jpg On Windows machine it works. On linux I have same paths, but js can't find image. I'm missing something or It's just stupid mistake somewhere? -
pass if code in django, if something in data -> pass
my code is take reques.body and into data var. and if data dic in username or email or telephone then checking password. and if password collect i return token. but my code is just pass all if. i think if @ in dic it is can check key in dic i used httpie and send password and telephone or email or username. but all pass. i dont know what i mistake. plz help me! class UserLoginView(View): def post(self, request): data = json.loads(request.body) check_password = int(data['password']) check_username = 'username' if check_username in data: login_username = data['username'] login_user = User.objects.filter(username=login_username) if login_user is None: return JsonResponse({'message':'have not this ussername User'}, status = 400) elif login_user is login_username: get_user = User.objects.get(username=login_username) if check_password is not get_user.password: return JsonResponse({'message':'Not collect password'}, status = 400) else: encoded_token = jwt.encode({'user': login_user}, 'wecode', algorithm='HS256') return JsonResponse({'token':encoded_token}, status = 200) elif 'email' in data: login_email = data['email'] login_user = User.objects.filter(email=login_email) if login_user is None: return JsonResponse({'message':'have not this emain User'}, status = 400) elif login_user is login_email: get_user = User.objects.get(email=login_email) if check_password is not get_user.password: return JsonResponse({'message':'Not collect password'}, status = 400) else: encoded_token = jwt.encode({'user': login_user}, 'wecode', algorithm='HS256') return JsonResponse({'token':encoded_token}, status = 200) elif 'telephone' in data: … -
When I run `./manage.py runserver`, it starts two processes. How to enable interprocess data sharing and interprocess calls?
I also use apscheduler lib inside the Django webserver handler. I want to create a single instance of apscheduler and communicate all calls to it. Is the best solution to create a different process specifically designated for apscheduler instance? A similar questions are [1] and [2]. [1] How to enforce only one running instance of a process in python Django framework? [2] Make sure only one worker launches the apscheduler event in a pyramid web app running multiple workers -
How to iterate iterate over a list a filter it according to a second list
I have a list of videos that belong to courses. I want to display those videos in a template grouped by courses: first all videos from a course, then a separator and all the videos of the next course. I already have a query_set grouped by course but I cannot find out how to display them separated in my html file. Any hints? Ideas? -
how to include template with context in navbar?
In base.html I have included navbar {% include 'partials/navbar.html' %}, now I need to do context for navbar.html. I trying to make context for navbar.html in this way: view.py def unread_conversation(request): if request.user.is_authenticated: conversations_all = Conversation.objects.filter(Q(starter=request.user) | Q(receiver=request.user)) for conversation in conversations_all: unread = Message.objects.filter(Q(conversation_id=conversation.pk) & Q(seen=False) & ~Q(user=request.user)) context = { 'unread': unread } return render(request, 'conversations/unread_message.html', context) else: messages.error(request, 'register please') return redirect('register') unread_message.html {% if unread %} <span>You have new message</span> {% endif %} navbar.html {% include 'conversations/unread_message.html' with unread=unread %} but it does not work for me, can you correct my way or offer me a better way of this? -
How to ensure idempotency in a Django REST API?
Say, I'm building a REST API based on Django/DRF and PostgreSQL. I want all GET, PUT, DELETE endpoints to follow the best practices and be idempotent. How can I ensure/verify that this is true? -
How to set Django model default value equal to result of a query
I'm quite new at Django, and trying to create a model where det default value for Foreign Keys user and department are set to the correct values for the logged in user. Normally I use the request object and queries the database, but in the model definition I don't know how to do this. I suppose a path forward is to make default value a function and make the query in the function, but I am stuck. Any help are greatly appreciated . Here is an example of my code: from django.contrib.auth import get_user_model from django.db import models from another_app.models import Department, DepartmentPermissions class Article(models.Model): header = models.CharField(max_length=200) text = models.CharField(max_length=800) owner = models(get_user_model(), related_name='owner_article', on_delete=models.PROTECT) department = models.ForeignKey(Department, on_delete=models.CASCADE) #here I want it defaulted to DepartmentPermissions.objets.get(user= <logged in user>)[0].department -
How to design a model and its child django
How to design a model in django for storing below JSON values in a single model class Bus(models.Model): source = models.CharField(max_length=200) destination = models.CharField(max_length=200) type= models.CharField(max_length=200) price=models.FloatField() I need to accept below json to accept and store in same table if i can use ListField , then how it will be for connections { "source": "delhi", "destination": "pune", "type": "Economy", "price":300.0, "Connections": [ { "source": "lon", "destination": "liverpool", "type": "luxury", }, { "source": "banglur", "destination": "cochin", "type": "luxury", } ], } -
How to have Django templates display slugs
Hi guys i am new to django...i been watching youtube videos and reading books on Django but am still struggling with templates. I am working on a ecommerce project and i would love a bit of help with templates. So i want my template to display a list of categories as links on a sidebar. I have defined a slug field in my category models and i have managed to map a url...but i am still not getting a list of categories on my index page sidebar. This is my url pattern and this is working perfect. When i click 127.0.0.1.000/food it's working (food is a category) path('<slug:category_slug>/', views.category, name='category'), the view function def category(request, category_slug): """Defines category views""" categories= get_object_or_404(Category, slug= category_slug) context = {'categories': categories} return render(request, "categories_list.html", context) This is the categories_list.html template that i need help with <h3> Shop by Category </h3> {% if category in categories %} <li> <a href ="{{category.slug}}"> {{category.name}}</a> </li> {% endif %} My wish is to have the categories displayed on the sidebar of my index page as links. I have used {% include 'category_list.html' %} on my index page template, and its only displaying the Shop by Category heading instead … -
Get List of Categories on the basis of foreign model in django
I've two models as below. class Category(models.Model): title = models.CharField(max_length=55) class Meta: verbose_name = 'Food Category' verbose_name_plural = 'Food Categories' def __str__(self): return self.title class FoodItem(TimeStampWithCreator): CATEGORY_CHOICES = ( ('takeway', 'Takeaway'), ('dine_in', 'Dine In'), ('function', 'Function'), ) type_menu_select = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='takeway') category = models.ForeignKey(FoodCategory, on_delete=models.CASCADE) i want to filter all the categories containing takeaway, I've no idea how to achieve this -
DJango user not logging out
I'm new to DJango and I'm trying to make a user auth. My login is working fine but my user isn't logging out. My Logout view is: from django.contrib.auth import logout from django.contrib.auth.models import User class LogoutView(generic.View): @staticmethod def get(request): if User.is_authenticated: # Debug statement print('if') logout(request) return redirect('login') else: print('ekse') return redirect('index') My url is working fine because when i go to /logout/, My debug statement executes but if User.is_authenticated: always returns an object(true). How can I resolve this issue. Thanks -
Same query set, different result in django
I get a different result when I filter another time with the same filters. This code is part of the get_queryset() of a class that inherits ListAPIView. validity_filters = Q( ( ( Q(display_publisher_group__publishers__id__exact=98) | Q(display_publisher_group__isnull=True) ) & ( ~Q(blacklist_publisher_group__publishers__id__exact=98) ) ) ) campaigns = Campaign.objects.filter(validity_filters) print(1, campaigns.distinct().count()) campaigns = campaigns.filter(validity_filters) print(2, campaigns.distinct().count()) The output is: 1 33276 2 33275 -
App 'category' doesn't provide model 'category'
Django==3.0.6 class Category(CommentMixin, TitleMixin, SlugMixin, models.Model): pass from category.models import Category class Post(TitleMixin, SlugMixin, DescriptionMixin, models.Model): ... category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='blog_posts') The database has been dropped and recreated. All migrations have been deleted. In settings.py 'post' and 'category' are added. When making migrations: ValueError: The field post.Post.category was declared with a lazy reference to 'category.category', but app 'category' doesn't provide model 'category'. Could you help me understand what is going on here? -
I am getting error ModuleNotFoundError: No module named 'rest_framework'
if I try to install rest fremwork by command pip3 install Django rest framework then it is showing Requirement already satisfied. -
How to handle AJAX POST request in Django
I have a sort of twitter like button function in my app such that, when the button is clicked, it triggers an AJAX call and performs the action specified in the views. However, when i click the button, it does not perform action in views. The code reaches the 'like view' but does not execute anything after 'if request.POST:'. Please help. Menu.html <form action="{% url 'like'%}" id="plt_{{menu.id}}" data-id="{{menu.id}}" method="post"> {%csrf_token%} <input name="menu_id" type="hidden" value="{{ menu.id }}"> <div class="like-button" id="btn_{{menu.id}}"></div> </form> <script> $('.like-button').on('click', function () { var id = $(this).attr('id'); id = id.replace('btn_',''); $(this).toggleClass('animate').promise().done(function () { var link = $("#plt_"+id).attr('action') $.ajax({ type: 'POST', url: link, headers: {'X-CSRFToken': '{{ csrf_token }}'}, }) }); }); </script> Views.py def like(request): print('reached') //this prints if request.POST: menu = Menu.objects.get(pk=request.POST.get('menu_id')) //execute code to like return HTTPResponse('') -
Django restframework, Authentication credentials were not provided
I took a tutorial in Redox and Django from youtube from Traversy Media. I follow along with the tutorial and now I don't know were it curshed. curl http://localhost:8000/api/auth/login/ -d \ '{"username": "Tom", "password": "PassWord@321"}' \ -H "Content-type: application/json" -X POST By doing so I need to get user and the corresponding token but instead I'm getting {"detail":"Authentication credentials were not provided."} What all I did => # settings.py INSTALLED_APPS = [ 'leads', 'rest_framework', 'frontend', 'accounts', 'knox', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("knox.auth.TokenAuthentication", ), } # serializers.py class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") # api.py class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data = request.data) serializer.is_valid(raise_exception = True) user = serializer.validated_data _, token = AuthToken.objects.create(user) return Response({ "user": UserSerializer(user, context = self.get_serializer_context()).data, "token": token }) # leadmanager/urls.py urlpatterns = [ path("api/auth/", include("accounts.urls")), ] # accounts/urls.py urlpatterns = [ path("login/", LoginAPI.as_view()), ] I don't know were it crushed. -
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response?
I am using react for my frontend and Django restframework for API. I am getting Access to XMLHttpRequest at 'xxxxxxxx' from origin 'xxxxxxxx' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. I have enabled "corsheaders" at my installed app, 'corsheaders.middleware.CorsMiddleware' at Middleware and CORS_ORIGIN_ALLOW_ALL = True and CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] in setting.py. Can anyone guide why i am getting this issue. Whether it is from client side or Server side. -
django.db.utils.OperationalError: no such table - after deleting all Django migrations
I had some issues with my database(design) and deleted all migrations, but not the db.sqlite3 file. I then rewrote my models.py, re-registered them inadmin.py and ran python3 manage.py makemigrations and python3 manage.py migrate. Both seemed to work fine and create the tables. In the Django admin interface, I can see my new tables, but when trying to access them or do something in my views.py with them i get this error (in this case for table orders_dish: django.db.utils.OperationalError: no such table: orders_dish Can anyone help me? Am really stuck here... Below the full traceback: Internal Server Error: /admin/orders/dish/ Traceback (most recent call last): File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: orders_dish The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/contrib/admin/options.py", line 574, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response … -
Django access fields of model with many to many relationship
So I have the following models: class Image(models.Model): image=models.ImageField(upload_to='postimages') id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) class Post(models.Model): title=models.CharField(max_length=500) created_date=models.DateField(auto_now=True) id=models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) images=models.ManyToManyField(Image) user=models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, related_name='posts') In my views I have created a post object like this: post=Post(title=title) post.save() post.images.add(image) Now I need to diplay the image field of the Image model in my homepage. I am trying to do it like this: {%for post in posts%} <img src="{{post.images.image}}"> {%endfor%} But this returns image with src=(unknown). So my question is how do I access the image field of the Image model? -
'NoneType' object has no attribute 'nazev_zanru' although it should have
Good day community, I need your help as I cannot proceed with my project. Django model.py returns an AttributeError: 'NoneType' object has no attribute 'nazev_zanru' My models.py is as follows; from django.db import models class Zanr(models.Model): nazev_zanru = models.CharField(max_length=80, verbose_name="Žánr") def __str__(self): return "Nazev_zanru: {0}".format(self.nazev_zanru) class Meta: verbose_name = "Žánr" verbose_name_plural = "Žánry" class Film(models.Model): nazev = models.CharField(max_length=200, verbose_name="Název Filmu") rezie = models.CharField(max_length=180, verbose_name="Režie") zanr = models.ForeignKey(Zanr, on_delete=models.SET_NULL, null=True, verbose_name="Žánr") def __str__(self): return "Nazev: {0} | Rezie: {1} | Zanr: {2}".format(self.nazev, self.rezie, self.zanr.nazev_zanru) class Meta: verbose_name = "Film" verbose_name_plural = "Filmy" As far as I understand, the def __str__(self): return "Nazev: {0} | Rezie: {1} | Zanr: {2}".format(self.nazev, self.rezie, self.zanr.nazev_zanru) code refers through zanr = models.ForeignKey(Zanr, on_delete=models.SET_NULL, null=True, verbose_name="Žánr") to class Zanr(models.Model): nazev_zanru = models.CharField(max_length=80, verbose_name="Žánr") def __str__(self): return "Nazev_zanru: {0}".format(self.nazev_zanru) ` which is therefore defined. Where is the mistake? Migrations, URLs and admin done. Thank you in advance, David -
Django URL routing
I am learning Django and progressing well but i am stuck on how to configure the different urls to view functions. I created a project TenancyMGt and an app rentals. I have created several views in the module views.py Two are relevant here: def createTenant(request): form = TenantsForm context = {'form': form} html_form = render_to_string('rentals/partial_tenant_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) class TenantsListView(ListView): model = Tenants context_object_name = 'tenant_list' template_name = 'rentals/tenants_list.html' paginate_by = 5 def get_queryset(self): return Tenants.objects.all() Now i created a file urls.py under the app rentals: from . import views from django.urls import path app_name='rentals' urlpatterns = [ path("", views.TenantsListView.as_view(), name="index"), path("",views.TenantDetailView.as_view,name="detail"), path("",views.createTenant, name='createTenant'), path("<int:pk>/",views.TenantUpdateView.as_view, name='edit'), path("<int:pk>/",views.delete, name='delete'), ] under TenancyMgr/urls, i add the following: from django.contrib import admin from django.urls import path,include from rentals import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('rentals.urls')), ] When i run the server, the index view opens successfully! From the index, i want to open the createTenant view as below. <button type="button" class="btn btn-primary js-create-tenant" data-url="{% url 'rentals:createTenant' %}> <span class="glyphicon glyphicon-plus"></span> New Tenant </button> When the button is clicked, i get the urls below: http://127.0.0.1:8000/rentals/createTenant/ Then i get the response is 404,page not found error. But this opens admin … -
how can I avoid hide lesson content from end user views-template?
I am trying to do this all vip user paid that contains type 2 allow to see the full information , but however it does as expect, but with a minor issue , it hide the lesson to the end-user if this doesnt belong to x user logged. I want to keep lesson displayed to the end-user, but however if the user tries to click to the lesson then display upgrade account instead of hidding content. how can I achieve this? model class Lesson(models.Model): content_title = models.CharField(max_length=120) content_text = models.CharField(max_length=200) thumbnail = models.ImageField(upload_to='xxx/xxx/xxx/xxx/xxx') link = models.CharField(max_length=200, null=True) allowed_memberships = models.ManyToManyField(Membership) def __str__(self): return self.content_title view def get_context_data(self, **kwargs): context = super(bootCamp, self).get_context_data(**kwargs) lesson = Lesson.objects.first() user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type lesson_allowed_mem_types = lesson.allowed_memberships.all() context['lessons_allowed_mem_types'] = lesson_allowed_mem_types context['lessons'] = None if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): if Lesson.objects.filter(allowed_memberships=1): context['lessons'] = Lesson.objects.filter(allowed_memberships=1).values() elif Lesson.objects.filter(allowed_memberships=2): context['lessons'] = Lesson.objects.filter(allowed_memberships=2).values() else: pass return context template {% if lessons is not None %} {% for lessson in lessons %} <div class="col-md-3"> <a href="/{{ lessson.link }}"> <div class="item"> <div class="content-overlay"></div> <img src="/{{ lessson.thumbnail }}" /> <div class="content-details fadeIn-bottom"> <h3 class="content-title">{{ lessson.content_title }}</h3> <p class="content-text">{{ lessson.content_text }}</p> </div> </div> </a> </div> {% endfor %} {% else %} <p>upgrade</p> {% endif %} -
django not redirecting from CreateView
So I initially thought that the submit button was not working, but looking in the database, it is POSTing to the database, but it is not clearing the form and going to the success url, any ideas what I'm doing wrong here? <!DOCTYPE html> {% extends "project_portal/base.html" %} {% block detail %} <div class="project_setup"> <h1>Project Setup</h1> <form class="update" method="POST"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" class="btn" value="Submit"> <a href="{% url 'project-list' 0 %}">Cancel</a> </form> </div> {% endblock %} and here is the view: class ProjectCreateView(CreateView): template_name = 'project_portal/project_create.html' form_class = ProjectModelForm queryset = Project.objects.all() success_url = '/si/home/0/' def form_valid(self, form): user = self.request.user form.instance.user = user return super().form_valid(form)