Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Find /home/user in python as root user
When I want to get user directory as normal user in Python, then i can simply do this: os.path.expanduser('~') --> /home/user But, when I run this command as the root user, then it shows this result. Running as root: os.path.expanduser('~') --> root Is there any way to get /home/user directory as root user in python3? Thanks for your help. -
Why does my Django CreateView not recognise form_valid
I am using the django allauth module to create a user. In views,py I am subclassing CreateView, but I cannot get form_valid to work. It seems not to be being called (I have not imported HttpResponseRedirect but it doesn't complain class SignupPageView(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def form_valid(self, form): print('form_valid') return HttpResponseRedirect(self.get_success_url()) What am I doing wrong? -
Filter instantly a field in different form in django
In this simplified order, i want to choose the country on Order and instantly filter only cities of this country in OrderItem. Models class Company(models.Model): company = models.ForeignKey('User',on_delete=models.CASCADE) name = models.CharField(max_length=240) class Country(models.Model): company = models.ForeignKey('Company',on_delete=models.CASCADE) name = models.CharField(max_length=240) class City(models.Model): country = models.ForeignKey('Country', on_delete=models.CASCADE) name = models.DecimalField(max_digits=20, decimal_places=0) class Order(models.Model): company = models.ForeignKey('Company',on_delete=models.CASCADE) country = models.ForeignKey('Country',on_delete=models.CASCADE) class OrderItem(models.Model): order = models.ForeignKey('Order', on_delete=models.CASCADE) city = models.ForeignKey('City',on_delete=models.CASCADE) Forms : class OrderForm(ModelForm): class Meta: model = Order def __init__(self, company , *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['company'] = forms.ModelChoiceField(queryset=Company.objects.filter(name=company), initial = company) class Order1ItemForm(ModelForm): class Meta: model = Order1Item OrderItemFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=3) Views : class OrderCreate(CreateView): form_class = OrderForm model = Company template_name = "order_form.html" def get_success_url(self): return reverse_lazy('order_list') def get(self, request, *args, **kwargs): company_instance = request.user.company self.object = None form = OrderForm(company_instance) formset = OrderItemFormSet(form_kwargs={"company":company_instance}) return self.render_to_response( self.get_context_data(form=form,formset=formset)) def post(self, request, *args, **kwargs): self.object = None company_instance = request.user.company form = OrderForm(company_instance, self.request.POST) formset = OrderItemFormSet(self.request.POST, form_kwargs={"company": company_instance}) if (form.is_valid() or formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset)) In this simplified order, i want to choose the … -
Python server side code generating from OpenAPI and easy to update
I want to convert OpenAPI 3 to django or other server side codes. I know some converters such as swagger-django-generator. https://github.com/praekelt/swagger-django-generator But some solutions are only generate STUB server. The stub server is very nice but the STUB server is not assuming the modification. I seem swagger-django-generator doesn't assume the modification. I want to write OpenAPI documents and generating Typescript client codes and Python server codes. And I modify the logic based on its generating codes. Please tell me about the solution in my situation. -
Checking presence of element in a multiple field value in django template
Let us consider a database values as: name works_in band 1 band 2, band 3 band 2 band 3 band 1, band 2 now let us consider user_band as band 3 in template: {% if user_band in works_in %} Continue next process {% endif %} {% if name == user_band %} Same bands {% endif %} I don't know why conditions are not working if user_band is present in works_in message should be displayed -
How do you create a event model for a group and count hosted and attended event amount per groupmember with Django?
I recently learned how to django with a nice udemy tutorial. So I'm able to create groups and users can join and leave groups. Now I added a feature to the groups where a user can create/host a dinner and others of the group can join the dinner. on top of that I want to keep track of which groupmember hosted how many dinners and which groupmember joined how many dinners, however now when I call the amount of dinners attended by a user, I also get the total amount of dinners a user joined including those of other groups. Ideally a GroupDinner contains all group members with status='unknown' and a groupmember can than choose to attend or decline. So per Dinner there is overview of the groupmembers haven't reacted yet and those who have. So currently I have my models defined like so: Model.py class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') description_html = models.TextField(editable=False, default='', blank=True) members = models.ManyToManyField(User, through="GroupMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class Meta: ordering = ["name"] class GroupMember(models.Model): group = models.ForeignKey( … -
xhr.send() post request don't pass data
on the typescript side, i have this code that should send post request. note that getCookie function is copied from Django docs exactly like it is. const xhr = new XMLHttpRequest(); xhr.responseType = "json"; xhr.open("POST", `http://localhost:8000/create/`); xhr.setRequestHeader("Content-Type", "application/json"); const coockie = getCookie("csrftoken"); if (coockie) { xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-with", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", coockie); } xhr.onload = function () { callback(xhr.response, xhr.status); }; xhr.onerror = function (e) { console.log(e); callback({ message: "The request was an error" }, 400); }; xhr.send('{"content":"new text"}'); in views.py @api_view(["POST"]) @permission_classes([IsAuthenticated]) def post_create_view(request, *args, **kwargs): print(request.data) serializer = CreateTweeSerializers(data={request.data}) # raise_exception= if form.error reutnr error and status400 if serializer.is_valid(raise_exception=True): serializer.save(user=request.user) return Response(serializer.data, status=201) return Response({}, status=400) `print(request.data)` return `<QueryDict: {}>` -
How to send error message to the Django generic DeleteView Confirmation Page using JsonResponse
I am trying to use Django generic DeleteView using the confirmation page. The setup is working as intended. Later the business logic was changed to prevent deletion if there are child instances assigned to the object being deleted, using on_delete=models.PROTECT in the model. And the DeleteView has been modified to the following: class TerritoryDeleteView(LoginRequiredMixin, DeleteView): template_name = ".../trty_delete.html" model = Territory success_url = reverse_lazy('territories_list') # THE FOLLOWING MODIFICATION DONE: def delete(self, request, *args, **kwargs): self.object = self.get_object() try: self.object.delete() return HttpResponseRedirect(success_url) except ProtectedError: error_message = "This object can't be deleted, as an Outlet is already assigned to the Territory..." return JsonResponse(error_message, safe=False) The above (modified) view works fine. However, in case it encounters the ProtectedError, the error_message is shown in a blank browser page. How could I display the error_message in the confirmation page (template) itself? -
Issue with showing all videos from DB (QuerySet object has no attribute)
I am uploading a video file to my webpage, which I can also play. However, the moment I want to show all the video files on different page and play them, I get QuerySet object has no attribute I can't figure out what I am doing wrong. Models.py: models.py class VideoModel(models.Model): name = models.CharField(max_length=500) videofile = models.FileField(upload_to='videos/', null=True, verbose_name="") def __str__(self): return self.name + ": " + str(self.videofile) Views.py: views.py class ShowVideosView(View): def get(self, request): form = VideoForm() lastvideo = VideoModel.objects.last() videofile = lastvideo.videofile return render(request, 'videos.html', {'videofile': videofile, 'form': form}) def post(self, request): form = VideoForm(request.POST or None, request.FILES or None) lastvideo = VideoModel.objects.last() videofile = lastvideo.videofile form = VideoForm(request.POST or None, request.FILES or None) if form.is_valid(): name = form.cleaned_data['name'] videofile = form.cleaned_data['videofile'] new_video = VideoModel(name=name, videofile=videofile) new_video.save() context = {'videofile': videofile, 'form': form} return render(request, 'videos.html', context) class ListOfVideosView(View): def get(self, request): all_videos = VideoModel.objects.all() videofile = all_videos.videofile context = {'all_videos': all_videos, 'videofile': videofile} return render(request, 'all_videos.html', context) all_videos.html: all_videos.html {% for video in all_videos %} <video width='400' controls> <source src='{{MEDIA_URL}}{{videofile}}' type='video/mp4' Your browser does not support the video tag. </video> {% endfor %} -
FilePathField adds backslash to the end of path django
This is my model : from django.db import models from project.settings import BASE_DIR class Restaurant(models.Model): logo_img = models.FilePathField(path=BASE_DIR, recursive=True, null=True) when I send a request, the response is as follows : {'logo_img': [ErrorDetail(string='\"/media/tmp/72a68b59ad0047edb4cd275725bff229.jpg\" is not a valid path choice.', code='invalid_choice')]} This is my request body : { "logo_img" : "/media/tmp/72a68b59ad0047edb4cd275725bff229.jpg" } This file path is correct & it exists on server. Why it adds backslash to the end of path? -
Помогите придумать тему для дипломной работы
Я на 4 курсе и паралельно работаю веб. девом. Мой стек: Python, Django, Django REST, FastApi, Flask, JavaScript, XML / JSON, SQL, MySQL, PostgreSQL. Помогите придумать тему для курсача, это должен быть или веб сайтик или телеграм бот с веб. админкой. А то у меня уже ноль идей =( -
NameError: Undefined
I am working on a django project where I define a loop variable in an html file but it is not recognizing the variable. Please look at the code and tell me if there is anything wrong. % for category in categories: <div class="mobile-nav-item dropdown-item dropdown-nav-item toggle-category-sub-dropdown" role="button" aria-label=${_("Options Menu")} aria-expanded="false" tabindex="0" aria-controls="${category.replace(' ','_')}"> <a role="menuitem">${_(category)}</a> <div style="left:100%;top: -1px !important;width: max-content" class="dropdown-category-sub-menu hidden" aria-label=${_("More Options")} role="menu" id="${category.replace(' ','_')}" tabindex="-1"> % for subject in subjectLists: %if category == subject['category']: <div class="mobile-nav-item dropdown-sub-item dropdown-nav-item"><a href="${reverse('about_course', args=[text_type(subject['id'])])}" role="menuitem">${_(subject['name'])}</a></div> %endif % endfor </div> </div> % endfor -
html form elements in for loop with a single submit button in django
if put a submit button below form closing tag it shows the multiple buttons all over the table but what i want it in one submit DATA {% block content %} id studentname Hallticket Number ExamType Medium Barcode OldBarcode Attendance {% for i in students %} {{ i.id }} {{ i.sname }} {{ i.htno }} {{ i.ExamType }} {{ i.medium }} {{ i.Barcode }} {{ i.OldBarcode }} Choose... Present Absent MallPractice {% endfor %} {% endblock %} -
Django Filters not querying data
I'm trying to filter API responses through a web search. After typing a search query it doesn't filter the result. I'm also using pagination. How to solve this do I need to make changes in my filter or View. search query http://127.0.0.1:8000/course-api/subjectlist/?search="ICT"/ after giving this search query still it returns all of the elements through the response. Subject model class Subject(models.Model): def upload_location(instance, filename): return "subject_images/%s/%s" % (instance.subject_name, filename) subject_name = models.CharField(max_length=200, null=True) subject_cover = models.ImageField(null=True, blank=True, upload_to=upload_location,default="subject_images/default.png") description = models.CharField(max_length=500, null=True, blank=True) author = models.ForeignKey(TeacherProfile,on_delete=models.CASCADE,null=True,default=None) subject_type = models.CharField(max_length=100, null=True, blank=True) class_type = models.CharField(max_length=10, null=True, blank=True) short_description = models.CharField(max_length=300,blank=True,null=True) created_at = models.DateTimeField(default=now) filters.py import django_filters from ..models import Subject class SubjectFilter(django_filters.FilterSet): class Meta: model = Subject fields = ['subject_name'] Views.py @api_view(['GET']) def SubjectList(request): paginator = PageNumberPagination() paginator.page_size=5 subjects =SubjectFilter ( request.GET, queryset= Subject.objects.all()) result_page = paginator.paginate_queryset(subjects.queryset,request) serializer = SubjectViewSerializer(result_page,many=True) return paginator.get_paginated_response(serializer.data) -
Checking if an object name exists in UpdateView is giving an error if i want to use the same name
I'm looking for a trick to use UpdateView and update a name of an object, but i want to raise a formerror if one of the other object has the same name. My problem is if i want to Update only f.e point of my object but at the same time I want to use the same name. For example: Object: name = 123 , point = 1 OtherObj: name = 124 , point = 1 If i want to update name to '124' raise a form error, and that's correct. But if i want to update only point, so i want to use the same name, raise a form error. I wrote in my forms.py, this: class CardUpdateForm(forms.ModelForm): card_title = forms.CharField(label="Titolo Card", widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField(label="Descrizione card", widget=forms.TextInput(attrs={'class': 'form-control'})) # column_id = forms.CharField(label="Nome colonna", widget=forms.TextInput(attrs={'class': 'form-control'})) expiration_date = forms.DateField(label="Data di scadenza", widget=forms.DateInput(attrs={'class': 'form-control'})) class Meta: model = Card fields = [ 'card_title', 'description', 'expiration_date', 'column', 'story_points', ] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(CardUpdateForm, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): card_title = self.cleaned_data.get('card_title') description = self.cleaned_data.get('description') card_title_qs = Card.object.filter(card_title=card_title) if card_title_qs.exists : raise forms.ValidationError('Nome della Card già utilizzato. Per favore inseriscine un altro.') -
Accessing input field values from same form into different apps in django
I am a django framework and Mpesa daraja api beginner. I want to make the amount and phone number to be dynamic in that the values of the same should be obtained from input fields... please help -
SMTPAuthenticationError on Heroku
I am trying to request a reset password from a system deployed on heroku but i get this error. SMTPAuthenticationError at /password-reset/ (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 i1cE5v2I-3UUFLl6jQMnBfbcvZuRiGo_q9k1T5h2XgMGxtKYIJ0sIPE9Jr6zW1X78xQM3\n5.7.14 Py7mrOXSPkPG01upxjbZRi68aLrKIbvG_4uHrli9l7ZVmFnr8CxRNb9JUDGVcm8M>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 k188sm1479373qkd.98 - gsmtp') I have set all these settings and they seem to be okay but i still get the same error. Kindly help EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
Looking for examples in django tests for a website
For a big scale website..i am looking an example on how you can create tests in django for different type of users admin,guest,client,etc.Does anyone have a link or a youtube video to suggest? I am looking for sth more complicated than the simple test examples in django website. Any link would be helpful! -
Can I run redis servers on a windows server?
I have designed an app in django using django channels with redis servers for websocket communication, but I have to host it on a windows server. Can I and how do I run redis servers for that application. Is there any alternative to this? -
Django makemessages on third-party iframe?
I'm using a third-party library, and I'd like to translate the text on some of the iframes provided by the library on my website. I can't use makemessages to generate the correct phrases in the .po files, as the iframe code is not part of my codebase. I could manually add the translations to the .po files but then the next time I run makemessages these phrases will be removed because i18n will not find them within the codebase. Is there a way to use i18n on the words of a third-party iframe without the translations being removed every time makemessages is run? -
django.urls.exceptions.NoReverseMatch: Reverse for 'core_user_changelist'
I get this error when I run docker-compose run app sh -c "python manage.py test && flake8" git hub code: https://github.com/OsamaDaghestani/recipe-app-api.git ERROR: test_create_user_page (core.tests.test_admin.AdminSiteTests) Test that the create user page works Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 39, in test_create_user_page url = reverse('admin:core_user_add') File "/usr/local/lib/python3.7/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'core_user_add' not found. 'core_user_add' is not a valid view function or pattern name. ====================================================================== ERROR: test_user_change_page (core.tests.test_admin.AdminSiteTests) Test that the user edit page works ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 32, in test_user_change_page url = reverse('admin:core_user_change', args=[self.user.id]) File "/usr/local/lib/python3.7/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'core_user_change' not found. 'core_user_change' is not a valid view function or pattern name. ====================================================================== ERROR: test_users_listed (core.tests.test_admin.AdminSiteTests) Test that users are listed on user page ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 24, in test_users_listed url = reverse('admin:core_user_changelist') File "/usr/local/lib/python3.7/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'core_user_changelist' not found. 'core_user_changelist' is not a valid view … -
Error when trying to serialize multiple followers:Got AttributeError when attempting to get a value for field `email` on serializer `UserSerializer`
I am trying to show the followers in UserSerializer,as a user instance.Almost the same method i used in article model works,but in user model it gives me problem.Below i can explain it better with my codes: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') profile = models.ForeignKey(User,on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now=True) Serializers.py class UserSerializer(serializers.ModelSerializer): followers_set = serializers.SerializerMethodField() def get_followers_set(self, user): return UserSerializer(user.followers.all(), source='followers', required=False,read_only=True,many=True).data class Meta: model = User fields = ('id','email','username','followers_set') class ArticleViewSerializer(serializers.ModelSerializer): author = UserSerializer(required=False,read_only=True) class Meta: model = Article fields = ('id','author') def create(self, validated_data): return Article.objects.create(**validated_data) class FollowSerializer(serializers.ModelSerializer): author = UserSerializer(required=False) profile = UserSerializer(required=False) class Meta: model = FollowUserModel fields = ("author","profile") Now the author works as intended,it gives the full user instance.But in followers_set i get this error: Got AttributeError when attempting to get a value for field `email` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `FollowUserModel` instance. Original exception text was: 'FollowUserModel' object has no attribute 'email'. I don't get it,like i defined everything … -
Save a unique order id for each company in django
I would like to have a unique id_order per company, and if already exist, i cannot save the order or form is not valid. In my example, each company save orders, Company A can save id_order 1 id_order 2 id_order 3 ... Company B can save id_order 10 id_order 20 id_order 30... what i want now is that company A cannot save two times id_order 3 or company B cannot save two times id_order 20. class Company(models.Model): name = models.CharField(max_length=240) last_order = models.DecimalField(max_digits=20, decimal_places=0) class Order(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) id_order = models.DecimalField(max_digits=20, decimal_places=0) def save(self, *args, **kwargs): created = not self.pk super().save(*args, **kwargs) if created: Company.objects \ .filter(pk=self.company_id) \ .update(last_order=self.id_order) Forms: class OrderForm(ModelForm): class Meta: model = Order def __init__(self, company , *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['company'] = forms.ModelChoiceField(queryset=Company.objects.filter(name=company), initial = company) try: code = company.last_order + 1 self.fields["id_order"].initial = code except Exception as e: print(e) -
Django - how to obtain the latest related model in an efficent way I can iterate on the template?
Let's say I have two related models, one of the two with a datetime field. (Author & Book with a pub_date). I want to display a list of authors and the latest book each of them has written. I made a method on the Author model: def get_latest_book(self): return self.books.all().latest('pub_date') That is working, but it's very inefficent when it comes to be rendered on a template: views.py: class AuthorListView(ListView): model = Author template_name = 'author_list.html' def get_queryset(self): return self.model.objects.filter(owner=self.request.user).order_by('name').prefetch_related('books') author_list.html: ... {% for author in author_list %} Name: {{author.name}} - Latest publication: {{author.get_latest_book}} {% endfor %} ... This is generating a large number of queries like: SELECT ••• FROM `app_book` WHERE `app_book`.`author_id` = 374 ORDER BY `app_book`.`pub_date` DESC LIMIT 1 36 similar queries. for each Author I have in the database! This results in huge loading times for the book list. How can I print on the template a list of Authors with their latest book in an efficient way? -
mathematical calculation in django
i am new to django. i am working on a project e-shop, seller input the item and have right to offer discount as well through database. models field include discount_offered_percentage i want to print MRP, Discount percentage, final price after discount. how can i calculate the final price? I don't want to store the value in database but want to calculate and print it on the html page directly. as I am printing the available items in database to html page. how can I fetch the value of discount_offered_percentage column for each iteration on view.py? thanks in advance