Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: can't subtract offset-naive and offset-aware datetimes
i have a 'free_trial' function in my app that allows users who have an account not older than 7 days to try my app. user model class CustomUser(AbstractUser): def free_trial(self): if (self.date_joined - datetime.now()) < timedelta(days=7): return True templates {% if user.free_trial %} #Access Features {% endif %} but i'm getting this error on template can't subtract offset-naive and offset-aware datetimes -
onchange event being triggered when form submits
I would like the user to be able to record an action that they have carried out. I grouped the actions by category and then using two select menus and JS the user is only showed the actions from the category that they have selected. There is also a quantity input that is generated depending on which action is selected. My issue is that when I submit the form, I get the error: Uncaught TypeError: Cannot set property 'onchange' of null The select box and the functionality implemented by the JS work until the form is submitted. index.js document.addEventListener("DOMContentLoaded", () => { // First select let cat_select = document.getElementById("id_post_cat"); cat_select.onchange = () => handleCatChange(cat_select.value); // Second select let desc_select = document.getElementById("id_post_action"); desc_select.onchange = () => handleDescChange(desc_select.value); }); const handleCatChange = (cat) => { let quantity_div = document.getElementById("quantity_div"); quantity_div.innerHTML = ""; // Fetching the actions in the category selected and populating second select fetch(`/action/${cat}`) .then((response) => response.json()) .then((data) => { let desc_select = document.getElementById("id_post_action"); let optionHTML = "<option>---------</option>"; data.actions.forEach((action) => { optionHTML += '<option value"' + action.id + '">' + action.desc + "</option>"; }); desc_select.innerHTML = optionHTML; }) .catch((err) => console.log(err)); }; const handleDescChange = (desc) => { let quantity_div = … -
When is PostgreSQL shared lock released
I am using Django transaction.atomic with a PostgreSQL DB to do a query and then update some data. Like so: with transaction.atomic(): res = my_model.objects.filter(some_filter) DO WORK res.update() If I understand correctly the filter query is creating a shared lock in the PostgreSQL DB. When is that lock released? Directly after its execution or when the entire transaction completes? -
Get available rooms in selected dates django
I am creating a project similar to a house booking system, with a few particularities (you publish the house but you can rent the rooms individually, and you can set when you are on holidays and the house is not available) in Django (rest-framework, so only API for now). The house model can be simplified to: class House(models.Model): title = models.CharField(max_length=127) n_rooms = models.PositiveSmallIntegerField() there is a calendar to save when the house is not available: class Unavailability(models.Model): house = models.ForeignKey(House, on_delete=models.CASCADE, related_name="house_unavailability") unavailable_rooms = models.SmallIntegerField() from_date = models.DateField() to_date = models.DateField() and a model to save when there have been bookings: class Booking(models.Model): house = models.ForeignKey(House, on_delete=models.CASCADE, related_name='booking') booker = models.ForeignKey(UserProfile, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() n_rooms = models.PositiveSmallIntegerField(default=1) rent = models.DecimalField(decimal_places=2, max_digits=8) I am now trying to create an API to search the houses that have at least one room available in the selected dates (not on holidays and not booked). I have seen some similar cases without the particularities I have and using other languages but none using Django (I am using MySQL so I could fall back to SQL if a clean solution with Django does not arise) -
How to specify correctly wsgi for Heroku deploy?
I have following project structure In Procfile i difine web as web: gunicorn george_paintings.wsgi When i deploy project on Heroku i see that Heroku identified my Procfile Starting process with command `gunicorn george_paintings.wsgi` But when i got an error ModuleNotFoundError: No module named 'george_paintings' ` How to properly set up wsgi in Proclife in context of my project structure? -
Django Deprecated error in Django-Admin. Can anyone help me out with it?
When I am using django-admin startproject api then it is opening file named django-admin.py and the code looks like this : #!C:\Users\Administrator\Desktop\api\venv\Scripts\python.exe When the django-admin.py deprecation ends, remove this script. import warnings from django.core import management try: from django.utils.deprecation import RemovedInDjango40Warning except ImportError: raise ImportError( 'django-admin.py was deprecated in Django 3.1 and removed in Django ' '4.0. Please manually remove this script from your virtual environment ' 'and use django-admin instead.' ) if name == "main": warnings.warn( 'django-admin.py is deprecated in favor of django-admin.', RemovedInDjango40Warning, ) management.execute_from_command_line() I am using virtual environment. I am not getting how to get rid out of it. -
I cant join two models on Django rest api and get a specific output
Hello guys I am new in Django REST API. I want your help. I am trying to join my two models : User and blogs to get specific api output like this: { "blog_id": 1, "title": "first blog", "description": "hola", "image": "/images/phone.jpg", "create_at": "2021-04-08T14:24:51.122272Z", "update_at": "2021-04-08T14:37:00.287746Z", "user": 1, "user_name": "superuser", "first_name": "Dannis", "email": "superuser@test.com" } Here is the models.py class Blog(models.Model): blog_id = models.AutoField(primary_key=True, editable=False) title = models.CharField(max_length=128,null=False,blank=False) description = models.TextField(null=True,blank=True) image=models.ImageField(null=True,blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True, editable=False) update_at = models.DateTimeField(auto_now=True,editable=False) def __str__(self): return f'{self.user.username} {self.title} {self.create_at} {self.update_at}' class UserActive(models.Model): user_active_id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False) last_active = models.DateTimeField(auto_now_add=True, editable=False) Here is the views.py @api_view(['GET']) def get_blogs(request): blogs = Blog.objects.all() serializer = BlogSerializers(blogs, many=True) return Response(serializer.data) @api_view(['GET']) def get_users(request): user = User.objects.all() serializer = UserSerializer(user, many=True) return Response(serializer.data) here is the serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'first_name', 'is_staff', ] class BlogSerializers(serializers.ModelSerializer): class Meta: model = Blog fields = '__all__' Please Help me out. I will be so grateful -
Django m2m field on signals getting overridden
I am adding a m2m field on signals, but it gets overridden after the signal call. But when using django admin it does not get overridden. Here's the signal.py snippet @receiver(post_save, sender=Category) @on_transaction_commit def update_properties(sender, instance: Category, created, *args, **kwargs): print("Adding tag 5: Asdf") instance.tags.add(5) on_transation_commit decorator def on_transaction_commit(func): def wrapper(*args, **kwargs): transaction.on_commit(lambda: func(*args, **kwargs)) return wrapper views.py class CategoryUpdateView(PermissionRequiredMixin, TagFormMixin, UpdateView): model = Category form_class = CategoryForm template_name = '.....' tag_class = Tag permission_classes = [...] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) .... return context TagFormMixin class TagFormMixin: tag_class = None def get_tag_class(self): return self.tag_class def get_form_kwargs(self): ... creates tags if does not exist ... As much I can understand, after the post_signal is done executing, somewhere in View/Form tags are overriden -
Place image on page that users can refer too using "src" in an "img" tag (Django)
How do I place an image that people can refer to i.e via a link just like this ? If I just place a normal <img src="{% static 'media/my_img.png' %}"> in my template and inspect the site, the source is static/media/my_image.png. I want to be able to refer to specific images from my webpage in an email using html like<img src="my_page.com/logos/my_image.png> -
Django admin dependent drop down (no models)
models.py class Document(models.Model): word_type = models.CharField(max_length=255, choices=[('noun', 'noun'), ('verb', 'verb'), ('adjektive', 'adjektive')], default='noun') word = models.CharField(max_length=255) article = models.CharField(max_length=255, choices=[('the','the), ('-','-')], default='') forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['word_type', 'word', 'article'] def __init__(self, *args, **kwargs): super(DocumentForm, self).__init__(*args, **kwargs) if self.instance.word_type == "noun": self.fields['article'].choices = [('the', 'the')] else: self.fields['article'].choices = [('-', '-')] I have a model 'document'. When creating a document object in django admin, I want the article dropdown (actual language has several articles) only to show up when 'noun' is selected as word type. Currently I got it working to update the choices to '-' if it's not a noun, but the dropdown only updates with init. So I'm looking for a way to update the article dropdown automatically when word type changes. Maybe there is another (better) way of doing it, would be great if there was a solution to make article dropdown completely disappear when 'verb' or 'adjective' is selected as word type. I'm fairly new to django, couldn't find a solution for this since most tutorials assume article and word_type are dependent models, which is not the case for me. -
Django Oscar, how to make product price dynamic, by allowing users to enter their own value
Im using django-oscar as my e-commerce library, What I want to do is to give users an input field they can use to enter the amount they want to pay for a product When a user presses the add to cart, button they are presented with a Price Input Field How can I archieve this? -
Uploading Django website to Godaddy using Cpanel
I build a website using django(+html,css,js,bootstrap). I check my site on wampserver and its complete. Now i want to upload it to my domain on godaddy using cpanel but i have no idea how to do it. Can anyone explain it to step by step. -
django form dropdown return key instead of value
I have populated dropdown list by values as pk and key as names in my django form. <select name='user_name_fk' id='id_user_name_fk'> <option value='1'>name1</option> <option value='2'>name2</option> <option value='3'>name2</option>.... </select> When i post a form, i get keys(names) asa output instead of values(pk). when i print(form.cleaned_data['user_name_fk']) output is 'name'. As i get text as a output as "text", i cant able to update foriegn key field(error : Cannot assign "'1'": "TABLENAME.user_name_fk" must be a "TABLENAME" instance). i do not know where i do the errors. i would like to get oupt as form.cleaned_data['user_name_fk']=pk. Can anybody help me to find a solution pls? Thanx in advance forms.py class MyTable2Form(forms.ModelForm): user_name_fk= forms.ChoiceField( label='Names', required=True, choices=MyTable1.objects.all().values_list('pk','user_name'), widget=forms.Select( attrs={'class':'form-select'} ) ) class Meta: model = MyTable2 fields = ['user_name_fk'] class MyTable3Form(forms.ModelForm): user_name_fk= forms.ModelChoiceField( label='Names', required=True, empty_label='-- Names --', queryset=MyTable1.objects.only('pk','user_name'), widget=forms.Select( attrs={'class':'form-select'} ) ) class Meta: model = MyTable2 fields = ['user_name_fk'] models.py class MyTable1(models.Model): table1_id=models.AutoField(primary_key = True) user_name= models.CharField(max_length=100) def __str__(self): return (self.user_name) class MyTable2(models.Model): table2_id=models.AutoField(primary_key = True) user_name_fk= models.ForeignKey(MyTable1, blank=True, null=True, on_delete=models.CASCADE, default=None) def __str__(self): return (self.user_name_fk) views.py class Page2view(TemplateView): template_name='logout.html' def get_context_data(self, *args, **kwargs): context=super().get_context_data(**kwargs) context={'form':MyTable2Form()} return context def post(self,request): form=MyTable2Form(request.POST) if form.is_valid(): reg=form.save(commit=False) #print(form.cleaned_data['user_name_fk']) reg.user_name_fk=MyTable1.objects.get(table1_id=form.cleaned_data['user_name_fk']) reg.save() messages.success(request,'Form is saved successfully') return HttpResponseRedirect('/page2/') class Page3view(TemplateView): … -
how to change email for user and confirm it using usercreationform - django
how to change email for user and confirm it using usercreationform , i want allow user to change email in his profile and when he enter new email he must activate email to save it in his profile forms.py : # Profile Form class EmailChangeForm(forms.ModelForm): email = forms.EmailField(required=True,label='Email',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6','placeholder':' Enter Your New E-mail '}) ) class Meta: model = User fields = [ 'email', ] def clean_email(self): email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).count(): raise forms.ValidationError('Email is already in use, please check the email or use another email') return email views.py : # Edit Profile View class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): return self.request.user urls.py : from django.urls import path from blog_app.views import SignUpView, ProfileView, ActivateAccount,EmailChange urlpatterns = [ path('profile/change-email/me/', EmailChange.as_view(), name='emailchange'), path('activate/<uidb64>/<token>/', ActivateAccount.as_view(), name='activate'), ] change email html page : <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="fadeIn fourth" style="background-color:#7952b3" value=" change "> </form> -
When does the save method in a DJango model not run?
I have a Django model that overrides the save method and looks like this: class Log(models.Model): agent = models.ForeignKey(Agent, on_delete=models.CASCADE) calls_logged = models.IntegerField(default=0) texts_logged = models.IntegerField(default=0) completed_logs = models.BooleanField(default=False, db_index=True) def save(self, *args, **kwargs): if self.calls_logged >= 30 and self.texts_logged >= 50: self.completed_logs = True super().save(*args, **kwargs) What's supposed to happen is when the Agent reaches 30 calls and 50 texts, the save() method is supposed to change the completed_logs field to True. But when I recently checked my DB, an agent had reached over 30 calls and over 50 texts but completed_logs wasn't marked as completed. So, my question is: is there ever a time that Django will not call the save() method on a model? Is there a better way to do this? -
Django [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'MYSCHEMA.MyUnmanagedModel'
I'm running into this issue: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'MYSCHEMA.MyUnmanagedModel'. It's an unmanaged model, so I understand that I have to create the table manually ahead of time. Here is the model: class MyUnmanagedModel(CampusModel): id = models.IntegerField(db_column="ID", primary_key=True) end_year = models.IntegerField(db_column="endyear") grade = models.CharField(db_column="grade", max_length=2) enrollments = models.IntegerField(db_column="enrollments") class Meta(object): managed = False db_table = "[MYSCHEMA].[MyModelTable]" I have ensured that my docker database contains the appropriate 'MYSCHEMA' with the table 'MyModelTable' and that it's built out appropriately with respect to the model (all the appropriate columns). I'm using factory-boy to create the object: here is my Factory: class MyUnmanagedModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyUnmanagedModel database = "secondary_database" id = factory.Sequence(lambda n: n) end_year = 2021 grade = 1 enrollments = 1200 I use multiple databases in my project, the 'secondary_database' is the one that holds the database with the appropriate schema. DATABASES = { "default": { "ENGINE": "mssql", "NAME": os.environ.get("default_NAME"), "HOST": os.environ.get("default_HOST"), "USER": os.environ.get("default_USER"), "PASSWORD": os.environ.get("default_PASSWORD"), "PORT": os.environ.get("default_PORT"), "OPTIONS": { "host_is_server": True, "driver": os.environ.get("ODBC_DRIVER"), }, }, "secondary_database": { "ENGINE": "mssql", "NAME": os.environ.get("secondary_NAME"), "HOST": os.environ.get("secondary_HOST"), "USER": os.environ.get("secondary_USER"), "PASSWORD": os.environ.get("secondary_PASSWORD"), "PORT": os.environ.get("secondary_PORT"), "OPTIONS": { "host_is_server": True, "driver": os.environ.get("ODBC_DRIVER"), }, }, Using DataGrip or Azure … -
Django fetch manytomany values as list
class Groups: name = models.CharField(max_length=100) class User: firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) group = models.ManyToManyField(Groups) i need user details with groupname as list not as separate records. User.objects.values('firstname','lastname', 'group__name') While i'm querying like above, i'm getting like this <QuerySet [{'firstname': 'Market', 'lastname': 'Cloud', 'group__name': 'Group 5'}, {'firstname': 'Market', 'lastname': 'Cloud', 'group__name': 'Group 4'}]> but i want like this <QuerySet [{'firstname': 'Market', 'lastname': 'Cloud', 'group__name': ['Group 5', 'Group 4']}]> -
How to query data from real Database created by django-pytest db fixture
I write db-related tests for my django project using pytest. I use db fixture for creation of records in the database. Test works fine but how to select these records from real Postgres db. When I try to select these records via PgAdmin I get empty list. Can you please clarify how db fixture works and where does it store records? -
How to export all models in the same file with django-import-export?
I want to use django-import-export to manage export in my project. But, I can figure out how to export all models in the same file with django-import-export Can find in the doc a way to do that. I am only able to export model by model... -
Why Role Rights Are Not Assigned to a User?
Why when I create a user and assign a role to him the role rights are not assigned? self.request.user.get_user_permissions() returns empty tuple -
Cannot scroll through video using scrollmagic in django
I'm building a web app where video plays along the scroll, it works completely fine but when I incorporated it in django the video dosen't play while scrolling anyore. I have used scrollmagic plugin and jquery in javascript. And i have included static_root in setting.py and I have also tried accessing the video from media file from django but still it didn't work. HTML file : <main class="content"> <div class="container"> <video src="{% static 'images/My Video.mp4' %}"></video> </div> </main> I'm still new to javascript I tried this by watching youtube tutorials Javascript file : var controller = new ScrollMagic.Controller(); const video = document.querySelector('video'); var scene2 = new ScrollMagic.Scene({ duration: 9000, triggerElement: "main", triggerHook: 0 }) .addIndicators() .setPin('main') .addTo(controller); let scrollpos = 0; let accelamount = 0.1; let delay = 0; scene.on("update", e => { scrollpos = e.scrollPos / 700; }); setInterval( () => { delay += (scrollpos - delay) * accelamount; // console.log(scrollpos, delay); video.currentTime = delay; }, 20); settings.py # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] I know it's not right to access video file from static, but even when I fetch video by creating 'media_root' and use 'media_url' it didn't work. … -
Filterset field not working for multiple object
filterset field not working for multiple leave of a single employee leave details, how may i solve this? class LeaveApplicationGetUpdateView(RetrieveUpdateAPIView): serializer_class = LeaveApplicationSerializers queryset = LeaveApplication.objects.filter() permission_classes = (IsAuthenticated, IsSuperUser) filter_backends = [filters.OrderingFilter, DjangoFilterBackend] filterset_fields = ['type', 'from_date', 'to_date'] def get(self, request, *args, **kwargs): contact_inf = LeaveApplication.objects.filter(employee__code=self.kwargs.get('code')) # will be refactor if contact_inf: return Response({ 'success': True, 'message': 'Successfully', 'data': LeaveApplicationSerializers(contact_inf, many=True).data }, status=200) else: return Response({ 'success': False, 'message': 'Not Found' }, status=200) -
django-filter-2.0 + django 2.2 + Strictness Behaviour
I have the django 1.11 code as below and we are using django-filter==1.0 library for filters. and below is the code according to django 1.11 Models: class BaseItem(models.Model): CHOICES = ( (STATUS_ACTIVE, 'Active'), (STATUS_INACTIVE, 'Inactive'), ) class Item(BaseItem): name = models.CharField(null=True) symbol = models.CharField(null=False) Filter class ItemFilterSet(django_filters.FilterSet): status = django_filters.MultipleChoiceFilter(choices=Item.CHOICES, widget=CSVWidget) class Meta: model = Item fields = ['symbol'] strict = STRICTNESS.RAISE_VALIDATION_ERROR Viewset class ItemViewSet(ModelViewSet): http_method_names = ['get', 'post'] serializer_class = ItemSerializer queryset = Item.objects.all() filterset_class = ItemFilterSet def filter_queryset(self, queryset): try: return super().filter_queryset(queryset) except ValidationError as e: if 'symbol' in e.error_dict: raise exceptions.ValidationError(detail=e.message_dict) raise e But in Django 2.2 version we have used django-filter==2.0 library, but in this library, this strictness has been moved to view as per below link. https://django-filter.readthedocs.io/en/master/guide/migration.html#filterset-strictness-handling-moved-to-view-788 django-filter other github link https://github.com/stephenfin/django-filter/commit/552c35ac45b965c2d68e97f9cfdeef940f17d6ea So my question is, according to django-filter 2.0 and django 2.2 , in the view, I dont need to handle strictness according to second link ? it will be by default will have strictness behaviour(STRICTNESS.RAISE_VALIDATION_ERROR) in view ? or should i write some code for this in view ? -
How to check_object_permissions on @api_view functions?
I defined a view function with the @api_view decorator. Now I would like to test object-level permissions in this object. I know there is a check_object_permissions that would let me check the permissions I defined on my view, but I don't know how to call it. The documentation gives examples for classes, not functions. @api_view(["GET"]) @permission_classes([IsAuthenticated & IsOwnerOfItem]) def query_something_related_to_items(request, item_id): item = get_object_or_404(Item, id=item_id) # I want to test IsOwnerOfItem here, # I guess I need to call something like: # "self".check_object_permissions(request, item) # custom code here return something class IsOwnerOfItem(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.owner == request.user the documentation says: If you're writing your own views and want to enforce object level permissions, or if you override the get_object method on a generic view, then you'll need to explicitly call the .check_object_permissions(request, obj) method on the view at the point at which you've retrieved the object. But how do you call this in an view function? -
How to deploy Django apps independently using Docker?
We have a large Django project that is deployed weekly using Docker container, Nginx and Kubernetes cluster. This project has some smaller apps that often receive changes and fixes mid-week that would be nice to have in production immediately but they need to wait for the project deployment on the following week. Knowing that these apps in Django are not standalone and depend on other files/folder/settings, I would like to find a way to have a separate deployment cycle for these apps so the changes could be reflected more often than once a week but without affecting the whole project. I was thinking about using different Docker containers but I am not proficient in it yet to know if this is the best solution. I still find it a bit hard to visualize how to deploy just some "folders" of the project and have everything working together. What would be the best approach here?