Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
test return redirect("account_login") in django use pytest
i using pytest and coverage for testing django project But I don't know how to test the else block that has return redirect("account_login") and fix the red part that says coverage. In your opinion, how can I write a test for that else piece and fix the red part that says coverage? views.py @verified_email_required def profile_view(request, username): # We check if the user is logged in? if request.user.is_authenticated: try: profiles = Profile.objects.all()[:4] # get user profile by username profile = Profile.objects.get(user__username__iexact=username) user = User.objects.get(username=username) user_following = following(user) user_followers = followers(user) logged_in_user_following = following(request.user) logged_in_user_followers = followers(request.user) # if user not found raise 404 error except ObjectDoesNotExist: raise Http404 # context data context = { "user": user, "profile": profile, "profiles": profiles, "following": user_following, "followers": user_followers, } return render(request, "user_profile/profile.html", context) # if a user is not login in redirecting to login page else: return redirect("account_login") test_view.py @pytest.mark.django_db class TestProfileView: @pytest.fixture def user(self): user, created = User.objects.get_or_create( # created user username="test_username", first_name="test_first_name", last_name="test_last_name", email="test@test.com", is_active=True, is_superuser=False, ) ( user_email_address, created, ) = EmailAddress.objects.get_or_create( # user email confirmation email=user.email, user=user ) user_email_address.verified = True user_email_address.primary = True user_email_address.save() return user def test_profile_view_when_user_is_authenticated_return_correct_profile( self, user, client ): client.force_login(user) # user logged in response = … -
How do I mirror Django's email validation on the front end
I am using the user registration url from django rest auth: urlpatterns = [ #... path("registration/", include("dj_rest_auth.registration.urls")), #... ] This route includes email validation. However, I would like to prevalidate addresses before I send them to the server. Using a simple regex on the front end allows addresses through that dj_rest_auth doesn't: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) Will allow, for example, a@b.c which django will reject. I would like to match the server side validation as closely as possible with javascript. What regex does dj_rest_auth use? -
For creating app to upload and dislpaly images i am getting, ModuleNotFoundError: No module named 'posts.url'
created Django project called django_project and a new app called posts. (.venv) > django-admin startproject django_project . (.venv) > python manage.py startapp posts django_project/settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "posts", # new ] python manage.py migrate posts/models.py from django.db import models class Post(models.Model): title = models.TextField() cover = models.ImageField(upload_to='images/') def __str__(self): return self.title config/settings.py MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media" (.venv) $ mkdir media (.venv) $ mkdir media/images posts/admin.py from django.contrib import admin from .models import Post admin.site.register(Post) python manage.py makemigrations Migrations for 'posts': posts/migrations/0001_initial.py - Create model Post python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, posts, session s Running migrations: Applying posts.0001_initial... OK (.venv) > python manage.py createsuperuser (.venv) > python manage.py runserver "Till here the code worked fine" config/urls.py from django.contrib import admin from django.conf import settings # new from django.urls import path, include # new from django.conf.urls.static import static # new urlpatterns = [ path("admin/", admin.site.urls), path("", include("posts.urls")), # new ] if settings.DEBUG: # new urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) posts/urls.py from django.urls import path from .views import HomePageView urlpatterns = [ path("", HomePageView.as_view(), name="home"), ] posts/views.py from django.views.generic import ListView from .models import Post class HomePageView(ListView): … -
Django models. How do I make "add new" filed in Django?
I am trying to make an OfferUp-like web app using Django Framework. Everything has been going great until I ran into a problem. How could I make it so that users can upload multiple pictures, instead of just one using the models.ImageField() function? You know? We might have users that only have 5 pictures to upload, while another user might have 8. How could I make it so that users can upload into the database as many pictures as they want? -
TypeError for aggregate queryset value in JsonResponse along with other queryset without loop?
I am trying to pass the value of b_tot along with my other queryset in JsonResponse. Is there a different way to get this result? all_reports = Task.objects.filter(start__gte=start, start__lte=end) query = all_reports.values() user_total_bill = all_reports.aggregate(b_tot=Sum(F('hours') * F('bill_rate'))) return JsonResponse(list(chain(query, user_total_bill['b_tot'])), safe=False) and getting the error return JsonResponse(list(chain(query, user_total_bill['b_tot']))) TypeError: 'float' object is not iterable I have to do calculations based involving hours and bill_rate for multiple users that match the input criteria. I cannot change the models so have to work in the view only. What else I tried: json dump and serialize.serializer. Any help would be appreciated, TIA -
How display data on a map using django , leaflet and AJAX
How display data on a map using django , leaflet and AJAX? At what level of even_map.html and how should I add the loop that allows to retrieve the coordinates of the events to be able to add and display markers on the map? Below are my programs. I have no error but the markers are not displayed on the map. #models.py class Evenement(models.Model): name = models.CharField(max_length=20) date = models.DateField() time=models.TimeField() longitude = models.FloatField(null=True, blank=True) latitude = models.FloatField(null=True, blank=True) geom = models.PointField(srid=4326, null=True, blank=True,) @property def geom(self): return (self.longitude, self.latitude) def __str__(self): return self.name #views.py def evenement_map(request): all_evenements = Evenement.objects.all() return render(request, 'even_map.html', {'all_evenements': all_evenements}) def EvenementData(request): name = serialize('geojson', Evenement.objects.all()) return HttpResponse(name,content_type='json') #urls.py app_name="evenement" urlpatterns = [ path('evenement_register/', views.evenement_register,name="even_register"), path('evenement/', views.EvenementData, name= 'evenement'), path('evenement_map/', views.evenement_map,name="even_map"), ] #forms.py class evenement_form(forms.ModelForm): class Meta: model=Evenement fields='__all__' widgets={ 'date': DatePickerInput(format='%d/%m/%y'), 'time': TimePickerInput(), 'geom': LeafletWidget(attrs={}), } labels={ 'name': _("Name:"), 'date':_("Date :"), 'time': _("Time :"), 'longitude':_("Longitude :"), 'latitude':_("Latitude :"), 'geom':_("Localisation :"), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('name', css_class='form-group col-md-2 mb-0'), Column('date', css_class='form-group col-md-2 mb-0'), Column('time', css_class='form-group col-md-2 mb-0'), Column('longitude', css_class='form-group col-md-2 mb-0'), Column('latitude', css_class='form-group col-md-2 mb-0'), css_class='form-row' ), Submit('submit', 'Register') ) <!---even_map.html--> <!DOCTYPE html> {% load … -
What is the best way to implement these models?
I am trying to create a social media app where users can sign up, make posts, view others post, like and unlike other Users posts. What would be the best way to implement the models for the like and unlike feature? Initially, I created a post model in a post app and two models: like and unlike in a reactions app. Do you think this is a good idea? -
CSS3/HTML Divs are mismatched somewhere
I'm following along a tutorial and, unfortunately, his code editor automatically indented everything when he copied/pasted a new <div> (Sigh) I assumed I would be able to fix it, however, I'm clearly an idiot. (In the second pic I cut off the top where it has LOGO in the top right on accident in the screenshot) This is what my site looks like This is what I would like it to look like {% extends 'main.html' %} {% block content%} <div class="room-container"> <div> <style> .room-container( display: grid; grid-template-columns: 3fr 1fr; ) </style> <div class="room-container"> <div> <h1>{{room.name}}</h1> <p>{{room.description}}</p> <div class="comment-wrapper"> <h3> Conversations </h3> <hr> {% for message in room_messages %} <div> <a href="{% url 'delete-message' message.id %}">Delete</a> <small>@{{message.user}} {{message.created|timesince}} ago </small> <p>{{message.body}}</p> <hr> </div> {% endfor %} </div> <div> {% if request.user.is_authenticated %} <div class="comment-for"> <form method="POST" action=""> {% csrf_token %} <input type="text" name="body" placeholder="Comment here.." /> </form> </div> </div> </div> {% endif %} <div> <h3>Participants</h3> <hr> {% for user in participants %} <div> <p>@{{user.username}}</p> </div> {% endfor %} </div> </div> {% endblock %} -
Get files local server with django-heroku
I'm developing a project using django, and I'm thinking of deploying my app on heroku, but it doesn't store images and files, and I'd like to store them on a server on my local machine, is there any way or tutorial I can follow ? -
Django for multiplayer games website (poker)
I am creating a poker card game website with javascript, I was wondering if it is possible to make it a multiplayer game and run it live with django as backend (django is the only backend frame work i know, i made many projects but never worked with sockets or channels this is my first project ) -
BLOB/TEXT column 'x' used in key specification without a key length
I am getting hung up on this error. I have moved from SQLLite to MySQL with PythonAnywhere for my Django webapp. When running my migrate command I am getting the following error: BLOB/TEXT column 'Connector' used in key specification without a key length This is the models.py class POS_Accounts(models.Model): Connector = models.CharField(max_length = 100, blank=True) StoreName = models.TextField(blank=True) AccountUsername = models.TextField(blank=False) ExpirationDate = models.DateTimeField(null=True, blank=True) MerchantId = models.TextField(blank=False, max_length=100) AccessToken = models.TextField(blank=False) RefreshToken = models.TextField(blank=False) -
Django: I am getting "ValueError: needs to have a value for field "id" before this many-to-many relationship can be used."
I am trying to write a function record_post that saves a Post with the following model: class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.CharField(max_length=1000) date_created = models.DateTimeField() platforms = models.ManyToManyField(Platform) And here is the record_post function: def record_post(user, body=None, platforms=None): post = Post( user=user, body=body, date_created=timezone.now(), ) # Add platforms facebook = Platform.objects.get(name="Facebook") if "facebook" in platforms: post.platforms.add(facebook) post.save() return post However, when I run the function I get the following error: ValueError: "<Post: 53>" needs to have a value for field "id" before this many-to-many relationship can be used. -
Avoid database hits when requests are only GET (using django-cachalot)
Django==4.0.6 django-cachalot==2.5.1 Models: from django.db import models from django.urls import reverse class Poll(models.Model): name = models.CharField(max_length=200) def get_absolute_url(self): return reverse("poll", kwargs={'pk': self.id}) def __str__(self): return self.name class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def get_absolute_url(self): return reverse("choice", kwargs={'pk': self.id}) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Templatetags from django import template from django.utils.safestring import mark_safe from polls.models import Question register = template.Library() @register.simple_tag(takes_context=True) def question(context, id): question = Question.objects.get(pk=id) choices = question.choice_set.all() html = "<p>" + question.question_text +"</p>" html += "<p>Answers</p>" for choice in choices: html += "<p>" + choice.choice_text + ": " + str(choice.votes) + "</p>" return mark_safe(html) cache_project/cache/polls/templates/polls/poll_detail.html {% extends 'polls/base.html' %} {% load polls %} {% block content %} <p>Poll: {{ object.name }}</p> <p>Question 1: {% question id=1%}</p> {% endblock %} Admin: from django.contrib import admin from .models import General from django.apps import apps @admin.action(description='Warm cache up') def warm_up(modeladmin, request, queryset): MODELS_AND_APPS = { "Poll": "polls", "Question": "polls", "Choice": "polls", } for model_name in MODELS_AND_APPS: current_model = apps.get_model(app_label=MODELS_AND_APPS[model_name], model_name=model_name) all_instances = current_model.objects.all() list(all_instances) # The very warming the cache up. class GeneralAdmin(admin.ModelAdmin): actions = [warm_up] admin.site.register(General, GeneralAdmin) I … -
How to allow JSON access to the text within a textarea in HTML>
I am trying to create a button that allows users to save edits to a post, which they write in a textarea, through JSON. I am trying to save the data through a PUT request, but I get the following error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) javascript function: function save_edit(id){ console.log("save button is clicked"); const edit_area = document.querySelector(`#edit_area_${id}`); //save the post fetch(`/edit/${id}`,{ method: 'PUT', post: JSON.stringify({ post: edit_area.value }) }) } django.views: def edit(request, post_id): try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: return JsonResponse({"error": "Post not found."}, status=404) if request.method == "POST": edited_post = request.POST.get('post') try: post.post = edited_post post.save() except: return JsonResponse({"error": "Editing the post did not work."}, status=404) elif request.method == "GET": return JsonResponse(post.serialize()) elif request.method == "PUT": data = json.loads(request.body) edited_post = data["edit_area"] post.post = data["edited_post"] post.save() else: return JsonResponse({"error": "Need a GET request."}, status=404) html {% for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself_{{ post.id }}" class="post_itself">{{ post.post }}</h6> {% if post.user == request.user %} <button id="{{ post.id }}" class="edit_button" value="{{ post.id }}">Edit</button> {% endif %} <textarea class="textarea" id="edit_area_{{ … -
AttributeError at /cart 'str' object has no attribute 'get'
in django e-commerce website i have the error AttributeError at /cart 'str' object has no attribute 'get' i'm realy dont what happend, i have the code which must work with my task, but it doesnt work too Please help me U can find a code below my views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Category, Product, Cart, CartItem from django.core.exceptions import ObjectDoesNotExist # Create your views here. def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_cart_id(request)) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create(product=product, quantity=1, cart=cart) cart_item.save() return redirect('cart_detail') def cart_detail(request, total=0, counter=0, cart_items=None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass return render(request, 'cart.html', dict(cart_items=cart_items, total=total, counter=counter)) -
Code just work when debuggig line by line
I'm running a django app and when I run in debuung mode, lien per line, the code works well. Bur in normal mode(runserver), somethings not work.. Someone can explain? I'm trying to run the follow code: def edit_picture(form, request, User_): person = Person.objects.get(User=User_) person.Picture.delete(save=False) person.Picture = None person.save() form.instance.Picture = request.FILES['Picture'] return form The rest of the project is ok.. -
How does a Django ModelForm base class replace widgets for all DateFields?
I have a very simple HTML date picker widget: class NativeDateInput(forms.widgets.DateInput): input_type = 'date' I can use this widget in a repeat-yourself manner in a single ModelForm: class DirectFormExample(ModelForm): my_date = forms.DateField(widget=NativeDateInput) ... I would like a DRY version of this that replaces widgets for all date fields for forms inheriting from an abstract ModelForm base class, but I cannot work out what this should be from either of these strongly related questions: Django Problem inheriting formfield_callback in ModelForms https://stackoverflow.com/a/661171/4107809 class BaseModelForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name, field in self.fields.items(): if isinstance(field, django.forms.fields.DateField): field.widget = NativeDateInput class Meta: abstract = True class SimpleExample(models.Model): my_date = models.DateField() class SimpleForm(BaseModelForm): class Meta: model = SimpleExample fields = ['my_date'] Unlike for the repeat-yourself version, this fails: Widget.use_required_attribute() missing 1 required positional argument: 'initial' How can I perform the widget replacement for all DateFields in all forms inheriting from BaseModelForm? -
Django Multiple Vendor for brick and molar store
I need to find a way to use Django models or forms to upload products to a specific vendor. For example, I have 3 vendors at my store A01, A02, and A03. A01 sells 4 products, A02 sells 1 product, and A03 sells 20 products. In the form I type: A01 - product 1 - cost A01 - product 2 - cost A01 - product 3 - cost A01 - product 4 - cost A02 - product 1 - cost......... and so on and when I send the form it reads and updates and adds products of the vendor that sold it. if that makes sense. -
Unable to customize user registration with djoser
I have being using djoser with django to handle register and login. I have no issue configuring the default register field (username, email, password and re_password). But now I want to customize the register field and add gender and hobby. However, I keep getting the following error when I try to register another user with these additional fields that djoser does not provide by default. user = User.objects.create_user(**validated_data) TypeError: UserManager.create_user() missing 2 required positional arguments: 'gender', 'hobby' The error is coming from the function in models.py file for creating new user shown below: class UserManager(BaseUserManager): def create_user(self, username, email, gender, hobby, password=None, **extra_fields): if username is None: raise ValueError(_('Username is required')) if email is None: raise ValueError(_('Enter a functional email address')) if gender is None: raise ValueError(_('Provide your gender')) if hobby is None: raise ValueError(_('Enter hobby')) user = self.model(email=self.normalize_email(email) **extra_fields) user.username=username user.gender=gender, user.hobby=hobby user.set_password(password) user.save() return user def create_superuser(self,username, email, gender, hobby, password=None): if password is None: raise ValueError(_('Please enter your password')) user = self.create_user(email=self.normalize_email(email)) user.username=username user.gender=gender, user.hobby=hobby user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=25, unique=True, default='') email = models.EmailField(max_length=255, unique=True) gender = models.CharField(max_length=50, null=True, blank=True) hooby = models.CharField(max_length=50, null=True, blank=True) is_active … -
How to create a model by specifying the field names of the Foreign key that are unique together rather than it's pk?
I'm trying to configure REST framework serializer to POST a Target object by specifying the 3 field names of it's Foreign relation Market that are unique together (symbol, exchange, type), rather than specifying the primary keys of the Market object. models.py class Exchange(models.Model): exid = models.CharField(max_length=12, unique=True) class Market(models.Model): symbol = models.CharField(max_length=5) type = models.CharField(max_length=5) exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='market') class Meta: unique_together = ['symbol', 'type', 'exchange'] class Target(models.Model): weight = models.FloatField() exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='target') market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='target') dt = models.DateTimeField(null=True) Instead of this : { "weight": 19.23, "market": 11, "dt": "2022-06-09" } I would like to post in this form : { "weight": 0.1923, "market_symbol": "ABC/USD", "market_type": "xyz", "market_exchange_exid": "my_exchange", "dt": "2022-06-09" } To achieve this I created a class ModelSerializer and added the 3 custom fields that uniquely specify a market, as suggested in Specifying fields explicitly. class TargetSerializer(serializers.ModelSerializer): market_symbol = serializers.StringRelatedField() market_type = serializers.StringRelatedField() market_exchange = serializers.StringRelatedField() class Meta: model = Target fields = ('id', 'weight', 'dt', 'market_symbol', 'market_type', 'market_exchange') However when I push the data it throws a Bad Request 400. How can I tell him to use this fields as a Foreign key selector ? -
how create form for multiple data and related tabels in django
I want to save several photos for product at the same time when creating a product with one form for product and images this is my models.py class Producte (models.Model): title = models.CharField(max_length=30) price = models.PositiveBigIntegerField() inventory = models.IntegerField(default=0) __discount__ = models.IntegerField(default=0) description = models.TextField() @property def totulpoint(self): like = Comments.objects.filter(commentType=0).count() persentlike = Comments.objects.all().count() / like return 100 / persentlike @property.setter def discount (self , number): if not number in range(0,100): raise ValueError("dicsount must be in range 1,99") else: self.__discount__ = number @property def discount(self): return self.price - (self.price * (self.__discount__ / 100)) class Images(models.Model): image = models.ImageField() producteid = models.ForeignKey(to=Producte ,on_delete=models.CASCADE) this is my forms.py class ProducteForm(forms.Form): title = forms.CharField(max_length=30) price = forms.IntegerField() inventory = forms.IntegerField(default=0) __discount__ = forms.IntegerField(default=0) description = forms.Textarea() @property.setter def discount (self , number): if not number in range(0,100): raise ValueError("dicsount must be in range 1,99") else: self.__discount__ = number class Meta : fields = [ "title", "price", "inventory", "discount", "description", ] Sorry for asking such a question, I'm new to Django Django -v => 4.0.5 -
Django Dynamic/Clone Models
I am looking for a way to achieve the following with Django, would appreciate it if someone can point me in the right direction to do this. There are 3 registered models in an app (Model1,Model2 and Model3). The user will submit a form (single field, e.g. Project Name and Submit button), let's say the project he creates by submitting this form is 'PROJECT001'. Then what is expected to be done is to copy/clone the 3 models (Model1,Model2 and Model3) with a suffix of the project, i.e. 3 new models should be created 'PROJECT001_Model1', 'PROJECT001_Model2', 'PROJECT001_Model3'. I have tried to search for this, however can't find any resources. The closest I have found is https://code.djangoproject.com/wiki/DynamicModels but this documentation seems confusing. Any help is appreciated. Thanks. -
Some problem in customizing a serializer of Djoser
I created two customized serializer for the user_create and current_user endpoints in Djoser. I also wanted to have re_password field in user registeration. But when I add "USER_CREATE_PASSWORD_RETYPE": True in the setting of Djoser, my serializer for create user doesn't work. Could you tell me where is the problem? here is my serializer: from djoser.serializers import UserSerializer as BaseUserSerializer, UserCreateSerializer as BaseUserCreateSerializer class UserCreateSerializer(BaseUserCreateSerializer): class Meta(BaseUserCreateSerializer.Meta): fields = ['id', 'username', 'password', 'email', 'first_name', 'last_name'] class UserSerializer(BaseUserSerializer): class Meta(BaseUserSerializer.Meta): fields = ['id', 'username', 'email', 'first_name', 'last_name', 'password'] and here is settings of Djoser: DJOSER = { "USER_CREATE_PASSWORD_RETYPE": True, "SERIALIZERS": { 'user_create': 'core.serializers.UserCreateSerializer', 'current_user': 'core.serializers.UserSerializer', } } -
Use QueryManager in Filter After SelectRelated
I'm trying to do select_related join in Django followed by a bunch of filtering. queryset = Foo.foo_manager.all().select_related("bar").filter( bar__field_1__gt=0, bar__field_2=1, bar__field_3__lt=100, bar__field_4="X", ) But the Bar class already has its own query manager called bar_manager that fetches all instances that match this condition. Is there a way to use this after the select_related? E.g. queryset = Foo.foo_manager.all().select_related("bar").filter(bar__bar_manager__all=True) -
How can I implement post_save signals in Django?
I am currently building a geolocation app, and I'm somewhat stuck somewhere. I'm trying to implement a post_save Django signals in this code, but I can't figure out what exactly I need to do. any help here would be appreciate. Here's my code: from ipaddress import ip_address from django.contrib.auth import get_user_model from celery import shared_task from apps.users.abstractapi import AbstractAPI User = get_user_model() @shared_task def enrich_user(user_pk): user = User.objects.get(pk=user_pk) api = AbstractAPI() location_details = api.get_geolocation_details(ip_address=user.ip_address) if location_details is not None: user.country = location_details.get("country") user.country_code = location_details.get("country_code") user.country_geoname_id = location_details.details.get("country_geoname_id") user.longitude = location_details.get("longitude") user.latitude = location_details.get("latitude") user.save(update_fields=("country", "country_code", "country_geoname_id", "longitude", "latitude")) holiday_details = api.get_holiday_details( country_code=user.country_code, day=user.date_joined.day, month=user.date_joined.month, year=user.date_joined.year, ) if holiday_details is not None and any(holiday_details): user.joined_on_holiday = True user.save(update_fields=("joined_on_holiday",))