Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my response data is not being shown in the postman and how do I see the request data in Django
views.py from django.shortcuts import render from rest_framework import viewsets from django.http import HttpResponse from .serializers import TodoSerializer from .serializers import UserSerializer from .models import Todo from .models import User class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() def get_object(request): return "Added"; class UserView(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() def get_object(request): print("request", request) return "Registered"; class LoginView(viewsets.ModelViewSet): #serializer_class = UserSerializer #queryset = User.objects.all() #print("queryset = ",queryset[len(queryset)-1].email_id) #print("serializer_class = ",serializer_class) def get_object(self,request): return HttpResponse("request") # Create your views here. urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from todo import views router = routers.DefaultRouter() router.register(r'users', views.UserView) router.register(r'todos', views.TodoView) router.register(r'login', views.LoginView) print("In url file") urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ] This is my views.py file and urls.py file. I have a model created for user, with fields- email_id and password CRUD operations are implemented automatically, so how do I validate data passed from the login form in frontend Please tell me what's wrong in the code. I am not able to do the login part. -
Django default cache not used
I have this lines in Django settings: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ["REDIS_URL"], # I tried hard-coding this value as well "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, } } Then I do: python3 manage.py shell >>> from django.core.cache import caches >>> caches["default"] >>> <django_redis.cache.RedisCache object at 0x7f87a61eb730> Cash uses Redis fine, but if I do: >>> from django.core.cache import cache >>> cache <django.core.cache.DefaultCacheProxy object at 0x7f7773164dc0> As you can see, it's not Redis, I checked that it has separate storage, each process has separate cache. Why is it so? Shouldn't from django.core.cache import cache use Redis as cache? I checked many times, "default" not misspelled. -
Issues sending email with django-recpatcha and django-crispy-forms
I'm trying to set up a Contact Form on a client website using the django-recaptcha app and django-crispy-forms. My form data isn't passing is_valid() on POST and I can't figure it out. Any help would be greatly appreciated! (Running Django 3.11 on Windows 10 with Python 3.8.5.) As far as I know, I've set all the configs up according to spec. Here's the models.py: from django.db import models class ContactEmail(models.Model): created = models.DateTimeField(auto_now_add=True) first_name = models.CharField(blank=False, max_length=50) last_name = models.CharField(blank=False, max_length=50) email = models.EmailField(blank=False) phone = models.CharField(max_length=32, blank=True) subject = models.CharField(blank=False, max_length=80) message = models.TextField(blank=False) def __str__(self): return "{} {}: {} ({})".format( self.first_name, self.last_name, self.subject, self.created.strftime("%m/%d/%Y, %H:%M:%S UTC") ) forms.py: from django import forms from django.urls import reverse from .models import ContactEmail from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV3 from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class ContactForm(forms.ModelForm): captcha = ReCaptchaField(widget=ReCaptchaV3(attrs={ 'data-theme': 'dark', 'data-size': 'compact' })) class Meta: model = ContactEmail fields = [ 'first_name', 'last_name', 'email', 'phone', 'subject', 'message', ] def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['captcha'].label = False self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit', css_class='btn-block')) self.helper.form_method = 'POST' self.helper.form_action = reverse('contact') views.py: import datetime from django.contrib import messages from django.core.mail import send_mail from django.http import HttpResponse … -
Django "Exception has occurred: ImproperlyConfigured Requested setting DEBUG, but settings are not configured..." even after setting in manage.py
Sorry, I am a newbie in Django, so please comment if I have forgotten any important information. I have set up my Django App following this VSCode tutorial. In short, it teaches me to build a docker image of a Django App in Venv. When I started to run with VSCode, an error occurred saying that Exception has occurred: ImproperlyConfigured Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.. However, I have os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'yiweis_blog.settings') in my both wsgi.py and manage.py. Meanwhile, when I attach a shell directly to the container, and run python manage.py runserver, it prints Django version 3.1.1, using settings 'yiweis_blog.settings'. I have also tried to assign variable yiweis_blog.settings to DJANGO_SETTINGS_MODULE in dockerfile and export the variable in terminal, but both of them still did not work. Any help is appreciated. Thanks! -
I can't render the image template tag from my Wagtail page model
I'm trying to access an image, feed_image on a blog post page's template but am unable to render it correctly. I have tried passing it specifically to my context variables, calling it directly, through the page.notation, and through wagtail's own {% image %} template function. models.py {BlogPage} class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) quote = models.CharField(max_length=250, default='', blank=True) author = models.ForeignKey('blog.Author', null=True, on_delete=models.SET_NULL) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple) ] promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ] content_panels = Page.content_panels + [ ImageChooserPanel('feed_image'), FieldPanel('date'), FieldPanel('intro'), FieldPanel('body', classname="full"), FieldPanel('quote'), FieldPanel('author') ] parent_page_types = ['blog.BlogIndexPage'] @property def parent_page(self): return self.get_parent().specific def get_context(self, request, *args, **kwargs): context = super(BlogPage, self).get_context(request, *args, **kwargs) context['parent_page'] = self.parent_page context['feed_image'] = self.feed_image context['all_categories'] = BlogCategory.objects.all() return context blogpage.html {% extends "base.html" %} {% load static %} {% load wagtailcore_tags %} {% load wagtailimages_tags %} {% comment %} {% load custom_tags %} {% endcomment %} {% block content %} <section class="blog-post-header" style="background-image: url({{ page.feed_image.url }})"> <div class="container h-100 align-items-center"> <div class="row h-100 align-self-center"> <div class="col my-auto text-center mh-100"> <h2 class="curly text-vivid-green display-4 font-weight-bold">{{ … -
How to post OneToOne field in django rest-framework using overwrite create method
I am trying to override create method to make a post request but i am stuck, here is my code class Order(models.Model): street_number = models.PositiveIntegerField(blank=True, null=True) street_name = models.CharField(max_length=250, null=True, blank=True) class Seller(models.Model): order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='seller_order',blank=True, null=True) first_name = models.CharField(max_length=250, null=True, blank=True) last_name = models.CharField(max_length=250, null=True, blank=True) class OrderSerializer(serializers.ModelSerializer): sellers = SellerSerializer() class Meta: model = Order fields = '__all__' def create(self, validated_data): order = Order.objects.create(**validated_data) seller_validated_data = validated_data.pop('sellers') if seller_validated_data: seller_obj = Seller.objects.create(order=order) seller_obj.first_name = seller_validated_data.get('first_name') seller_obj.middle_name = seller_validated_data.get('middle_name') seller_obj.last_name = seller_validated_data.get('last_name') order.save() return order My json in postman i am sending like below { "street_number":11, "street_name":"dfd", "seller":{ "first_name":"kk", "last_name":"dfdf" } } But i am unable to create seller object with a relation of order, please help me -
Django delivery form
I am building an e-commerce website and at the checkout want the user to fill out delivery form (with address, zip, city etc.). I have made the form in Django, however the delivery works only in certain region and I want to accept addresses in this region. Otherwise, I want user to see that delivery doesn't work in his region. How could I do it? Did anyone face this problem? -
Npm package in Django isn't working on Heroku
I installed a package using npm in my Django app and then moved the folder to my static folder and imported it to base.html with <script src="/static/js/convertapi-js/lib/convertapi.js"></script> This works fine on localhost but when I deploy the app to Heroku it can't find the file. I'm new to Django so any help would be appreciated. -
Ordering Django Chained Queryset
I have a search page which pulls a request from several models and compiles them into separate querysets which are then combined using the chain() function before being rendered to the template. The views.py file looks like this: class SearchResults(ListView): template_name = 'front_end/search_page.html' context_object_name = 'query' def get_queryset(self): query_param = self.request.GET['q'] film_search = Film.objects.filter(Q(title__icontains=query_param)).distinct().order_by('-gross') actor_search = Actor.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') director_search = Director.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') writer_search = Writer.objects.filter(Q(name__icontains=query_param)).distinct().order_by('-career_gross') return list(chain(film_search, actor_search, director_search, writer_search)) This code works but I want to order the final list by 'career_gross' and 'gross' with the instance with the largest value for either of those attributes appearing first in the list. This is a problem as the querysets come from different models - I cannot order the chained list using order_by('career_gross') like I did before (not to mention not all models have a 'career_gross' attribute). To put it simply, can I order chained querysets by the value of different attributes coming from different model instances. -
Hi am new to Django, i want to get the system user/computer name who is accessing my website on intranet and store the hits into a sqlite DB table
how can I get the system/computer/user name of user who is accessing my website on internal network. I want to record the end user hits and to store them in SQLite DB -
django-import-export empty rows before csv header trigger exception while importing
While importing data from csv, I realized that this error is triggered if the first row is not the header list indices must be integers or slices, not str first_name,last_name,email,password,role Noak,Larrett,nlarrett0@ezinearticles.com,8sh15apPjI,Student Duffie,Milesap,dmilesap1@wikipedia.org,bKNIlIWVfNw,Student It only works if the first row is the header first_name,last_name,email,password,role Noak,Larrett,nlarrett0@ezinearticles.com,8sh15apPjI,Student Duffie,Milesap,dmilesap1@wikipedia.org,bKNIlIWVfNw,Student ... I tried overwriting before_import to remove any blank row def before_import(self, dataset, using_transactions, dry_run, **kwargs): indexes = [] for i in range(0, len(dataset)): row = ''.join(dataset[i]) if row.strip() == '': indexes.append(i) for index in sorted(indexes, reverse=True): del dataset[index] return dataset This works for all the rows, except the first row which should always contain the header, and if not the error is thrown. -
How to use websockets client/server between two Celery tasks?
I use Celery and Redis in my Django application to handle tasks and one of them is to subscribe to a websocket stream to receive financial data in an async loop. Of course others Celery tasks need these informations and I'm trying to figure out how to transmit the data to them. So far I tested writting the stream every x seconds into the database, works but consummes CPU. Not really efficient and cannot be real-time. Another solution could be to update a dictionary when fresh data arrive but unfortunnatly Celery tasks are executed in seprate processes so that global variable from one task isn't accessible in another task. After some research I came to the conclusion that best solution is to use the websockets library and I'm trying to implement this example of a websocket client/server. The idea is to start the ws server in the same task that receive the stream of financial data so it can transmit the data to another 'client' task. To do so I declared a global variable data which contain the stream as it arrives, and it's this variable I would like to transmit to the client in the gretting message. The server … -
Creating applications with django
I made 'Pollsapp' through the pycharm and django, but I can't see it. However, it can be checked on the admin site. When I search with "127.0.0.1:8000/Pollsapp/", it says "No Question". I registered the app(Pollsapp) on settings.py. And page not found (404) appears when I search http://127.0.0.1:8000/. Is this the problem? Only admin site operates normally. What do you think is the problem? I didn't understand this system well, so please let me know if you need any more information. -
Amazon S3 buckets, limit the number of request per day, limit of size
currently developping a "social network"-like website, I plan to use an Amazon S3 bucket to store users'profile pictures. Does anyone know whether there is an easy way to set : the maximum number of requests per day a bucket can accept the maximum size that the bucket can reach the maximum size a given picture must not exceed to be accepted My fear being that a given user would upload such a big picture (or such a big number of pictures, or create such a high number of profiles) that my amazon S3 bill would skyrocket... (I know that some 'a posteriori' alerts can be set, but I'm looking for a solution that would prevent this situation..) Any help greatly appreciated ! -
RuntimeError: populate() isn't reentrant import loop
I have my models.py file import an external function which then writes to a specific model. I think this is some sort of import loop but I'm not sure. This is a partial traceback File "path/Directory/Package/models.py", line 19, in <module> from externalFunction import myFunction File "path/Directory/externalFunction.py", line 9, in <module> django.setup() File "/path/anaconda3/envs/myEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/path/anaconda3/envs/Brew/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant File structure >Directory manage.py externalFunction.py >Package models.py >Package_api wsgi.py models.py from django.db import models import sys sys.path.append("..") from externalFunction import myFunction class Job(models.Model): name = models.CharField( max_length=30, default="name") externalFunction.py import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Package_api.settings') django.setup() from Package.models import Job def myFunction(): some stuff I've tried removing django.setup() from externalFunction.py but then it cannot import Job from the models. -
Data is not being saved as Encrypted data django
till now I tried more then 6 plugins and quite frustrate now. Now using this one cryprtography everything is fine and done accordingly but when I save data in model manager like this def create_user(self, email, password, **extra_fields): user = self.model(email=email, **extra_fields) user.test_field = 'tousif.noor@oc.com' user.save(using=self._db) return user it saving data normally not encrypted My model is like class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) test_field = encrypt(models.CharField(max_length=100)) objects = UserManager() -
How to change a boolean of Active True to false after a time frame
I am trying to set a parameter for a boolean from True to false after a time frame. For my limited knowledge in Python and Django, I am trying to learn the concept and the logic so that I can apply it in different other places in the project. here is the Models.py class Coupon(models.Model): code = models.CharField(max_length=15, unique=True) valid_from = models.DateTimeField(blank=True, null=True) valid_to = models.DateTimeField(blank=True, null=True) active = models.BooleanField(default=True) How do set that when the time frame is after valid_to the Active=status becomes False here is the views.py class AddCouponView(View): def post(self, *args, **kwargs): now = timezone.now() form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) coupon = Coupon.objects.filter(code__iexact=code, valid_from__lte=now, valid_to__gte=now).exclude( order__user=self.request.user, max_value__lte=F('used')).first() if not coupon: messages.error(self.request, 'You can\'t use same coupon again, or coupon does not exist') return redirect('core:checkout') else: try: coupon.used += 1 coupon.save() order.coupon = coupon order.save() messages.success(self.request, "Successfully added coupon") except: messages.info(self.request, "Max level exceeded for coupon") return redirect('core:checkout') except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('core:checkout') -
Djoser password reset implementation
I am using djosers for my authentication on django backend which eventually i'll be connecting to flutter frontend and i am having trouble implementing the password reset functionality... from what i have understood, first i need to hit the /users/reset_password/ with email body which will eventually give me the token of authentication which will be used further on confirm reset but the first thing i dont understand is PASSWORD_RESET_CONFIRM_URL field in the settings, like it needs a front end link with uid and token placeholders but what is this token field and what is this PASSWORD_RESET_CONFIRM_URL but i managed to look over a stack overflow question and filled it but now when i hit /users/reset_password/ i get this error [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions settings: DJOSER = { 'PASSWORD_RESET_CONFIRM_URL':'reset/password/reset/confirm/{uid}/{token}', 'LOGIN_FIELD' : 'email', 'USER_CREATE_PASSWORD_RETYPE' : True, 'SERIALIZERS': { 'user_create': 'auth_app.serializers.UseriCreateSerializer', 'user': 'auth_app.serializers.UserCreateSerializer', } } urls.py: urlpatterns = [ path('',home,name='home'), path('addInForum/',addInForum,name='addInForum'), path('addInDiscussion/',addInDiscussion,name='addInDiscussion'), path('<str:forum_id>/getDiscussion/',getDiscussion,name='getDiscussion'), path('getDate/',getDate,name='getDate'), path('reset/password/reset/confirm/<str:uid>/<str:token>/',PasswordResetView,name='PasswordResetView'), # url(r'^reset/password/reset/confirm/(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$', PasswordResetView.as_view(),), ] views.py @api_view(['GET']) def PasswordResetView(request,uid,token): post_data = {'uid': uid, 'token': token} return Response(post_data) -
Django fails to save recorda to database
Please am currently stuck at a juction trying to send data to the database. I created my HTML form fromsceatch and didn't make use of Django built in crispy_form. Whenever I hit the submit button it saves everything fields as'None'. What I could observed from my method is that, it keeps returning a GET request instead of a POST request. Please how can I solve that. Have been stuck on this thing for over a week, I'll really appreciate if I get a solution here. Thanks. -
Django filtering error: annotate + distinct not implemented
I'm using Django 2.2 and I need to group a query set by month and count the number of rows Input: Id | Value | Date 1 | Example value 1 | 2020-02-10 2 | Example value 2 | 2020-02-17 3 | Example value 3 | 2020-03-21 4 | Example value 4 | 2020-04-15 Expected output Month | Count 2020-02 | 2 2020-03 | 1 2020-04 | 1 I'm using an initial filtering like this. details = Process.objects.filter(started_at__gte=start_date, finished_at__lte=end_date).order_by('-serial_number').distinct('serial_number') #Some code using all details #Filtering After that I need to do the group by and count. summary = (details .annotate(m=Month('started_at')) .values('m') .annotate(total=Count('id')) .order_by('id').distinct('m','id')) But when I execute it I got the following error: NotImplementedError: annotate() + distinct(fields) is not implemented. Month class definition: class Month(F): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = models.IntegerField() I'm trying to do something like this. Django: Query Group By Month -
Syntax to append variable to {% url 'app_name:viewname' %}
How do I append a variable to a url name in a template, for eg.: {% for table in tables %} <a href="{% url 'menu:menu_view' %}"> <button class="button table{{table.pk}}">Table {{table.pk}}</button> </a> {% endfor %} With table.pk as a counter (passed in from view function), I would like to tag it to menu:menu_view so that I could have menu:menu_view1,menu:menu_view2, etc. And then I could name my urlpatterns as following: path('<int:table.pk/', views.menu_view, name='menu_view' + str(table.pk)), -
How to write Ajax logic in view for a reply comment form?
I created a comment thread view wherein it has comment and its relevant replies and reply form. This form works fine, but I only couldn't Ajaxify it. here is the form. <form action="." method='post' class="reply-form"> {% csrf_token %} <div class="input-container"> <label for="comment">Comment</label> <input type="hidden" name="content_type" value="blogs | blog" id="id_content_type"> <input type="hidden" name="object_id" value="1" id="id_object_id"> <input type="hidden" name="parent_id" value={{ comment.id }}> <textarea name="body" id="comment" class="input-textarea" rows="2" ></textarea> </div> <input type="submit" value="Reply" class="button" /> </form> This is what I tried but didn't work, I sent this Ajax form when form is submitted. $(document).on("submit", ".reply-form", function (e) { e.preventDefault(); $.ajax({ type: "POST", url: $(this).attr("action"), data: $(this).serialize(), dataType: "json", success: function (response) { $(".form-container").html(response["form"]); $(".reply-btn").click(function (event) { event.preventDefault(); $(this).parent().next(".comments").fadeToggle(); }); }, error: function (rs, e) { console.log(rs.responseText); }, }); }); and in turn, this request calls the following view def comment_thread(request, pk): obj = get_object_or_404(Comment, pk=pk) initial_data = { 'content_type': obj.content_type, 'object_id': obj.object_id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): content_type = ContentType.objects.get_for_model( obj.content_object.__class__) object_id = form.cleaned_data.get('object_id') body = form.cleaned_data.get('body') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_queryset = Comment.objects.filter(id=parent_id) if parent_queryset.exists() and parent_queryset.count() == 1: parent_obj = parent_queryset.first() comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=object_id, … -
Efficient way to query objects based on their coordinates in Django
I am tying to retrieve several objects and make a separate list for each based on their start location. For example, we have a query of 6 objects, and all of them have different start_loc. I want to make a list that have objects with their start_loc within 30 meters from each other. So, the list would look like [[obj1, obj2, obj3], [obj4, obj5]] My code is as follows: hikes = Hikes.objects.all().order_by('start_loc') eff_hikes = _eff_hikes(hikes) def _eff_hikes(hikes): ref_coords = [] for i in range(len(hikes) - 1): this_hike = hikes[i].start_loc next_hike = hikes[i+1].start_loc dis = D(m=this_hike.distance(next_hike)) if this_hike != next_hike and dis > D(m=30): ref_coords.append() = hikes[:i+1] # some more code return ref_coords This does not help and makes my code complicated. Is there a better solution to this problem? -
Creating object in django models
ck.imgur.com/ZK6tB.png Hi everyone. I've just began django with a tutorial, and created my models, objects in cmd. When i create an obj, it requires the first attribute title to be a num, otherwise an error. But i have Charfield in title, so why that happens? If need, i'll add screens of other apps -
Type Error: Format Requires Mapping in Django
In the python shell I have been trying make the following query: from fixtures.models import Summary Summary.objects.get(team='Liverpool') But I get the following error: TypeError: format requires a mapping But when I try to get the team from the first object it works: Summary.objects.first().team >>>'Liverpool' Any idea on how to solve this problem? Thanks