Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Allauth Form Errors not showing up
I have a custom django allauth login and signup form but form errors are not. I need custom errors to show up when password is wrong. Here are the Custom Forms class CustomSignUpForm(SignupForm): def __init__(self, *args, **kwargs): super(CustomSignUpForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control rounded input-lg text-center no-border' and here is the actual form itself. <form id="signup-form" method="POST" action="{% url 'account_signup' %}"> {% csrf_token %} {% if form.non_field_errors %} <div class="alert alert-warning"> <ul class="alert-message"> {% for error in form.non_field_errors %} <li>{{ error }}</li> {% endfor %} </ul> </div> {% endif %} <div class="form-group {% if form.email.errors %}has-error{% endif %}"> {{ form.email }} </div> <div class="form-group {% if form.username.errors %}has-error{% endif %}"> {{ form.username }} </div> <div class="form-group {% if form.password1.errors %}has-error{% endif %}"> {{ form.password1 }} </div> <div class="form-group {% if form.password.errors %}has-error{% endif %}"> {{ form.password2 }} </div> <button type="submit" class="btn btn-lg btn-warning lt b-white b-2x btn-block btn-rounded"><i class="icon-arrow-right pull-right"></i><span class="m-r-n-lg">Sign Up</span></button> </form> -
Daphne: command usage error
I'm on a windows computer using Daphne with django 2.0 for asgi. When I run 'daphne mywebsite.asgi:application' I get the following error: daphne : The term 'daphne' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + daphne mywebsite.asgi:application + ~~~~~~ + CategoryInfo : ObjectNotFound: (daphne:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I look in my virtual env and I see that daphne is installed (pip install daphne validates that nothing needs to be installed). Does anyone know what's going on? Micah -
Django Views. How can I change this code from functions based to class based
I'm new to django and was doing most of the staff using function based views. Right now I need to change part of my code to class based and I've stacked for 2 days because can't find any information about implementation of categories using classes So my current code in views.py: from django.shortcuts import render, get_object_or_404 from .models import Category, Product def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) context = { 'category': category, 'categories': categories, 'products': products } return render(request, 'shop/product/list.html', context) Here is my part of models related to categories: class Category(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(blank=True, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('title',) verbose_name = 'категория' verbose_name_plural = 'категории' def __str__(self): return self.title class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField(null=True) price = models.DecimalField(max_digits=20, decimal_places=2, default=49.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) How can I change my views to class based? -
Django Try, except and ObjectDoesNotExist
I am trying to achieve one of the three print messages in order to proceed with my code. Now I am always receiving RelatedObjectDoesNotExist User has no ambassador_profile. What I actually expect is print("No amb profile"). Anyone understands what I am doing wrong here? views.py user = request.user try: ambassador = user.ambassador_profile selected_event = get_object_or_404(Event, slug=event, organizer__slug=organizer) connected_events = ambassador.events.all() if selected_event in connected_events: print("You have an ambassador profile and you are connected.") else: print("You are not connected.") except user.ambassador_profile.ObjectDoesNotExist: print("No amb profile") models.py class AmbassadorProfile(models.Model): slug = models.CharField( max_length=10, unique=True, ) user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='ambassador_profile', ) -
Django: ManyToOne relation with different models?
I.e. I have File which can be attached to Email in many to one manner. So I use ForeignKey(Email) field in the File. But what to do if I'd like to reuse File to be attachable to let's say Publication? It's possible to use ManyToManyField in Email and Publication, but I'd like to keep -ToOne relationship, means only one "owner" of each File should exist. So File should act as having ForeignKey(Email) or ForeignKey(Publication) depending on context. -
How to store data in a database on a Bootstrap grid?
Kind all day! Prompt who nibud faced such task: The user in the admin panel (not django, custom) should create a dashboard (something like the work area) inside which you need to store data on each grid in each cell, so you must first create a bootstrap grid (store the data of the rows and columns) and in the future each cell to support data such as graphs, widgets, and so on. I can not understand how to organize the storage of this data in the database, how should the structured data be structured? Maybe there's a package like that at all? -
Django: Catching Integrity Error vs qs.exists() which one is more efficient?
Two ways to check whether same data exists or not: 1 try: MyModel.objects.create( field1=field1_value, field2=field1_value, ) except IntegrityError: # doing something 2 qs = MyModel.objects.filter(field1=field1_value, field2=field2_value) if qs.exists(): # doing something I wonder which one is more desirable way to check integrity. -
Using a form on DetailView, to submit data to a FormView - including data from context of the DetailView
A View(ViewA) is generating a template with context(contextA). ViewA is inheriting from DetailView or ListView. In ViewA I have a form(contact form), which on submit sends data to another View(ViewB) wich inhertis from FormView. In the form I want to have visible fields but also multiple HiddenInput fields that send contextA data to ViewB, basically info abou the page were the user accessed the contact form. How do I integrate the form in ViewA considering is a DetailView and not a Create/Update View. How do I set the HiddenInput(s) in template to send data to ViewB ? -
performance of skip_locked postgres and django
I want to use select_for_update command of django for concurrent access to my postgres database. My query is as follows : Entity.objects.select_for_update(skip_locked=True).all()[:10] My question is that if two process call this query and my table contains 20 rows, does each of them get 10 rows or the first one get 10 rows and the other no rows? In other words is query performed first and then locked rows are skipped or first locked rows are skipped and then query is performed? -
Removing ManyToMany relationship with PrimaryKeyRelatedField in DRF
I have two models like this: Tags(models.Model): key = models.CharField(unique=True, max_length=50) value = models.TextField() Note(models.Model): key = models.CharField(unique=True, max_length=50) tags = models.ManyToManyField(Tag) Where Tags are used to categorise Notes just like StackOverflow questions here. When clients create/update Notes I want them to be able to send a list of Tag ids in order to associated them. This works well. When they receive the Note, I want the Tags in full, not just a list of IDs. So I subclassed PrimaryKeyRelatedField and overrode to_representation: class RelatedTagsField(PrimaryKeyRelatedField): def to_representation(self, value): return { 'id': value.id, 'key': value.key, 'value': value.value } class NoteSerializer(ModelSerializer): tags = RelatedTagsField(queryset=Tag.objects.all(), many=True, required=False, allow_empty=True) class Meta: model = Note fields = '__all__' This works well when creating Notes and when adding Tags by sending a PATCH containing the Tag IDs in a list, but it doesn't work when sending an empty list to delete the Tags of a Note. DRF just doesn't do anything at all (the QueryDict is empty, so is validated_data). Here is an unit test to illustrate the problem: class TaggedNoteTestCase(APITestCase): # setUpTestData omitted def test_update(self): # create a tag response = self.client.post( f'/api/tags/', { 'key': 'mytag', 'value': 'bla' } ) self.assertEqual(response.status_code, 201) tag_id = response.data['id'] … -
How to update different rows concurrently in Mysql
I have a large table in which I have to update several rows. I tried to use multiple threads to update different rows concurrently, but it seems MySql locks all the rows in the table instead of locking only those rows which are matched by 'where' clause. Hence the update is not concurrent and sometimes lead to lock timeout error. Is there any way to update different rows concurrently? I am using Django in backend to perform update operation. I can switch to Postgres, but will it help or will there still be locking problem? -
views.py for extended user model by onetoone to add profilepicture
I am extending User model to add profile information using onetoone relation. The user should be able to change the basic user profile info. What should be the views to add such functionality? Here is my model Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=100, default='No description field') city = models.CharField(max_length=100, default='Location not added') phone = models.CharField(max_length=10, default='',blank= True) image = models.ImageField(upload_to='products/profile/%Y%/%m/%d', blank=True) def __str__(self): return self.user.username Here is my form forms.py class UserForm(forms.ModelForm): class Meta(): model = UserProfile fields = ['description', 'city', 'phone', 'image'] What should I include in my views? views.py @login_required() def edit_profile(request): pass I want to update the model the extended UserProfile instance in a way that the previous info gets overwritten and the new information is updated. -
does splitting querset requires cleaned data?
I have a queryset named fp_items and look like 201;202;205 etc... Here how it looks like: I am trying to split these items into list because I would do another queryset to recall these items one by one. Should I use cleaned data ? Why I can't split queryset output ? I am getting this error: Exception Type: AttributeError Exception Value:'QuerySet' object has no attribute 'split' fp_items = SWTypes.objects.filter(pk__in=id,swtype__in=swtype).values('fp_items') fp = fp_items.split(';') -
Programming Error when trying to delete User in Django Admin Panel
I got a web page online and everything works fine. Except when I try do delete a user I get the following error: {ProgrammingError at /admin/auth/user/ operator does not exist: text = integer LINE 1: ...OIN "auth_user" ON ("avtimessolver"."employee_id" = "auth_us... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.} I am using Django with nginx, gunicorn and postgresql. Is there anything wrong with my model? The table avtimessolver is generated by an algorithm where i save the id as names so that Django displays names rather than ids in some queries. Is there any way to fix this without changeing the table, so that the delete function also accepts user names as input? Any help is appreciated. -
What are the properties of ImageField in django?
I have created a userUpdate view with a partial modelForm to update user data, which consists of an imageField. Form in my template looks like: <div class='field'>{{ form.photo.label_tag }} {{ form.photo}}</div> Here photo is the imageField. The rendered html view is: But, I don't want the clear checkbox. How to get the url of the current image if one exists for the model instance? What are all the properties of the photo? So, that I can individually use them as required. -
Call R as rpy2 in Django App
I have done statistical analysis on R and have called my R code into python from rpy2 this has done successfully. Now i want to know how to call this on Django App? and later i want to deploy that Django App in Heroku. -
Django 2.0 editing translations from the administration panel
My client wants to edit the translations of the application texts was possible from the administration panel by editing the form fields. He also wants to add more languages with just one click from the admin panel. Does anyone have a better idea than using https://github.com/filebrowser/filebrowser, editing the .po files by this file manager and add to the admin panel a button that creates a new language? There is only one obstacle, after each edit of the translation I have to use the django-admin compilemessages command? -
Django flat pages with .html extension
I am trying to set up django flat pages that would be accessible via a url like /pages/page1.html instead of /pages/page1. Followed the flatpages docs, and instead of the flatpages middleware used this code in the root urls.py (in the same folder with settings.py): re_path('pages/.*\.html$', include('django.contrib.flatpages.urls')), But this results in a 404 error. I tried specifying the extension as a non-capturing group: re_path('pages/.*(?:\.html)$', include('django.contrib.flatpages.urls')), but I'm still getting a 404. What would be the correct way to have the .html suffix for flatpages? -
How to generate credentials of twitter/facebook/instagram just with python script
If I have login and password for above mentioned websites. How to get credentials for those website so that i can use them to update status / delete etc. I am aware of twitters tweepy and facebooks graph api but i need to know how to generate credentials with just login and password to data analytics. Thank you. -
Linkedin API does not return email address in Django 2.0
Here is the test code: Step #1: Request Auth Code args_str = urlencode({ 'response_type' : 'code', 'client_id' : '<app client id>', 'scope' : 'r_emailaddress r_basicprofile', 'state' : '<my state id>', 'redirect_uri' : '<app redirect url>' }) url = 'https://www.linkedin.com/oauth/v2/authorization' return redirect(url + '?' + args_str) Step #2 Handle call back Step #3 Get access token Step #4 Get data from linkedin using access token def get_linkedin_data(request, access_token): api_endpoint_profile = 'https://api.linkedin.com/v1/people/~' access_token = access_token headers = {} headers['Authorization'] = 'Bearer ' + access_token headers['User-Agent'] = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0' headers['x-li-format'] = 'json' values = { 'format' : 'json' } data = urllib.parse.urlencode(values) data = data.encode('ascii') url_request = urllib.request.Request(api_endpoint_profile, data=data, headers=headers, method='GET') url_response = urllib.request.urlopen(url_request) response_data_profile = json.loads(url_response.read().decode('utf-8')) The response_data_profile variable contains basic profile data only but not the email address. What am i missing here? Note: App created in Linkedin developer account with r_basicprofile and r_emailaddress scopes selected Permission granted to scopes basicprofile and emailaddress When api tries to get linked data -
django allauth user_signed_up signal isn't working
from django.db import models import time from django.contrib.auth.models import User from allauth.account.signals import user_signed_up, password_set from django.db.models.signals import post_save from django.dispatch import receiver, Signal # Create your models here. # @receiver(user_signed_up) # def employeeID(sender=User, **kwargs): # old_username = kwargs['username'] # user = User.objects.get(username = old_username) # user.username = str(time.time()).split('.')[0] # user.save() # @receiver(user_signed_up) # # def employeeID(request, user, sociallogin=None, **kwargs): # def employeeID(sender, **kwargs): # print('signal received') # old_username = kwargs.username # user = User.objects.get(username = old_username) # user.username = str(time.time()).split('.')[0] # user.save() # @receiver(user_signed_up) # def employeeID(sender, **kwargs): # request = kwargs['request'] # user = kwargs['user'] # # Do your stuff with the user # username = request.user.username # u = User.objects.get(username = username) # u.username = str(time.time()).split('.')[0] # u.save() # @receiver(user_signed_up) # def employeeID(sender=User, **kwargs): # request = kwargs['request'] # user = kwargs['user'] # # Do your stuff with the user # username = request.user.username # u = User.objects.get(username = username) # u.username = str(time.time()).split('.')[0] # u.save() # @receiver(user_signed_up, sender=User) # def employeeID(sender=User, **kwargs): # username = kwargs['request'].user.username # # username = kwargs['user'].username # print(username) # u = User.objects.get(username = username) # u.username = str(time.time()).split('.')[0] # u.save() # @receiver(user_signed_up) # def employeeID(request, user, **kwargs): # # username = … -
Using django_filters on graphene queries while not using Relay
While using graphene with Relay in django, there is an option to use filtering while querying the data. class AnimalNode(DjangoObjectType): class Meta: model = Animal filter_fields = ['name', 'genus', 'is_domesticated'] OR filter_fields = { 'name': ['exact', 'icontains', 'istartswith'], 'genus': ['exact'], 'is_domesticated': ['exact'], } interfaces = (relay.Node, ) Is it possible to use filtering in this fashion while I'm not using relay or is it a relay-only feature? I don't see any filtering for non-relay in the graphene docs so can't really be sure how to proceed with this. -
Catch Celery exception in case of worker is stopped/failed or Redis is not started, avoiding retry
I have a Celery task that works with Redis: @app.task(bind=True, name='task_a', max_retries=4, soft_time_limit_exception=300) def task_a(self, a, b): try: # some code here except Exception as e: raise self.retry(exc=e, countdown=exponential_backoff(self)) def exponential_backoff(task_self): minutes = task_self.default_retry_delay / 60 rand = random.uniform(minutes, minutes * 1.5) return int(rand ** task_self.request.retries) * 60 I have the following issue: If Redis is not working or celery workers are stopped/failed, the code is 'waiting' until Celery finish 'something', than execute my other code. What I want in this cases, is to catch this specific errors and do other operations, or ignore without calling retry. If this specific exceptions are triggered, return a code/exception to the functions that called the task without doing retry. I tried CeleryError, OperationalError, I don't which exceptions can work in those cases. -
django - Model Serializer destroy method
I have a model named Profile which is a wrapper over the User model of django. Now, I have created a ProfileSerializer in the following way: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data, username=validated_data.get('username')) profile = Profile.objects.create(user=user, **validated_data) return profile def update(self, instance, validated_data): instance.dob = validated_data.get('dob', instance.dob) instance.karma = validated_data.get('karma', instance.karma) instance.username = validated_data.get('username', instance.username) user_data = validated_data.pop('user') instance.user.first_name = user_data.get('first_name', instance.user.first_name) instance.user.last_name = user_data.get('last_name', instance.user.last_name) instance.user.email = user_data.get('email', instance.user.email) instance.user.username = instance.username new_password = user_data.get('password') if new_password: instance.user.set_password(new_password) instance.user.save() instance.save() return instance class Meta: model = Profile fields = '__all__' The problem here is, when I am trying to DELETE a profile, the profile is getting deleted but the user still stays. I need to be able to delete user as well when a DELETE request is made. I tried to do some search but I couldn't find and destroy or delete methods for a ModelSerializer. -
Difference between requests library of python and WSGIRequest of django
In Django/Python, an API can be called using python requests library as well as using a WSGIRequest For example... import requests from django.core.handlers.wsgi import WSGIRequest response1 = requests.get(api_url) response2 = wsgi_request = WSGIRequest({'PATH_INFO': api_url}) What is the exact difference between these way of calling API... WSGIRequest is used to call internally URLs/APIs'?