Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django relationship with User default auth model and another Model
I’m developing a web application where users can subscribe to different series of texts, that would be seen inside the system. I want to create a relationship between the User and the SeriesText, so I can grab the current logged user in the VIEW, and just return all of his subscriptions at the dashboard template. An user would be able to subscribe to as many series as he wants. I’m using the default User model from django.contrib.auth.models, and I’m not sure how to create this relationship. I read a lot and I think the correct usage here would be Many-to-many (is that correct?), so I tried this, using a pivot table/model called Subscriptions: from django.contrib.auth.models import User as BaseUserClass class User(BaseUserClass): subscriptions = models.ManyToManyField(SeriesText, through="Subscription") class SeriesText(models.Model): series_name = models.CharField(max_length=255) series_text = models.CharField(max_length=255) subbed_users = models.ManyToManyField(User, through="Subscription") class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) series = models.ForeignKey(SeriesText, on_delete=models.CASCADE) def subscribe(self, user_id, series_id): self.user = user_id self.series = series_id self.save() But that didn’t seem to work, I got errors even trying to use a User.objects.get(pk=1), don’t really know why. I’m really confused if I need to put the relationship both ways, like created models.ManyToMany on SeriesText model, and on an extended User … -
Django JSONField nested greater than operation
Here's the structure of the JSONField - data I have. data : { "animals" : [ "animal_id" : 2321, "legs" : [ { "name" : "front", "measured_at" : 1596740795.453353 }, { "name" : "back", "measured_at": 1596740795.453353 } ] ] } I need to find all records that match the following condition legs-name = "front" OR measured_at is greater than 6 hrs from now. I have tried the following six_hrs_ago = (datetime.utcnow() - timedelta(hours = 6)).timestamp() obj = Model.objects.filter(data__has_key='animals'). filter(Q(data__animals__legs__name="front") | Q(data__animals__legs__measured_at__gt = six_hrs_ago)))) This doesn't work, and it fetches no record. I also tried to just filter the records with legs - name - front, that doesn't work either obj = Model.objects.filter(data__animals__contains=[{'legs': [{"name": "front"}]}]) Any ideas are appreciated. -
Optimal model design for historical data tracking
How to construct relationships between these two models? Company stores data about a company: class Company(models.Model): """Company related data""" name = models.CharField(max_length=120) abbrev = models.CharField(max_length=5) founded = models.IntegerField(null=False) country = models.CharField(max_length=60) Meanwhile StockQuote tracks history of shares' prices: class StockQuote(models.Model): """Price history""" fetch_date = models.DateField(default=timezone.now()) business_day_date = models.DateField(default=timezone.now()) price = models.CharField(max_length=8, default='0.00') Considering that each of StockQuote records can be assigned just one Company, how should these models be connected with relationships so that it would be straightforward to display all prices listed, querying just the Company model (API endpoint)? -
DRF Custom Password Serializer `create()` must be implemented
When try to Update password it required create() How to add it in the right way? Serializer My serilizer class UserPasswordChangeSerializer(serializers.Serializer): old_password = serializers.CharField() password = serializers.CharField() class Meta: model = User fields = ('old_password', 'password') def validate(self, data): if not self.context['request'].user.check_password( data.get('old_password')): raise serializers.ValidationError( {'old_password': 'Wrong password.'}) return data def update(self, instance, validated_data): instance.set_password(validated_data['password']) return super().update(instance) View My action view @action(methods=['post'], detail=True) def change_password(self, request, *args, **kwargs): user = self.get_object() user.serializer = UserPasswordChangeSerializer(data=request.data, context={'request': request}) user.serializer.is_valid(raise_exception=True) user.serializer.save() return Response(status=status.HTTP_204_NO_CONTENT) -
django: OperationalError at /handle_contact
I have used forms for my contact page. When I fill the form and click on submit option in my contact page I get error which says Operational Error at /handle_contact no such table: app_contact -
How to implement session timeout - Angular - Django app integration with Azure AD
Overview - I am working on a solution having UI built in angular and backend in django. I want to implement authentication and authorization using Azure AD. At UI, I have made use of @azure/msal-angular, which acquires access tokens directly from azure each time a backend enpoint is hit. Problem 1 - Access tokens are acquired in the background and never expire unless user logs out. Is there a way to log user out after certain period of time/inactivity? Problem 2 - @azure/msal-angular uses implicit grant flow which receives user tokens in url fragments, which seems not secure. Is auth code a better way to go about it? -
Django query- annotating with one of two fields (depending on what exists)
I have the following models, that describe employees on a job: class Job(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) # Several other Job related fields class CrewAssignment(models.Model): job = models.ForeignKey(Job, on_delete=models.PROTECT, related_name='crew_assignments') user = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateField() # Several other crew related fields class SubAssignment(models.Model): job = models.ForeignKey(Job, on_delete=models.PROTECT, related_name='crew_assignments') user = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateField() # Several other sub related fields Given a User u, and a Date d, I am trying to assemble a query that will return all Job entities that u was either a CrewAssignment or SubAssignment on with a date on or after d, annotated with the date. For example, if d is 2020-08-06, and the user has the following assignments: CrewAssignment | Job id 1 | 2020-08-06 SubAssignment | Job id 2 | 2020-08-06 CrewAssignment | Job id 1 | 2020-08-07 CrewAssignment | Job id 3 | 2020-08-07 SubAssignment | Job id 3 | 2020-08-07 Things to note- the user was on Job 1 on multiple days (so there should be an entry for each day), and the user was a CrewAssignment and a SubAssignment for Job 3 on the same day, which should only create one entry. I would like … -
'Request' object has no attribute 'get' error while getting the api url
In this when I got to the validat_phone URL and I post the phone_number in URL, it returns the error 'Request' object has no attribute 'get', I don't know how to fix the error. Is there is a way to fix the error? Here is my view.py class ValidatePhoneSendOTP(APIView): def post(self, request, *args, **kwargs): phone_number = request.data.get('phone', False) if phone_number: phone = str(phone_number) user = User.objects.filter(phone__iexact = phone) if user.exists(): return Response({ 'status' : False, 'status' : 'Phone number is already exists.' }) else: key = send_otp(phone) if key: PhoneOTP.objects.create( phone = phone, otp = key, ) link = f'My--api-url - {phone}+ {key}' test = request.get(link) return test; return Response({ 'status' : True, 'detail' : 'OTP sent successfully.' }) else: return Response({ 'status' : False, 'detail' : 'Sending otp error.' }) else: return Response({ 'status' : False, 'detail' : 'Phone number is not given in post request.' }) def send_otp(phone): if phone: key = random.randint(999,9999) print(key) return key else: return False -
How can I use django to display data on a website without reloading the whole page
i use django to render a page. If a user now requests information, I would like to load it from the database and display it on the website. It's actually quite simple. I get the information in Django and I find the data in the database. BUT how do I get them back to the user. I don't want to re-render the whole page (it could) I just want to re-render part of the website without having to reload the whole page. Is there a trick? I might have thought of sending the data back via AJAX and adjusting the page using js, but isn't there a more elegant option from django and is AJAX still up to date? had heard that this should no longer be used ... -
How do I manually ask Django to translate a string (which I know there is a translation for)?
I just implemented translations for my learning-to-code-side-project, and it works great! I also use django-modeltranslation for models, and no problems there either. As a finishing touch I wanted to create a view that changes the language. It should take a single keyword argument - the language_code of the desired language, e.g. "en-us", "de", "nb" and so on, and also should accept the GET parameter next, which I then forward the user to after the language settings have been updated. E.g.: http://127.0.0.1:8000/en-us/change-language/nb/?next=/en-us/dashboard/ In this example url /en-us/ is the current language, /change-language/ is the location of the change-language-view (so to speak), /nb/ is the desired language, and ?next=/en-us/dashboard/ is the current url in the current language (and thus where users will be redirected after having their language changed, and after the url have been translated to a new language, e.g. "/nb/kontrollpanel/") I made the URL-translations work with resolve and reverse as seen below: def change_language_view(request, **kwargs): #get and validate the language user is trying to change to language_code = kwargs.get('language_code', None) try: assert [lang[0] for lang in settings.LANGUAGES if lang[0] == language_code], _("%(selected_languages)s not in %(settings_languages)s"%{language_code, settings.LANGUAGES}) except (AssertionError, TypeError) as err: raise Http404(_("Couldn't find that language: ")) #get the next … -
How to send signal from nodemcu to Django website
How to send a signal from nodemcu to Django website Actually I want an IP address of nodemcu to find its location In my project, I want to location of that nodemcu and that location will display to admin of geopy map in Django website and I don't want to use PHP and SQL language. please help me, please. -
Django check if post value exists in db
I'm trying to submit two forms with one submit button. First I want to check if form 1 already exists in the db, if id does then just post the second form using the "ticker" from first form as Foreginkey. But seem to get an error: 'UserTickerForm' object has no attribute 'get' My code: if request.method == 'POST': request_form_user_ticker = UserTickerForm(request.POST) request_form_trade = TradesForm(request.POST) if request_form_user_ticker.is_valid() and request_form_trade.is_valid(): if not User_Ticker.objects.filter(portfolio=select_portfolio, ticker=request_form_user_ticker.get('ticker')).exists(): user_ticker_instace = request_form_user_ticker.save(commit=False) user_ticker_instace.portfolio = select_portfolio user_ticker_instace.save() trade_instance = request_form_trade.save(commit=False) trade_instance.ticker = request_form_user_ticker.get('ticker') trade_instance.save() else: trade_instance = request_form_trade.save(commit=False) trade_instance.ticker = request_form_user_ticker.get('ticker') trade_instance.save() Does anyone know who this is happening and what I can do to fix this? -
Image submit button: POST data includes name.x and name.y but not name
This is my input element: <input class="desktop_hidden" type="image" alt='Submit' src="{% static 'auctions/images/button.png' %}" value="Post Comment" name="make_comment"> When I submit this, I get an error "ValueError: The view auctions.views.listing_page didn't return an HttpResponse object. It returned None instead." When I inspect the POST data, it has "make_comment.x: 0", and "make_comment.y: 0", but not "make_comment: Post Comment" that it has when I use a normal submit button. I'm guessing I'm missing something basic in the html, what is it?? -
How to interact with DB from a button on Django when your 'item' change every refresh (Python)
I'm looking for a way to change an 'item' (the one displayed on the page) in the DB. But first, I should have 2 buttons on the page. And secondly, The 'item' shown is random from the DB. So the problem is : How can I change the item info in the DB knowing that the button will refresh the page to send it in the request. (I remind you that my item is random and so, change every refresh) So, I need a way to change it or a way to randomize the page but not when I send a POST request My views.py : (Messy but it's ok xD) def review(request): loop = True i = 0 while loop and i < len(Cartes.objects.filter(user_id_shared_id__exact=request.user.id).values_list('pk', flat=True))*4: i = i + 1 pks = Cartes.objects.filter(user_id_shared_id__exact=request.user.id).values_list('pk', flat=True) if len(pks) == 0: loop = False return redirect('/create/') random_pk = choice(pks) card = Cartes.objects.get(pk=random_pk) obj, created = Review.objects.get_or_create( card_id_id=card.id, user_id_id=request.user.id, ) print(card.id, "///", obj.id) date_3_days = obj.review_date + datetime.timedelta(days=3) date_7_days = obj.review_date + datetime.timedelta(days=7) date_21_days = obj.review_date + datetime.timedelta(days=21) date_42_days = obj.review_date + datetime.timedelta(days=42) if obj.review_level == 1: loop = False elif obj.review_level == 2 and datetime.date.today() >= date_3_days: loop = False elif obj.review_level … -
Django User password field different from what it's supposed to be
When working with projects with Django, usually the password field in the admin page is disabled and just shows information like this: algorithm: pbkdf2_sha256 iterations: 180000 salt: vakJGB****** hash: mD0TmS************************************** The problem is that it's using an enabled password field which admin users can interact with and I want to stop that. My User model: from django.db import models from django.contrib.auth.models import AbstractUser from prototype.settings import AUTH_USER_MODEL class Agent(AbstractUser): parent = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='children') -
Configure one API for two apps
My case: I'm creating a SaaS that has two client types, both of which must be able to access the same API, one is built in React and the other in Electron, the API is built in Django. The problem: I'm a bit new to working with APIs, so I don't know what I should do in this case. What I think is that I should upload the API to a cloud and then access it from the clients I need, however I think I would need to implement authentication for the API. My question: Am I right or what should I do? -
How to access "other side" of ManyToMany relationships in Django/Wagtail?
I think I'm lacking the right search term for what I'm looking for here. I've got a model for BookPage that accepts multiple authors in a ParentalManyToMany relationship in Wagtail. I'm able to access each of the authors in a template using this code: {% with author=page.author.all %} {% if author %} {% for aut in author %} <div> {{ aut }} </div> {% endfor %} {% endif %} {% endwith %} This prints each author associated with a book. How do I do the reverse, and get all the books written by a particular author, though? I can't seem to find anything about this in the Wagtail docs. -
Why i couldn't save the student's profile in the database
I'm new at django and trying to extend the custom user to multiple user profiles and when i am trying to save the user it says "Student with this Group already exists." The first user registered normally but when i create the second second one it raise the error even the user model dosen't have a membership with the group here is my code models.py class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( (1, 'student'), (2, 'parent'), (3, 'gard'), (4, 'teacher'), (5, 'secretary'), (6, 'supervisor'), (7, 'admin'), ) is_active = models.BooleanField(default=True) user_type =models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,null=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile') group = models.OneToOneField(Group,related_name='student_group',on_delete=models.CASCADE,null=True) teacher = models.ManyToManyField(Teacher,related_name="student_teacher") def save(self,*args,**kwargs): self.user.is_active = False return super(Student,self).save(*args,**kwargs) class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) retuen super().save(*args, **kwargs) This is my forms.py file views.py def student_signUpView(request,**kwargs): registered = False if request.method == 'POST': user_form = UserSignUpForm(request.POST) profile_form = StudentSignUpForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.set_password(user_form.cleaned_data['password2']) print(user.user_type) user.save() profile = profile_form.save(commit=False) profile.user = user profile.exist = True profile.save() registered = True else: print(user_form.errors,profile_form.errors) else: user_form = UserSignUpForm() profile_form = StudentSignUpForm() return render(request, 'accounts/singup.html',{ 'registered':registered, 'user_form': user_form, 'profile_form': profile_form, }) and here is the … -
redirect to a page with pk on django
This funtion is to update an order, i would like to be redirected to the customer profile page where i can find all this customer's orders. on the costumer profile i have all orders listed with option to modify or delete. i would like to modify and to redirected to the costumer profile page which the url is : path("customer_profile/<int:pk>/", views.Customer_profile, name="customer_profile") def OrderUpdate(request, pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method == 'POST': form = OrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('orders') context = {'form':form} return render(request, 'orders/order_form.html', context) -
Can not use UserAdmin fildsets with cutom user model
I tried to customize Django User,which worked fine but I lost things like user_permissions. I don't have user permissions window from which I can give permissions like "can add Product,Can delete cart" etc. I tried this: from django.contrib.auth.admin import UserAdmin fieldsets = UserAdmin.fieldsets + ('Custom fields set', {'fields': ('email', 'staff')}), and UserAdmin.fieldsets += ('Custom fields set', {'fields': ('email', 'staff')}), but these didn't worked for me. If I try to add 'user_permissions' to fieldsets I get error " Unknown field 'user_permissions' specified'". Do I need to define user_permissions fields? class UserManager(BaseUserManager): def create_user(self,email,password=None,is_active=True,is_staff=False,is_admin=False): if not email: raise ValueError("Users must have email") if not password: raise ValueError("Users must have password") user_obj = self.model( email = self.normalize_email(email) ) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.set_password(password) #inbuild hashing user_obj.save(using = self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email,password=password,is_staff=True) return user def create_superuser(self,email,password=None): user = self.create_user(email,password=password,is_staff=True,is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(unique=True,max_length=255) # full_name= models.CharField(max_length=100) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) timestamp= models.DateTimeField(auto_now_add=True) # confirmed= models.BooleanField(default=False) #confirmed email? USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True This is how my admin … -
How to add request.user to manytomanyfield for team members in django?
I was trying to create a custom team model having a manytomanyfield for team members, now i have a form that allows users to create their own team(s), but i dont understand how i can add request.user to the members of the team. Below are the codes: models.py class Team(models.Model): name = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=1024) created_at = models.DateTimeField(auto_now_add=True) members = models.ManyToManyField(User, through='Member') def __str__(self): return f"Team: {self.name} created on {self.created_at}\nMember(s): {self.members}" class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE, blank=True) forms.py class TeamRegistrationForm(ModelForm): class Meta: model = Team fields = ["name", "description"] views.py @login_required(login_url="/login/") def teamregister(request): if request.method == "POST": form = TeamRegistrationForm(request.POST) if form.is_valid(): form.save() form.instance.members.add(request.user) # doesn't work :[ print(form.save()) messages.success(request, "Your team has been successfully registered!") return redirect("dashboard") else: form = TeamRegistrationForm() return render(request, "users/team.html", {"form": form}) I tried to use form.instance.members.add(request.user) to add the logged in user to the member of the team but it didn't work. Please help :[ -
Django Rest Framework: Overriding the PATCH or update()
I'm working up at a little IMS system Warehouse - it's products in the store App_form - it's the little form with order ChosenProduct - products which are chosen in order Models.py class Warehouse(models.Model): product_name = models.CharField(max_length=200, unique=True) amount = models.IntegerField() f_price = models.CharField(max_length=255, null=True) posted_user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.product_name class App_form(models.Model): deleted = models.BooleanField(default=False) name_customer = models.CharField(max_length=200) joined_date = models.DateField(verbose_name='joined date', auto_now_add=True) posted_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.surname class ChosenProduct(models.Model): product = models.ForeignKey(Warehouse, on_delete=models.CASCADE) quantity = models.IntegerField() app_form = models.ForeignKey(App_form, on_delete=models.CASCADE, related_name='chosen_products') def __str__(self): return self.product.product_name views.py class WarehouseList(generics.ListCreateAPIView): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer class WarehouseDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer class App_formList(generics.ListCreateAPIView): queryset = App_form.objects.all() serializer_class = App_formSerializer class App_formDetail(generics.RetrieveUpdateDestroyAPIView): queryset = App_form.objects.all() serializer_class = App_formSerializer serializers.py In App_formSerializer I rewrote the create method Where after chosing product from Warehouse the product quantity decreases class WarehouseSerializer(serializers.ModelSerializer): class Meta: model = Warehouse fields = ['__all__'] class ChosenProductSerializer(serializers.ModelSerializer): product_info = WarehouseSerializer(source='product', read_only=True) class Meta: model = ChosenProduct exclude = ('app_form',) class App_formSerializer(serializers.ModelSerializer): chosen_products = ChosenProductSerializer(many=True) @transaction.atomic def create(self, validated_data): chosen_products_data = validated_data.pop('chosen_products') app_form = App_form.objects.create(**validated_data) for chosen_product_data in chosen_products_data: chosen_product = ChosenProduct.objects.create(app_form=app_form, **chosen_product_data) product = chosen_product.product product.amount = product.amount - chosen_product.quantity product.save() … -
difference between django db router and custom model admin class
Recently I had a use case where i wanted to configure multiple DB instances in django. I wanted to configure django admin for the same as well. According to the documentation - https://docs.djangoproject.com/en/3.0/topics/db/multi-db/ there are 2 approach Using DB routers Create a custom admin class and modify 5 methods save_object etc - https://docs.djangoproject.com/en/3.0/topics/db/multi-db/#exposing-multiple-databases-in-django-s-admin-interface Does anybody know Why is the other approach listed here, I tried both and DB router is way easier. Is there any drawbacks of using DB router over custom Admin Class. Is there something one should be aware of when using either of the approaches Django masters please help -
404 (Not Found) in ajax post url
jQuery("#myform").submit(function (e) { e.preventDefault(); var formData = new FormData(this); jQuery.ajax({ type:'POST', url:'{% url 'myurl' %}', data: formData, cache:false, contentType: false, processData: false, success: function (data) { alert("Done"); } }); }); The code works perfectly fine in localhost but shows 404 url not found when hosted on server. -
NGINX and TRAEFIK staticfiles are not working with HTTPS in production
I'm developing a website for my association Here. It uses Django 3.0.7 and PostgreSQL. I follow this tutorial to make it works in good condition in development and in production. In development mode all is good, site is working perfectly, static files and media files are served by the Django built-in web server. I test the "vanilla" (coming from the tutorial) production on my local machine it works too. But the tutorial is not complete for me so after completing it, I decided to adapt the code to fit my needs. As I follow the tutorial I created a new docker-compose and a new dockerfile for production. But there are 2 differences between the tutorial and the site I want to set in production: I want to Use TREAFIK to route the traffic on different URL (appli.amis-simserhof.fr) because I will have other projects in the future on the same server with others subdomains.. I want to secure the website using HTTPS. So I use CERTBOT (let's encrypt) to generate certificates. I add this certificates to TREAFFIK in order to use HTTPS and it works. So I adapted the docker-compose file with my new stuff : version: '3.7' services: **traefik: image: …