Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cookies with CORS
I try to send cross-domain POST request from "test.net" to my host "example.com" with browser. In response I set test cookie. response = Response({'ok': True}, status=status.HTTP_200_OK) response.set_cookie('test1', 'test-cookie', domain='example.com') return response However cookies are not set in browser. If I send request with client (Postman, Insomnia) - cookies are returned and set like this test1=test-cookie; Domain=example.com; Path=/ In browser I get no warnings, cookies are gone. Maybe any browser have some logs for this case? I tried this settings on django server: SESSION_COOKIE_SAMESITE = None CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_DOMAIN = 'example.com' -
Having a problem with the follower system, I am following myself in Django
Hey guys I am trying to send a follow request through the django notifications and the person at the other end will be either accepting or rejecting the request. But I have a problem that when the person at the other end accepts the request, this error is showing Something went wrong! and he is following himself. This is the code I have now. def send_follow_request(request, id): current_user = request.user user = Account.objects.get(id=id) notify.send(request.user, recipient=user, verb='has sent you a follow request', target=user) return redirect('posts:userprofile', user.username) def accept_follow_request(request, id): current_user = request.user user = Account.objects.get(id=id) contact, created = Contact.objects.get_or_create(user_from=request.user, user_to=user, follow_status='AC') if user != request.user: create_action(request.user, 'started following', user) notify.send(request.user, recipient=user, verb='started following you') return redirect('all_user_notifications') return HttpResponse('Something went wrong!') This is the notification view class AllNotificationsList(LoginRequiredMixin, NotificationViewList): def get_queryset(self, *args, **kwargs): if get_config()['SOFT_DELETE']: qset = self.request.user.notifications.active() else: qset = self.request.user.notifications.all() return qset Can anyone tell me where the problem is? Thanks! -
¿Why my CORS config in django is not working?
I have my REST API settings in my production.py file. This REST API is uploaded to Heroku and uses django-cors-headers with the following configuration: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-Party apps 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'gunicorn', # Local apps 'core', 'users', 'checkers', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'myapi.herokuapp.com' ) The idea when putting myapi.herokuapp.com in CORS_ORIGIN_WHITELIST is to see if making the request from localhost is rejected (it would be the right thing to do). But this is accepted which gives me to understand that CORS is not working well. -
Implement a tenant like structure for shops
I need a little pointing in the right direction please. I have a shop who owns (multiple) locations and those locations have (multiple) products. models.py: class Shop(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField('name', max_length=120) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) class Location(models.Model): name = models.CharField('name', max_length=120) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) class Product(models.Model): price = models.DecimalField("price", decimal_places=2, max_digits=8) location = models.ForeignKey(Location, on_delete=models.CASCADE) name = models.CharField('name', max_length=120) So there is for example a user "me" and this user belongs to the Shop "Wallmart". "Wallmart" has locations like "NY Shop" and "London Shop". It is ok for me to create the locations in the admin panel and assign them to tenants (working). How would I implement a select box to define the location variable so I can catch it when saving a new product? -
Django rest framework passing ValidationError messages to response
i'm currently trying to pass the ValidationError message from Django to the body of my response. Is there any way to do that? Here is a create method that i'll customize in my viewset. def create(self, request, *args, **kwargs): try: serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) except Exception as error: return Response(data={"Message": str(error)}, status=status.HTTP_400_BAD_REQUEST) And here is the Message that is being returned when there is a ValidationError { "Message": "{'username': [ErrorDetail(string='A user with this username already exists.', code='unique')], 'email': [ErrorDetail(string='Insert a valid email.', code='invalid')]}" } But the result that im trying to achieve is this: { "Message": "A user with this username already exists. Insert a valid email." } Is there any way to extract the strings from the validation error message? -
Django timezone.now() giving wrong time
thanks for your time. i've got a model Profile thats linked on User. And a Hours models thats linked on Profile. By every time a user login a Hours object should be created with the loging_in field automatically set to timezone.now(). I've tried timezone.now(), datetime.now(), timezone.localtime(timezone.now()). Tried all of them on default of loging_in field and on login_view. every try creates the object as i want. But every time gives me the wrong time about 20 minutes earlier or later. So i'd like to know what am i doing wrong and whats the best way to set this (models or views). settings.py: LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = False USE_TZ = True DATETIME_FORMAT = "d/m/Y H:s" models.py: class Hours(models.Model): profile = models.ForeignKey(Profile, on_delete=models.SET_NULL, related_name='hours', null=True) loging_in = models.DateTimeField(default=timezone.localtime(timezone.now())) loging_out = models.DateTimeField(null=True) done = models.BooleanField(default=False) delta = models.DurationField(default=datetime.timedelta(hours=0)) objects = HoursManager() views.py: def login_view(request): if not request.user.is_anonymous: logout_view(request) else: # raise ValidationError('DESLOGUE PRIMEIRO') next = request.GET.get('next') form = LoginForm(request.POST or None) # se estiver escrito certo# if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') # autenticando o usuario# user = authenticate(username=username, password=password) # se estiver tudo certo (autendicado) chamar a função login# login(request, user) p1, status … -
how to update user data in django
I am new to Django I want to add more fields to registration form like (first name, last name, and gender). so I add those fields but when I create update form only username and email appear in fields . here all code ******* views.py ****** from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from . forms import RegisterForm , UserUpdateForm from django.contrib.auth.decorators import login_required def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('home-page') else: form = RegisterForm() return render(request,'Users/register.html',{'form':form}) @login_required def Profile(request): if request.method == 'POST': u_form=UserUpdateForm(request.POST,instance=request.user) if u_form.is_valid: u_form.save() return redirect('Profile-page') else: u_form=UserUpdateForm(instance=request.user) context={'u_form':u_form} return render(request,'Users/profile.html',context) models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Profile' signals.py* from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() ***** forms.py ****** from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): """docstring for ClassName""" email = forms.EmailField() firstName = forms.CharField(max_length=30) LastName = forms.CharField(max_length=30) CHOICES=[('Male','Male'), ('Female','Female')] gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) class Meta: model = User fields = ['username','firstName','LastName','gender','email','password1','password2'] class UserUpdateForm(forms.ModelForm): """docstring for UserUpdateForm""" email = forms.EmailField() … -
Self id in ExpressionWrapper (annotate)
I want to get aggregate of only those values that are created_by a specific user but the expression I wrote gets all of them for me. The issue is fairly simple, don't get too bothered by the code it's only there for reference. I'm Working on following query_set. query_set = ClanMember.objects.select_related('user').prefetch_related( 'user__interviews', 'user__interviews__interview', 'user__interviews__interview__user_task', 'user__interviews__interview__user_task__application__job' 'user__interviews__interview__user_task__job_application_notes' ).filter( role=HiringMemberChoices.Interviewer, is_active=True, user__interviews__interview__user_task__is_active=True, user__interviews__is_active=True, ).values( 'user__id', 'user__email').annotate( interviews=all_interviews_expression, recommendations=total_recommended_expression, accepted_candidates=hired_candidates_expression ).order_by('-interviews') Here lets focus on total_recommended_expression which is collected using the following expression total_recommended_expression = ExpressionWrapper( Count('user__interviews__interview__user_task__job_application_notes__id', distinct=True, filter=Q( user__interviews__interview__user_task__job_application_notes__overall_rating=NoteOverallRatingChoices.Recommended) & Q(user__interviews__interview__user_task__job_application_notes__is_active=True)), output_field=IntegerField() ) Now here is the problem, in job_application_notes there could be multiple entries by different users which is distinguished job_application_notes__created_by_id. Right now it's returning all the values in application_notes against a particular user_task_id, What I want is aggregate for all users specifically (for a user get only those entries whose created_by_id matches). Following is the SQL equivalent that works select * from workflow_jobapplicationnotes where is_active=True and overall_rating='Recommended' and created_by_id=91 .... The thing that I was to add to my Expression wrapper filter is created_by_id={user_id} where user_id will be variable coming from the query but I can't seem to figure out a way to do that. Any help or sense of … -
AttributeError: has no attribute 'STATIC'
So have been trying to start my server on python (Am new to python , django)and below is my code to run my server which can be seen herehttps://shrib.com/#Meerkat9GKd1xx and when i run the code i get the attribute error below: AttributeError: module 'student_management_system.settings' has no attribute 'STATIC' ``` How can i fix this issue -
DRF how to change standart error “No active account found with the given credentials?
Is it possible to change standart error message “No active account found with the given credentials? and if yes so how? Would be nice change the error message (e.g. “Entered email address or password incorrect. Please, try again”. -
Retrieve GraphQL Introspection Schema as http response
I can generate the Django Graphene introspection schema by using the Django management command as ./manage.py graphql_schema --schema tutorial.quickstart.schema --out schema.json How can I return the JSON schema as HTTP Response from a view, so that the client is able to view/fetch the same any time? -
Conditionally save data to different serializer upon certain condition
I am looking to save data to two serializers which are not not nested upon certain conditions. The condition is if data coming to serializer's endpoint has a certain field data, then the data should be saved to the second serializer while at the same time saving to the current serializer. Here is the serializer in question class BookingsCreateSerializer(ModelSerializer): items = BookingItemSerializer(many=True) class Meta: model = Booking fields = ( 'guest_name', 'company_name', 'mobile_Number', 'email', 'special_requests', ) Now if the data that is comming to this serializer contains a password field. Data should also be saved the user profile serializer. How can i go about this? Thank you. Here is the user serializer class UserProfileSerializer(serializers.ModelSerializer): """Serializes user profile object""" class Meta: model = models.UserProfile fields = ['name', 'email', 'password', 'parent', 'from_api', 'is_active', ] //more code here def create(self, validated_data): """Create and return a new user with encrypted password via API""" user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], from_api=validated_data['from_api'], password=validated_data['password'], is_active=validated_data['is_active'], ) user.set_password(validated_data['password']) user.save() return user -
React and Django routing problem in media file
When I am using re_path('.*',index,name='index') unable to route to my media locations and instead of re_path when I am using path('/',index,name='index') then my react app routing is not working. So what should I do? from django.contrib import admin from django.urls import path , include,re_path from .views import index from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/bookdetails/', include('backend.api.urls', 'api')), re_path('.*', index , name='index') ] urlpatterns += static(settings.MEDIA_URL,document_root= settings.MEDIA_ROOT) -
Render Menu with one active item
I am using Django and in my admin i have some items. When i use every item gets Highlighted. But i want only one item to be highlighted when i click that item. This is in my base.html in templates. <aside class="main-sidebar left fadeInleft qaod-sidebar"> <div class="slimScrollDiv"> <section class="sidebar"> <ul class="left-nav"> {% if request.user.is_superuser %} <li><a href="#"><i class="nav-icon fa fa-tachometer-alt"></i><span>Dashboard</span></a></li> <li><a href="#"><i class="nav-icon fa fa-users"></i><span>Groups</span></a></li> <li><a href="#"><i class="nav-icon fa fa-user"></i><span>Users</span></a></li> {% else %} <li><a href="/admin/"><i class="nav-icon fa fa-tachometer-alt"></i><span>Dashboard</span></a></li> <li><a href="/admin/test_suite_optimizer/duplicatetestcase/"><i class="nav-icon fa fa-copy"></i><span>Duplicate Test Case</span></a></li> <li><a href="/admin/test_suite_optimizer/project/"><i class="nav-icon fa fa-project-diagram"></i><span>Projects</span></a></li> <li><a href="/admin/test_suite_optimizer/duplicatetestcase/upload_csv/"><i class="nav-icon fa fa-file-csv"></i><span>Process CSV</span></a></li> {% endif %} </ul> </section> </div> </aside> -
django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "XXXXX", database "XXXX", SSL off
I am new to this after successfully created the Django app and Postgres install, I try to run migration using python manage.py runserver. But I am getting this error django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "::1", user "XXXXX", database "XXXXX", SSL off. I am running this on namecheap cPanel terminal. Anyone with a hint? -
TypeError can't multiply sequence by non-int of type 'str' (Python, Django, Bootstrap)
I am just trying to make a website that calculates force=mass*accleration I have tried adding int it gives, string error or some base 10 error. #mass=int(request.GET['mass']) ...this too gives an error & all the variations of it!!! views.py ```from django.http import HttpResponse from django.shortcuts import render def home(request): return render(request, 'home.html') def calculator1(request): mass = request.GET.get('mass') acc = request.GET.get('acc') print(mass) print(acc) force=mass*acc return render(request, 'calculator1.html', {'result':force})``` urls.py ```from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('calculator1', views.calculator1, name='calculator1'), ]``` calculator.html(a part of it) ```<a href="#" class="list-group-item list-group-item-action"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1">Newton's Second Law of Motion</h5> </div> <form action="calculator1" method="get"> Force = mass * accleration<br> mass = <input type="text" name="mass" size="7"><br> accleration = <input type="text" name="acc" size="7"><br> </form> force = {{result}} </a> <button type="submit" class="btn btn-dark">Calculate</button><br> </div>``` *help pleaseeee -
No module named django_elasticsearch
I try to add elastic search support to my model. I installed via: pip install git+https://github.com/liberation/django_elasticsearch.git --user I added to installed apps, runserver gives no error. INSTALLED_APPS = [ ... 'django_elasticsearch', ] But when I import in the model: from django.db import models from django_elasticsearch.models import EsIndexable class Building(EsIndexable, models.Model): ... and try to makemigrations, I get the following error: ModuleNotFoundError: No module named 'django_elasticsearch' What am I missing? -
Object of type 'Decimal' is not JSON serializable error for using session
I used Django3-by-example book for learning django. I used cart creating procedure from this book step by step and It worked correctly. I wanted to add compare list with the same procedure.after this I ran my django app correctly but I found a bug. If the first session(for example cart session)was empty and I wanted to add a product to second session(for example compare list) I got this error: TypeError: Object of type 'Decimal' is not JSON serializable if the second session was empty the first session worked correctly Also if the first session wasn't empty ,It worked correctly. what is my mistake? -
importError:cannot import name 'home_page' from 'shop.views'
I am a newcomer and I wrote Hello Word to start practicing and I use Django==3.1 and python3 and I encountered this problem ImportError: cannot import name 'home_page' from 'shop.views' and this is my code... views.py from django.shortcuts import render from django.http import HttpResponse def home_page(request): return HttpResponse('Hello world') urls.py from django.contrib import admin from django.urls import path from .views import home_page urlpatterns = [ path('admin/', admin.site.urls), path('',home_page), ] -
Monkey patch created_by and modified_by django
I have an application deployed an year ago. In production I am unwilling to change all models manually to add the created_by and modified_by fields as it would be little risky. Is there anyway, we can achieve it with less amount of coding we could fix it (at least for the future transactions it should add those fields to every model?) I was thinking of monkey patching it, but dont know how to implement it? from django.apps import apps from django.db import models from django.contrib.auth import get_user_model model_list = apps.get_models() #-- Monkey Patch for model in model_list: if model != get_user_model(): model.add_to_class('created_by', models.CharField(max_length=250,blank=True, null=True)) model.add_to_class('modified_by', models.CharField(max_length=250,blank=True, null=True)) def save(self): if self.pk: self.created_by = request.user.id #not sure, how I would get the user here from request self.modified_by = request.user.id return super(model, self).save(*args, **kwargs) model.add_to_class("save", save) -
how to get total price of books django?
if i add some books in store then how can i get the total_price of selected books in store? i am using override save method to get total_price but it's not working... store from django.db import models class Book(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) class Store(models.Model): books = models.ManyToManyField(Vital) total_price = models.IntegerField(default=0) def save(self): super(Book, self).save() self.total_price = self.books.all().aggregate(Sum('price')).self.save(commit=True) -
Django: update field of ManyToMany instance when it's set
Is it possible to do something when setting ManyToMany relations with .set()? Let's say, we have: class ModelA(): b_models = models.ManyToManyField(ModelB, related_name="as", through="ModelMN") class ModelMN(): model_a = models.ForeignKey(ModelA) model_b = models.ForeignKey(ModelB) And when we have an instance of Model A and list of Model B instances: a = ModelA() a.set([b1, b2, b3]) When calling .set(), an instace of ModelMN is created for every a-b relationship. Is it possible to modify a field of that instance (every ModelMN instance), everytime it is created? Overriding .save() method on ModelMN seems not to be working. -
Django session via CORS request
I have runnig django app on host "example.com". I enabled CORS and getting POST request from host "test.net". When I try to set cookie on that response, it is sent back to "test.net" with cookie domain "test.net" - so cookie can not be set. I want to process that request and authorize user on "example.com" (set "sessionid" cookie with domain "example.com"). How can I achieve that? -
how can i get hackerrank ranks and display it on my own website with python?
I want to compare my ranking in Hackerrank with the rankings of my friends and the results I save on the website that I process with django. So how do I access the hackerrank ranking and display it on my website? -
Django query More than one row returned by a subquery used as an expression
I have a pretty simple query and I need to add one field to get an average price grouped by benefit - I tried with ArrayAgg but is not working. properties = ( House.objects.filter( # a lot of filters ).annotate( prices=ArrayAgg( HousePrice.objects.all().values("benefit").annotate(price_avg=Avg("price")).values("benefit_id" "price_avg") ), ) ) more than one row returned by a subquery used as an expression Any ideas on how to resolve that? I'm not sure if this way is good to use ArrayAgg.