Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model.objects.all() returning empty QuerySet in celery task
project/project/settings.py ... CELERY_BEAT_SCHEDULE = { 'find-subdomains': { 'task': 'subdiscovery.tasks.find_subdomains', 'schedule': 10.0 } } project/subdiscovery/tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from subdiscovery.models import Domain @shared_task def test(): print(Domain.objects.all()) return 99 The celery worker shows an empty QuerySet: celery_worker_1 | [2019-08-12 07:07:44,229: WARNING/ForkPoolWorker-2] <QuerySet []> celery_worker_1 | [2019-08-12 07:07:44,229: INFO/ForkPoolWorker-2] Task subdiscovery.tasks.find_subdomains[60c59024-cd19-4ce9-ae69-782a3a81351b] succeeded in 0.004897953000181587s: 99 However, importing the same model works in a python shell: ./manage.py shell >>> from subdiscovery.models import Domain >>> Domain.objects.all() <QuerySet [<Domain: example1.com>, <Domain: example2.com>, <Domain: example3.com>]> -
How to handle login + FB login at the same time with django-allauth module?
Well.. I started to create simple app. Following official doc of Django, I created auth logic in separate app with name users, like this: users/urls.py: from django.urls import path, re_path, include from . import views urlpatterns = [ path('', include('django.contrib.auth.urls')), path('profile/', views.redirect_to_user_profile, name='redirect-user-profile'), re_path('profile/(?P<pk>\d+)/', views.UserProfileView.as_view(), name='user-profile'), path('register/', views.UserRegisterView.as_view(), name='user-register'), users/views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.views import generic from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Create your views here. def redirect_to_user_profile(request): url = f'/users/profile/{request.user.id}' return HttpResponseRedirect(redirect_to=url) class UserProfileView(generic.DetailView): model = User template_name = 'user_profile.html' class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'register.html' success_url = '/users/login' Everything was fine, so I decided to extent basic Django user, to add profile image for example (and more fields later) like this: users/models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class ProfileUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_image = models.URLField() @receiver(post_save, sender=User) # Still don't know how, but next rows create ProfileUser when User is created def create_user_profile(sender, instance, created, **kwargs): if created: ProfileUser.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profileuser.save() def __str__(self): return f"{self.user}" Still working fine. Then I decided to add FB login, … -
How to "get" User that don't sign in yet?
I'm working on email activation, I do not want the user to login before they activate their email, so I set the active status as "false". The question is how do I get that user and make it True when they activation email. def activation_view(request, activation_key): if (SHA1_RE.search(activation_key)): print("acti is real") try: instance = EmailConfirmed.objects.get(activation_key=activation_key) except EmailConfirmed.DoesNotExist: instance = None raise Http404 if instance is not None and not instance.confirmed: page_message = ("ยืนยัน User เรียบร้อย") instance.comfirmed = True instance.activation_key = "Confirmed" instance.save() user.is_active = True? elif instance is not None and instance.comfirmed: page_message = ("User ถูกยืนยันไปแล้ว") else: page_message = "" context = {"page_message":page_message} return render(request, 'accounts/activation_complete.html',context) else: raise Http404 -
In Django REST Framework, how to get the "query parameter" sent by the previous page's hidden input?
I have an html page for listing the model "Descriptions", and at the end of it there's a button to go to the Description creation page, while sending the "character_id" that is intended to be a default initial value for the new Description (and I have set up the context so that the character_id would be there: <!--The code for listing the Descriptions--> <form action="{% url 'polls:description_detail_create_from_character' %}"> <input type="hidden" value="{{ serializer.context.character_id }}" name="character_id"> <input type="submit" value="New Description"/> </form> On the browser, if I click "New Description", it will bring me to: http://localhost:8000/polls/description_detail_create_from_character/?character_id=3 However, then I don't know how can I get this "character_id" from description_detail_create_from_character (the next page)'s template. Thought it could be request.query_params.get('character_id', None), but doesn't work. By debugging, I can find the dict query_params, however, there's nothing in it. Just don't know how can I get this character_id=3. It's nowhere to be found in the {% debug %} either. Is something more to be done in the Serializer? Or View? Is this ?character_id=3 here actually a query parameter here? If it is not then what it is? Code: Serializers.py: # The serializer for the creation page class DescriptionCreateFromCharacterSerializer(DescriptionSerializer): author = serializers.HiddenField(default=serializers.CreateOnlyDefault(DefaultFieldCurrentUser())) # This works btw, unlike the … -
how to set cache in django i am not sure its saving in cache or not?
i want to reload a page fast the data coming from database takes time so i want to save in cache so for first time it will take time and then it will be store in redis server so this will help me with fast loading in data... what will be the easy way to do it and make database fast i already done indexing using PostgreSQL def render_upcoming_products(request, *args, **kwargs): if 'products' in cache: products = cache.get('products') return HttpResponse(render(request, "byond3/upcoming-trips/cards.html", context=products)) else: logger.info("Not there in cache") product_ids = [] destination = request.POST.getlist('destination[]','') duration = request.POST.getlist('duration[]','') month = request.POST.getlist('month[]','') style = request.POST.getlist('style[]','') datetime.datetime.strptime('Dec', '%b').month if destination: kwargs['destination__name__in'] = destination if style: kwargs['category__category_name__in'] = style if month: decoded_month = [datetime.datetime.strptime(m, '%b').month for m in month] kwargs['travel_planners__trip_start_date__month__in']=decoded_month else : decoded_month = [] kwargs['travel_planners__trip_start_date__gt'] = datetime.date.today().strftime('%Y-%m-%d') kwargs['is_upcomming_trip'] = True kwargs['published'] = True dictionary=dict() products = [] actions = [] kwargs1 = {} if duration: for dur_ in duration: if '>' in dur_: products.append(Product.objects.filter(Q(travel_planners__duration__gt=int(dur_.replace(' days','').replace('>',''))), **kwargs).order_by('travel_planners__trip_start_date')) elif '-' in dur_: products.append(Product.objects.filter(Q(travel_planners__duration__lte=int(dur_.replace(' days','').replace('-',',').split(',')[1]))&Q(travel_planners__duration__gte=int(dur_.replace(' days','').replace('-',',').split(',')[0])),**kwargs).order_by('travel_planners__trip_start_date')) else: products.append(Product.objects.filter(**kwargs).order_by('travel_planners__trip_start_date')) products = [j for i in products for j in i] products = list(set(products)) products.sort(key=lambda x: x.travel_planners.first().trip_start_date, reverse=False) no_of_products = len(products) no_of_dep = 0 for prod in products: no_of_dep … -
how to return a failure message when the email isn't sent with django-rest-auth?
I've set up django-rest-auth to send a password reset email. Unfortunately, the API returns a success message "Password reset e-mail has been sent" even there is no user with that email address.How can i solve this ?I want to display some messages like No email found if the entered email isn't valid. Any help would be great. -
To display the LinkedIn profile picture in Django
I am able to retrieve the profile picture from LinkedIn with social auth app django but how can I display the picture in Django? The retrieved data shows like ..."profile_picture": {"displayImage": "urn:li:digitalmediaAsset:xxxxxx"}... Is there a way to process this without using an API? -
Is it possible post the point dataset through form on django?
I want to post the point dataset into my postgres database using form. Is this possible? If yes, How can be possible? my views.py file from django.shortcuts import render from issue.models import Issue # Create your views here. def index(request): return render(request, 'pages/index.html') def about(request): return render(request, 'pages/about.html') def webmap(request): if request.method == 'POST': first_name = request.POST['firstname'] last_name = request.POST['lastname'] issue_header = request.POST['issue_header'] issue_body = request.POST['issue_body'] issue = Issue(first_name=first_name, last_name=last_name, issue_header=issue_header, issue_body=issue_body) issue.save() return render(request, 'pages/webmap.html') return render(request, 'pages/webmap.html') In this form I want to submit point data. I am using leaflet. And my marker location is var useMarker = true $('.fa-cubes').click(function () { if (useMarker) { map.on('click', function (e) { var popup = `<!-- Default form register --> <form class="text-center border border-light p-5" action="{% url 'webmap' %}" method="POST"> {% csrf_token %} <p class="h4 mb-4">Issue Form</p> <div class="form-row mb-4"> <div class="col"> <!-- First name --> <input type="text" name="firstname" id="defaultRegisterFormFirstName" class="form-control" placeholder="Your First Name"> </div> <div class="col"> <!-- Last name --> <input type="text" name="lastname" id="defaultRegisterFormLastName" class="form-control" placeholder="Your Last Name"> </div> </div> <!-- Issue header --> <input type="text" name="issue_header" id="defaultRegisterPhonePassword" class="form-control mb-2" placeholder="Input your issue header" aria-describedby="defaultRegisterFormPhoneHelpBlock"> <br> <!-- Password --> <input type="text" name="issue_body" id="defaultRegisterFormPassword" class="form-control" placeholder="Your issue in detail" aria-describedby="defaultRegisterFormPasswordHelpBlock"> <!-- … -
How to display name instead of email address while sending email in django rest framework?
This is django rest framework and here i am trying to send email and it is working fine also but the one problem is i want to display some name instead of email address in the users inbox for that i tried adding from_email argument in the urls but it didn't worked.It says TypeError: TemplateView() received an invalid keyword 'from_email'. How can i solve this settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = "myemail" EMAIL_HOST_PASSWORD = 'mypass' EMAIL_PORT = '587' urls.py path( 'password-reset/confirm/<uidb64>/<token>/', TemplateView.as_view(template_name="registration/password_reset_confirm.html", from_email='MyName<myemail>'), name='password_reset_confirm'), -
Can i deploy both Flask and Django application in common aws Elastic Beanstalk server?
I have two applications built with Flask and Django framework. I would like to host both the applcation in aws Elastic Beanstalk. Is it possible to host both application using the common server? Thanks for the Answers. -
How can I escape colons in Django's field lookups?
I've brought some JSON metadata into a JSONfield() and some of the key names include a colon. Am I able to escape the field lookups so I can do something like the example below? filtered_qs = queryset.filter(data__properties__object:key="some_value") where object:key is the name of my JSON key Currently i'm getting the keyword cannot be an expression syntax error. I'm using Postgres 11.2 and Django 2.2.2. -
Graphene-Django Relay Cursor Based Pagination Does Not Work for Dynamic Data
I am fetching dynamic data using Graphene-Django Relay specification. import graphene from graphene_django.types import DjangoObjectType from graphene_django.fields import DjangoConnectionField from . import models class PostType(DjangoObjectType): class Meta: model = models.Post interfaces = (graphene.Node, ) class Query(graphene.ObjectType): post = graphene.Field(PostType) posts = DjangoConnectionField(PostType) def resolve_posts(self, info, **kwargs): return models.Post.objects.order_by('-created_date', '-id') When I add a new post after fetching cursors and data, cursors change. In other words, the cursor that was pointing to the exact offset of data does not point that data any longer. It points a new, different data. Thereby, I cannot implement a cursor-based pagination by using: query fetchPosts ($cursor) { posts(first: 20, after: $cursor)... } Because cursor changes as data changes, it is no different than traditional offset-based-pagination. Is there something I am missing? What I want for the cursor is not to change. Like this article: https://www.sitepoint.com/paginating-real-time-data-cursor-based-pagination/ How should I make the cursor point the same data that changes dynamically? -
List all the permissions and Select/ Deselect/ Update for a specific user
I am working on a custom Admin app in Django project. I repeat, I DO NOT want to use the Django's inbuilt Admin interface/app provided. I am stuck at a point where I want to change the Permissions given to a specific User. I used the generic UpdateView for updation of some specific User's details like Name, Email, User Name etc. but when it came to updating the User Permissions, there was neither a button,link nor a checkbox. How can I ADD/Remove/Update the permissions of a User? Any help would be highly appreciated. class UserUpdate(UserPassesTestMixin, UpdateView): models = User fields = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'user_permissions') def get_object(self, queryset=None): obj = User.objects.get(pk=self.kwargs['pk']) self.success_url = reverse_lazy('admin:user_detail', kwargs={'pk': obj.pk}) return obj def test_func(self): return self.request.user.is_superuser This is my view for updating the User Data by selecting a User. -
How many times does the Django ORM hit the database when calling a foreign key's primary key and using the in list filter?
Lets say I have the following models: class Foo(models.Model): ... class Bar(models.Model): name = models.CharField(max_length=255) foo = models.ForeignKey(Foo) Now, I am doing the following queries: foo_pks = set([]) for bar in Bar.objects.filter(name='some_name'): foo_pks.add(bar.foo.pk) for foo in Foo.objects.filter(pk__in=foo_pks): # Do something So basically, I am adding the primary keys to the set, and then using that set to make another query. How many times am I hitting the database? Moreover, is this horribly inefficient, and if so, is there a better way to do this? -
What to test in a simple DRF API?
So, I'm not a test expert and sometimes, when using packages like DRF, I think what should I test on the code... If I write custom functions for some endpoints, I understand I should test this because I've written this code and there are no tests for this... But the DRF codebase is pretty tested. But if I'm writing a simple API that only extends ModelSerializer and ModelViewSet what should I be testing? The keys in the JSON serialized? The relations? What should I be testing? -
Django - access individual fields in a class-based view generated form
I'm using a custom template I created for a class-based view. Previously I used a "pre-defined" template, one created by form.as_p, but for the custom template I need to access certain fields individually, specifically I have a CharField constrained by choices and I want to populate the options in a <select> field, yet using something like form.myInput doesn't work: Model: class MyObject(models.Model): ... states = ( ('A', 'Activated'), ('D', 'Deactivated') ) state = models.CharField(max_length=1, choices=states, blank=False, default='A') View: class CreateMyObject(CreateView): model = MyObject fields = '__all__' Custom template: ... <select id="state" class="form-control"> {% for s in form.state %} <option value="{{s.0}}">{{s.1}}</option> {% endfor %} </select> ... (this doesn't work!!!) I've seen some solutions where people define a Form but I don't have one. My form is 100% the Model itself. Do I still need to define one? It seems to me I should be able to access easily the fields in form, given that, for instance, form.as_p access all of them and easily creates a basic template... Thanks. -
Django snapshot upload and face recognize with opencv
I'm trying take snapshot with getUserMedia() and recognize face using opencv-python. I only get encoded image from user media and can't open it with opencv. I'm using django 2.2 as backend server -
Pre_delete signal does not work in Django
I am working with signals in Django, specifically with the pre_delete signal, code: signals.py file: def delete_unnecessary_image(sender, instance, using): print('holaaaa') instance.image.delete(save = False) apps.py file (here I register the receivers in the ready() method): def ready(self): from .signals import delete_unnecessary_image from .models import Course pre_delete.connect(delete_unnecessary_image, sender = Course) The problem is that it doesn't work, it doesn't eliminate the image of the Course model, and I don't know why. Any solution? -
Crispy forms throws VariableDoesNotExist error failed lookup for key [html5_required] on forms
I use allauth to sign in with emails and did a very basic custom login form and a template override for allauth and display the login form. Hitting the URL throws me straight into the exception: Failed lookup for key [html5_required] in [{'True': True, 'False': False, 'None': None}, {'True': True, 'False': False, 'None': None, 'form': , 'form_show_errors': True, 'form_show_labels': True, 'label_class': '', 'field_class': ''}, {'forloop': {'parentloop': {}, 'counter0': 1, 'counter': 2, 'revcounter': 2, 'revcounter0': 1, 'first': False, 'last': False}, 'field': }, {}] where I then have to continue the debugger twice to end up on the form. I tried looking for this specific [html5_required] tag/key but haven't found anybody with the same missing key. I removed the custom login form in settings.py to see if there is an issue but that didn't help. I even tested it with a simple ```ModelForm`` just displaying two fields and got the same issue. settings.py: INSTALLED_APPS = [ ... 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ... ] CRISPY_TEMPLATE_PACK = 'bootstrap4' ACCOUNT_FORMS = { "login": "users.forms.CustomLoginForm" } forms.py from django.utils.translation import ugettext as _ from django.urls import reverse_lazy from allauth.account.forms import LoginForm, SignupForm from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML from django.forms import ModelForm class … -
How to customize RetrieveAPIView to take a subview like `blogs/:blog_id/minimal` in Django REST Framework?
I am on Django 1.11, and I am trying to generate a minimal view for a view that is extending RetrieveApiView. The router looks like this: url(r'^(/blogs/(?P<pk>.*)', BlogView.as_view() The BlogView is implemented as such: class BlogView(RetrieveAPIView): search_fields = () queryset = Blog.objects.all() serializer_class = BlogSerializer @detail_route(methods=["get"]) def minimal(self, request, pk=None, **kwargs): return Response( data={ "message": 1 } ) So basically I want to get /blogs/:blog_id to display the current default full view from BlogSerializer, and /blogs/:blog_id/minimal to trigger the minimal function here somehow and display another view. Currently, this solution doesn't really work as I got 404 when visiting /blogs/:blog_id/minimal. Is it possible without having to manually declare another url in route? The reason I choose to not use a query parameter here because I would prefer to have different permission for those 2 view. a minimal view can be viewed by less restricted role -
Validate end_date is bigger than start_date in Django Admin
I have a start_date and end_date fields in save_related action of my Django Admin, I want to assign an error to end_date when it is bigger than start_date, I have been looking docs, but don't find an example about that. -
Django: Survey models and how to display them on template
I'm building a Survey creator that can multiple questions and they can be of four different types: text question, date question, date range question and multiple choice. Below are the models that I've used but I'm having a super hard time understading how to display the correct widget for the correspoding type of question. models.py class Survey(models.Model): title = models.CharField(max_length=255, unique=True) class Question(models.Model): TYPE_QUESTION = ( ("Text", "Text"), ("Date", "Date"), ("Date Range", "Date Range"), ("Multiple Choice", "Multiple Choice"), ) survey = models.ForeignKey(Survey, null=True) title = models.CharField(max_length=255) type_question = models.CharField(max_length=255, choices=TYPE_QUESTION, default=TEXT) class Answer(models.Model): question = models.ForeignKey(Question, null=True) user = models.ForeignKey(User, null=True) answer = models.CharField(max_length=255) I want to achieve something like this but without having to define the form manually: preview.html {% for question in questions|dictsort:"date_added" %} <div class="question-container"> <h4>{{question.title}}</h4> <div class="question-body"> {% if question.type_question == 'Text' %} <input type="text"> {% elif question.type_question == 'Date' %} <input type="date"> {% elif question.type_question == 'Date Range' %} <input type="date"> <input type="date"> {% elif question.type_question == 'Multiple Choice' %} <input type="radio" name="gender" value="male" checked> Yes<br> <input type="radio" name="gender" value="female"> No {% endif %} </div> </div> {% endfor %} Should I redefine my Answer model and define one model for each type of questions? or … -
How to update profile picture for existing model instance?
I'm trying to update a user's profile photo after they've already created their account. I'm using an abstract user model connected to a model called Person. For additional context, I have my application connected to AWS to deploy to Heroku. I have a form, model, url and view set up but I'm sure I'm missing some piece to the puzzle. <form action="{% url 'update-photo' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <table class="table-form"> {{ form|crispy }} </table> <input type="submit" class="btn btn-lg custom-bg"> <br><br> </form> class User(AbstractUser): is_active = models.BooleanField(default=False) class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) upload = models.FileField(default='core/static/images/default_avatar.png') class UpdatePhotoForm(forms.ModelForm): class Meta: model = Person fields = ('upload',) @login_required def update_photo(request): person = Person.objects.get(user=request.user) from core.forms import UpdatePhotoForm if request.method == "POST": form = UpdatePhotoForm(data=request.POST, instance=request.user.person) if form.is_valid(): person = form.save(commit=False) person.save() return redirect('profile') else: form = UpdatePhotoForm() return render(request, 'core/edit_profile.html', {'form': form}) ``` urls.py path('update_photo/', core_views.update_photo, name='update-photo'), The form submits without any error but does not actually update the photo. I can change the photo in the admin site but not via the form. Any help would be greatly appreciated! -
Adding different images based on if post is liked
I'm creating a social media website, where users can like each others post. I have successfully done most of this. I have allowed a user to like and dislike posts, and displayed a list of the users who have liked the post in my template. One issue I have is changing an image based on whether the user has liked the post or not. My current implementation is incorrect, and I am unsure how to solve it. Currently, I have a variable on the Post model(is_liked), and an image changes depending if this is true or not. My problem with this is if one user likes a post, it shows up as liked for every user. I want it so everyone can't see the graphic that is displayed when a post is liked, and only if they like it themselves. models.py: class Post(models.Model): file = models.FileField(upload_to='files/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes') is_liked = models.BooleanField(default=False) views.py: def likepost(request, post_id): if request.method == 'POST': tuser = request.user post = get_object_or_404(Post, pk=post_id) if post.likes.filter(id=tuser.id).exists(): post.likes.remove(tuser) post.is_liked = False post.save() else: post.likes.add(tuser) post.is_liked = True post.save() return redirect('home') home.html(template) {% if post.is_liked == True %} … -
Django multidatabases : data for model field from another db
Is there a way to make a field model get its data from another database? I want to query a magento db and select the customer_id to use in my model field. I Know we can set different databases in the setting file and select the database with using()