Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django request's session consistency across different browsers
I have the session engine settings as follows: SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' SESSION_SAVE_EVERY_REQUEST = True CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 60*60, } } I go to 127.0.0.1:8000 with Browser 1 and can successfully log in. Then I go to 127.0.0.1:8000 with Browser 2 and can also successfully log in. Now I go to 127.0.0.1:8000 with Browser 1 and get the following error message: SuspiciousOperation at / The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. How can this error be avoided? The user should be able to log in with as many browsers as he likes. I don't mind if he gets logged out from the non-active browsers, but an error is not acceptable. -
How to add "Return Product" after "Product Delivery" functionality in Django Oscar
I want to add "Return Product" after "Product Delivery" functionality in Django Oscar. in settings.py i added below code. OSCAR_ORDER_STATUS_PIPELINE = { 'Pending': ('Processing', 'Cancelled',), 'Processing': ('Shipped', 'Cancelled',), 'Shipped': ('Delivered', 'Return', 'Returned', 'Cancelled',), 'Returned': ('Return', 'Returned',), 'Delivered': (), 'Cancelled': (), } OSCAR_ORDER_STATUS_CASCADE = { 'Processing': 'In progress', 'Shipped': 'Shipped', 'Delivered': 'Delivered', 'Returned': 'Returned', 'Cancelled': 'Cancelled' } i have written Ajax function to change the status after Order gets "Delivered" to "Return". below is the function. @csrf_exempt def return_order(request): # Return Order after Delivery if request.is_ajax(): data = request.body.decode('utf-8') try: order = Order.objects.get(id=int(data)) EventHandler().handle_order_status_change(order=order, new_status='Return') return HttpResponse(json.dumps({'status': 'True', 'msg': 'OK'})) except Exception as e: print(e) return HttpResponse(json.dumps({'status': 'False', 'msg': 'Error'})) I am geting Error something like this 'Return' is not a valid status for order 100213 (current status: 'Delivered') -
Django Microservices - skip all user created tables for non-user services
I am using Django in a Microservice architecture. I already have a userService for authentication with JWT with an apiGatewayService that checks if token is valid before routing requests to other services. This means that I do not need all the standard tables that are created for a user (user tokens, sessions, email etc) in my other services when I run python manage.py migrate. Is there a way to opt out of creating these unnecessary tables? I have read some people just saying not to run migrations so as not to create these tables, but I obviously want to create other tables (say I have an ordersService, I want an orders table etc). -
send VoIP notifications via PushKit in django
Hot to send VoIP notifications via Pushkit in Django server. Is it possible to send Pushkit notification using APNSNotificationWrapper -
Group objects by different models
I have two models: class Combo(models.Model): price = models.DecimalField class Choice(models.Model): combo = models.ForeignKey(Combo, on_delete=models.CASCADE) items = models.ManyToManyField(Item) And also I have models for order: class Order(models.Model): comment = models.CharField(max_length=300) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) amount = models.PositiveIntegerField Combo consist of all Choices linked to Combo and to have Combo price we need to have one item for each Combo choice. For example Combo#1 has two choices with items: Rag, Brom. Scoop. So if our order has 2 rags, 1 broom and 2 scoop we will get 2 combos and one broom as item. How can I split Order to combos and items to have 2 QuerySets - one for Combos and other for Inems not included to combos? Thanks! -
fetch data from databse based on choices django
i am creating artist booking web app and i have a dropdown list of artists like celeb, dancer, model so when i click any of them it should fetch only specific list in html template. i'm storing the artist based on choices this is my models.py: from django.db import models class artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) artist_name = models.CharField(max_length = 50) artist_type = models.IntegerField(choices = CHOICES) description = models.TextField(max_length = 500) def __str__(self): return self.artist_name view.py: def talent(request): artists = artist.objects.all() context = { 'aka': artists } return render(request, 'main_site/talent.html', context) when i am rendering this it get all the list but i need specific list like when i click on dancer it should get dancer only this is base.html navbar: <ul class="menu-horizontal text-left "> <li><a href={% url 'mainsite-index'%} class="menu-horizontal text-left nav-font">Home</a></li> <li><a href={% url 'mainsite-about'%} class="menu-horizontal text-left nav-font">About</a></li> <li class="dropdown"> <a href="#" class="menu-horizontal text-left dropdown-toggle nav-font" data-toggle="dropdown">Artist</a> <ul class="dropdown-menu nav-font" style="margin-top: 7px"> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Celebrities</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Singer</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Comedian</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Dancer</a></li> <li> <a href={% url 'mainsite-talent' %} style="color:grey;padding-left:5px">Model</a></li> … -
Google django-allauth config
I have been able to successfully configure django-allauth with my Django app. When i attempt to signup via Google, i see a Sign Up form getting shown before login, which is prompting user to enter username, email etc. like the following: Sign Up You are about to use your Google account to login to example.com. As a final step, please complete the following form: Username: E-mail (optional): Sign Up » Is there a config. which i can use to bypass this form? Please suggest how to avoid this. -
how to save username(phone) and password by unidecode in django?
I’m Use a Customuser Model in Django. When Register User by Persian or Arabic Digit Can't Log because Username and Password Save in Persian. in Login Form Can Change Entry to unidecode But in Register Form Can't. if Register by English Digit Can log by every Digit form (English, Persian, etc) But if Register Persian or Arabic Can't Log. How Resolve it? User Unidecode for Digit and text-unidecode for Charfiled in Code Try to unidecoede Phone(username) and Password in Reg Form But Unsuccessful class UserManager(BaseUserManager): def create_user(self, phone, name, family, password=None, is_active=True, is_staff=False, is_admin=False): if not phone: raise ValueError("Users must have an phone") if not password: raise ValueError("Users must have a password") if not name: raise ValueError("Users must have a name") if not family: raise ValueError("Users must have a family") this_phone = unide(phone) this_password = unidecode(password) user_obj = self.model( phone = this_phone, name = name, family = family ) user_obj.set_password(this_password) # change user password user_obj.is_active = is_active user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj -
Django admin custom choice formfield choice
In the django admin I'm trying to create a custom choice if a field in the database is None or with a value but I cannot make it work I can only get the whole queryset but I cannot get the id of the data so I can filter the request. Any suggestions? def formfield_for_choice_field(self, db_field, request, **kwargs): ordered = False qs = self.get_queryset(request) for query in qs: if query: if query.order: ordered = True if db_field.name == "order": if db_field.value: ordered = True if db_field.name == "status": if ordered: kwargs['choices'] = ( ('Ordered', 'Ordered'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Late', 'Late'), ('Never Arrived', 'Never Arrived'), ) else: kwargs['choices'] = ( ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), ('Late', 'Late'), ('Never Arrived', 'Never Arrived'), ) return super(xxxxxx, self).formfield_for_choice_field( db_field, request, **kwargs) -
Deserialize different fields names than attributes names
I would like to deserialize input given like: { "NameFilter": ["John", "Paul"], # name has to be exactly 4 letters length "AgeFilter": [ { "Min": 10, "Max": 12 }, { "Min": 8, "Max": 99 } ] } To something like this: { 'name_filter': ['John', 'Paul'], 'age_filter': ['10-12', '8-99'] } In order to do that I have created 3 serializers: class NameFilterSerializer(serializers.Serializer): name_filter = serializers.CharField(max_length=4, validators=[MinLengthValidator(4)]) def to_representation(self, instance): return instance class AgeFilter(serializers.Serializer): min = serializers.IntegerField() max = serializers.IntegerField() def to_representation(self, instance): return str(instance['Min']) + '-' + str(instance['Max']) class FilterSerializer(serializers.Serializer): name_filter = NameFilterSerializer(many=True) age_filter = AgeFilter(many=True) def to_internal_value(self, data): return { 'name_filter': data['NameFilter'], 'age_filter': data['AgeFilter'] } It returns correct values but in case of invalid input data ("Min" is not a number or "NameFilter" contains "NameExceeding4letters") it does not raise the error. What am I missing? -
Django resend activation link, missing 1 required positional argument: 'user'
I have read similar questions but I cannot understand why this is not working. I am trying to send a reactivation email to user when they click on a link. The activation link is generated properly when the user signs up and the email is sent, but when I try to call the same function again to reactivate link, it is not working saying it is missing one parameter. Here's the function: acounts/views.py def sendactivationmail(request, user): # Creating token and masing uid of user token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)).decode() # Sending email for email verification subject = 'Please Verify Your Email' from_email = settings.DEFAULT_FROM_EMAIL to_email = [user.email] context = { 'url': settings.BASE_URL + reverse('user-activation-link', kwargs={ 'uidb64': uid, 'token': token, }), } contact_message = render_to_string('verify_email.html', context) plain_message = strip_tags(contact_message) send_mail(subject, plain_message, from_email, to_email, html_message=contact_message, fail_silently=True) return redirect(reverse('login')) accounts/urls.py from django.conf.urls import url from .views import * from . import views from urllib import request from django.contrib.auth.models import User urlpatterns = [ url(r'^reactivate/$', views.sendactivationmail(request, User), name='reactivate'), Is this the right way to pass on the request and user parameters to the function? -
How to enable text compression in a django project?
Currently we are trying to increase the performance of our website. Our project is running in django and developed in javascript. Now after running audits in chrome we realised that we haven't enabled text compression. We already searched the web and found diffrent results but can't really find a general solution which is working for us. We tried the following already: COMPRESS_ENABLED = True We expect the content-encoding in our Response Header to show up. Please let me know if you need any other code details. Hope someone can help us. -
How do I store a user's google+ profile information with google+ API in my database?
I have djongo engine based google authentication web application. It signs in the user by using google+ API. My database is able to store the username and email. How do I get it to store the user's first name, profile picture url etc from google+ profile information in my database? -
Django: update_or_create, filter with list of kwargs
Is there any way of using list in kwargs filter of update_or_create? Here are my models: class Partner: ... class MyClassB: partner = models.OnetoOneField(Partner, related_name='some_name') .... I tried using for loop, and it works fine. # partners = list of queryset objects. for partner in partners: MyClassB.objects.update_or_create(partner=partner, defaults= {'name': None}) This operation is being used very frequently and I was thinking of optimizing this update_or_create. is there any way I could update all partners in one go? Something like: MyClassB.objects.update_or_create(partner__in=[partners], defaults={'name': None}) This code is part of an API that would be hit by a thousand partners every 5 seconds. And I want to avoid additional overhead of using for loop here. Is there any optimized way? -
How to create Django Subfolder for multiple country like subdomains
I wanted to make a multiregional website using Django. One way is to use subdomains For eg: in.example.com //India ae.example.com // UAE Note: The content is going to be the same just the language and payment gateway will change as per region/country. Another way is to use subfolders For eg: example.com/in example.com/ae I need to work using the later method of example.com/COUNTRY. How can I do so using Django? -
How do you get a string from Django PostgreSQL ArrayField?
I'm trying to get a string out of an ArrayField in my database but it only prints by characters, not the full string. For example, the ArrayField is named words and in the database it shows as {word1, word2, word3} so in the HTML I put {{ object.words.0 }} and { is rendered on the screen. How can I get it to render word1? I have added django.contrib.postgres to INSTALLED_APPS. This is what it looks like in my model: from django.db import models from django.contrib.postgres.fields import ArrayField class WordArr(models.Model): words = ArrayField(models.CharField(max_length=200, null=True)) -
Is there any package or function save csv file in database table format
Scenario: User upload the CSV file and in the backend save CSV as a file. Now I am trying to save those csv file in database as a table format. When csv save database it will show the data like pandas dataframe. I already see some packages like django-import-export. But it will not that i want. The main thing is that in that packages create the model before uploading the file. But i don't create model before user uploading file. here is my django code. model.py from django.db import models # Create your models here. from django.db import models # Create your models here. class DataUpload(models.Model): fileId = models.AutoField(primary_key=True) data_upload = models.FileField(upload_to='files/') class Meta: db_table = 'DataUpload' forms.py from django import forms from .models import DataUpload class PostForm(forms.ModelForm): class Meta: model = DataUpload fields = ['data_upload'] urls.py from django.urls import path from .views import dataview , FileView, ResultView # from .views import BonolothaDataView urlpatterns = [ path('', dataview.as_view()), path('fileview/', FileView.as_view(), name='fileview'), path('result/', ResultView.viewResult, name='result'), # path('bonolotha/', BonolothaDataView.as_view(), name='bonolotha'), ] views.py class dataview(View): model = DataUpload form_class = PostForm initial = {'key': 'value'} template_name = 'post.html' fileview_url = reverse_lazy('fileview') def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) # pribt html form … -
Django: Remove form fileds based on some values in the database
I want to remove some fields from a form based on some values in the database. I'm not using this form to insert the data into any database, I'm going to make a csv file from this form data. Also this form is not related to any model. forms.py class Registration_form(forms.Form): Applicant_Name = forms.CharField(label='Your name', max_length=100) Applicant_age = forms.IntegerField(label ='Age of Applicant') Applicant_email =forms.EmailField(max_length=50) Applicant_phone = forms.CharField(max_length=10) views.py class Registration_View(FormView): template_name = 'EVENTAPP/Application.html' form_class = Registration_form success_url = '/' def form_valid(self, form): Applicant_Name = form.cleaned_data['Applicant_Name'], Applicant_age=form.cleaned_data['Applicant_age'], Applicant_email=form.cleaned_data['Applicant_email'] Applicant_phone=form.cleaned_data['Applicant_phone'] # do some operations if form data valid return super().form_valid(form) models.py class es_event(models.Model): ev_name = models.CharField(max_length=100,verbose_name="Event Name") ev_date = models.DateField(auto_now=False, verbose_name="Date") ev_description = models.TextField(null=True, verbose_name="Description") registrant_name = models.BooleanField(default=True ) registrant_age = models.BooleanField(default=False) registrant_phone = models.BooleanField(default=False) registrant_email = models.BooleanField(default=False) registrant_institution = models.BooleanField(default=False) name = models.CharField(max_length=100,null=True) reg_open = True slug = models.SlugField(max_length=250) def save(self, *args, **kwargs): self.slug = slugify(self.ev_name) return super(es_event, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('event_detail', kwargs={'id': self.id, 'slug': self.slug }) urls.py url(r'^events/register(?P<id>\d+)(?:/(?P<slug>[\w\d-]+))?/$', views.Registration_View.as_view(), name='event_application') Now what I want to do is find a particular instance of es_event from the database by using the value of "id" in the URL. Then if that instance has the attributes registrant_name,registrant_age, etc is True then the … -
How to send multiple objects through request in django?
I have created a views function in django which returns the data of all cars. Now I want to add the functionality that a user can make multiple lists and then add those cars to any of the list created by them. The lists created by the users are displayed in the form of a drop down menu in front of the car name. How should I send the list information to be displayed according to the user in front of the car name in django rest framework. P.S: I am new to using django rest framework. -
How to create sign up form for customer user model in Django?
I have extended the User Model provided by Django into Owner object. What I intend to do, is create a sign up form which creates a new user in my application and also fill up the custom fields defined in Owner object. My code is as follows - model.py - class Owner(BaseModel): id = models.AutoField(primary_key=True) gym = models.ForeignKey(Gym, on_delete = models.CASCADE) # User model user = models.OneToOneField(User, on_delete = models.CASCADE) address = models.OneToOneField('Address', on_delete=models.CASCADE) contact = models.BigIntegerField(null=False) dob = models.DateTimeField(null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True, default=None) profile_photo = models.ImageField( upload_to='static/images/gym_owner/profile', null=True, blank=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Meta: verbose_name_plural = "Owner" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Owner.objects.create(user=instance) instance.profile.save() SO basically, Owner model extends the User model via One-to-One relationship method. And there is a signal receiver method which creates the Owner object when User object is created. Forms.py - class OwnerForm(ModelForm): class Meta: model = Owner fields = ('gym', 'address', 'contact', 'gender', 'profile_photo') The form basically contains the fields that I want to extend the User model with. And the view.py - @transaction.atomic def owner_signup(request): if request.user.is_authenticated: return redirect('dashboard') if request.method == 'GET': userForm = UserCreationForm() ownerForm = OwnerForm() return render(request, 'gym_owner/signup.html', {'userform': userForm, 'ownerForm': … -
How to convert Django template to pdf and download it locally
I want to convert and download django template to pdf file. I run my function using console. The function is as follows: def generate_windscreen_pdf(lead_ids): for lead_id in lead_ids: language = settings.DEFAULT_CULTURE_MAJOR translation.activate(language) car = map_lead(lead_id, 0) translate_dict_recursive(car, language) s_template = 'manager/seller/templates/pdf/windscreen.html' context = {'car': car, 'note': note} html_template = render_to_string(s_template, context) translation.deactivate() pdf_file = HTML(string=html_template).write_pdf(stylesheets=[CSS(string='@page { size: A4 landscape; margin: 0.2cm }')]) response = HttpResponse(pdf_file, content_type='application/pdf', mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename="windscreen_{0}.pdf"'.format(lead_id) return response And the template is as follows: <html> <head> <link rel="stylesheet" href="{{ car.header_css }}"> </head> <body> <div class="header"> <img src='{{ car.make }}' /> </div> I'm using weasyprint library. When I run it from the console I get the output as follows: Fontconfig warning: "/usr/local/etc/fonts/fonts.conf", line 146: blank doesn't take any effect anymore. please remove it from your fonts.conf Fontconfig warning: "/usr/local/etc/fonts/fonts.conf", line 146: blank doesn't take any effect anymore. please remove it from your fonts.conf <django.http.HttpResponse object at 0x10ad19f10> But I want that the file is downloaded to the folder on my local pc. Any idea how to do that? -
Picture Upload Form didnt show a image upload column
I have a CreateView for Post where I have a title and content columns, I tried to add image upload column for that post and it wont works, but it wont shows an error, so I don't know what I'm doing wrong... I migrated it and it wont show an column for upload picture. Here are my codes. views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(LoginRequiredMixin, DetailView): model = Post class PostCreateView(LoginRequiredMixin, CreateView): form_class = PostUpdateForm model = Post fields = ['title', 'content', 'image'] forms.py class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['image'] models.py class Post(models.Model): title = models.CharField(max_length=100, verbose_name='タイトル') content = models.TextField(verbose_name='内容') date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='uploaded_pic') def __str__(self): return self.title def get_absolute_url(self): return reverse('Post-detail', kwargs={'pk': self.pk}) post_form.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form enctype="multipart/form-data method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">ブログ投稿</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">投稿</button> </div> </form> </div> {% … -
How to perform content negotiation in django middleware?
Let say i have a Custom Django Middleware which check request header has jwt token if not return rest_framework Response., middleware.py @staticmethod def process_view(request, view_func, view_args, view_kwargs): try: jwt_token = request.headers["token"] except KeyError: response = Response(status=status.HTTP_403_FORBIDDEN) return response but i am getting error like .accepted_renderer not set on Response how to perform content-negotiation here? -
How to additional field to Django Oscar Order model?
I want add additional field to Order model. i have already forked order app. below is the code added in Order model in forked_app Order app. from django.utils import timezone from oscar.apps.order.abstract_models import AbstractOrder from oscar.apps.order.models import * # noqa isort:skip from django.db import models class Order(AbstractOrder): status_update_time = models.CharField(max_length=30) def save(self, *args, **kwargs): self.status_update_time = timezone.now() super(Order, self).save(*args, **kwargs) Below is the error i get while migrations. class Order(AbstractOrder): NameError: name 'AbstractOrder' is not defined Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f06737e6d08> RuntimeError: Conflicting 'order' models in application 'order': <class 'oscar.apps.order.models.Order'> and <class 'forked_apps.order.models.Order'>. -
Firebase phone authenticatin with django rest framework
I am developing APIs for an app where it is required to do firebase phone authentication from server side. I am using Djanngo Rest Framework for APIs I did some research for this and only found for email and password authentication. Found none for phone authentication. Is there any way in which I can do phone authentication from server side.