Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django get_full_name in admin
I know there are lots of similar questions but I couldn't find an answer. I'm trying to access to the get_full_name() method in the admin of my project. I extended the Django User model with a Bio class, connected through a "user" OneToOneField and updated via signals as exposed here. The main class of my models.py, ObjetArchi, is also related to the User model through the "auteur" ForeignKey field. I'd like to show the users full name's, as allowed by the get_full_name() method, in every part of the admin: on list_display, list_filter and fieldsets, as well as in the ObjetArchi form. How and where should I write this method? models.py: class Bio(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True ) coordonnees = models.CharField( max_length=300, verbose_name='Coordonnées institutionnelles de l\'auteur', help_text='300 caractères max.', blank=True ) site_web = models.URLField( verbose_name='Site web personnel', blank=True ) biographie = models.TextField( blank=True, null=True, ) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Bio.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.bio.save() (...) class ObjetArchi(gis_models.Model): id = models.AutoField( primary_key=True, verbose_name= 'Identifiant' ) titre = models.CharField( max_length=100, verbose_name='Titre', blank=True, null=True ) date = models.DateField( default=timezone.now, verbose_name='Date de publication' ) auteur = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='objets_archi_user', verbose_name='Auteur.e', blank=True, null=True ) resume … -
DRF error [<class 'decimal.ConversionSyntax'>] when calling a function in serializer
Below is my function in django models. def calc_totals(self): self.total_net_purchase_price = F('quantity') * F('net_purchase_price') self.total_net_sales_price = F('quantity') * F('net_sales_price') self.total_gross_purchase_price = F('quantity') * F('gross_purchase_price') self.total_gross_sales_price = F('quantity') * F('gross_sales_price') self.total_net_profit = F('total_net_sales_price') - F('total_net_purchase_price') self.total_gross_profit = F('total_gross_sales_price') - F('total_gross_purchase_price') When I call this function in DRF serializer: class PZItemSerializer(CountryFieldMixin, serializers.ModelSerializer): class Meta: model = PZItem fields = '__all__' def update(self, instance, validated_data): instance.calc_totals() instance.save() return instance It throws error: [<class 'decimal.ConversionSyntax'>] What's wrong? -
Accessing MongoDB Collection on Django
I have created table on MongoDB Atlas and trying to access it on Django Admin panel. I know how to create table and display on admin panel using models.py. But I am trying to do reverse here for example creating table(Collection) on Atlas MongoDB and access it on Django admin panel. How does that work? -
django-csp lib stripping single quotes?
I'm facing a weird behaviour with django-csp==3.7 and djangosaml2==1.3.3 I have spent a couple hours trying to find out why this happens, and I really don't see what the reason could be. I'm trying to add an exception to a viewset for which I'm willing to allow unsafe-inline The parent view is https://github.com/IdentityPython/djangosaml2/blob/v1.3.3/djangosaml2/views.py#L98 from djangosaml2.views import LoginView class CustomLoginView(LoginView): def get(self, request, *args, **kwargs): response = super().get(request) response._csp_update = {'script-src': ("'unsafe-inline'",)} return response However, when the header gets into the browser, I'm getting unsafe-inline instead of 'unsafe-inline' (note the single quotes) It does not happen in other views of the same project, where I get the expected outcome. -
The view home.views.login_view didn't return an HttpResponse object. It returned None instead
I am trying to create role based login system but it continuously showing the mentioned error N.B: I'm new to django ''' 'def login_view(request):' 'form = AuthenticationForm()' 'if request.method=='POST':' 'username = request.POST.get('username')' 'password = request.POST.get('password')' 'user = authenticate(username=username, password=password)' 'if user is not None and user.is_student==True:' 'login(request,user)' 'if request.GET.get('next'):' 'return render(request.GET.get('next'))' 'else:' 'return redirect('homepage')' ''' -
django query annotate values get list from reverse foreign key
I have a simple model like class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Blog(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) Here I want to query all authors with the title of all the blogs they have written like Author One : Blog One, Blog Two, Blog Three I want this from query and not loop Here my approach is to use subquery like blogs =Blog.objects.filter(author=OuterRef('pk')).values("title") authors = Author.objects.annotate(blogs=Subquery(blogs), output_field=CharField()) But here I am getting error like sub-select returns 2 columns - expected 1 How can I get all the authors with all the blogs they have written ? I do not want to use loop. I want this through query -
Django flush command doesn't clear all tables
I have a django app that contains 4 modules. Each of is modules store data into a table in the database. Which leaves us with 4 tables. When I run a flush command in order to delete existing data in these tables : python manage.py flush --noinput It clears data from 2 tables, but leaves data in the 2 other tables. I find it weird as a behavior. Do you have an idea on how is this possible to solve ? -
Django, Create domain block list for sign up
I am trying to create domain block list for my sign up form and I am having an issue. I made table for domain block list and I want sign up form to raise error if domain is in block list. Apparently, my code doesn't work unless I hardcode it. How do I make this work? :( class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') company_name = forms.CharField(max_length=50, label='Comapny Name') class Meta: model = DomainBlock fields = ('blocklist') ## block common domain from sign up def clean_email(self): data = self.cleaned_data['email'] if data.split('@')[1].lower() in 'blocklist': raise forms.ValidationError("This email is not allowed") # if data.split('@')[1].lower() == 'gmail.com': # raise forms.ValidationError("Gmail is not allowed") # if data.split('@')[1].lower() == 'msn.com': # raise forms.ValidationError("MSN email is not allowed") # if data.split('@')[1].lower() == 'yahoo.com': # raise forms.ValidationError("Yahoo email is not allowed") return data -
Null ID in Django Admin
I'm trying to add a new product in my Products model in Django Admin, yet for some reasons the id field always become null after adding. Below is my code: models.py from django.db import models class Products(models.Model): id = models.BigAutoField(primary_key=True) # incremental id title = models.CharField(max_length=200) def __str__(self): return self.title admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import * class ProductsAdminConfig(ImportExportModelAdmin): model = Products search_fields = ('title',) list_filter = ('title', ) list_display = ('id', 'title', ) admin.site.register(Products, ProductsAdminConfig) Originally I created my database table Products with SQLAlchemy, converting CSV to Mysql. However, I wanted to be able to add a new product inside Django Admin as well. I have tried emptying my SQL table, clearing my migration folder and run py manage.py makemigrations and py manage.py migrate, but the error still persisted. When I tried adding a new product, the data rows with null ids still got generated. Could you suggest me a way to solve this? Thank you! -
How to add a object to a users watch list via a link in Django
I have a website that recommends anime and I want each anime to have some text besides them as they appear, offering to add to a users 'list' which is a page where all anime in the users account-unique list will be shown. I have it working, and can add via the django admin but not via a button on the website. models.py class UserList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) anime_in_list = models.ManyToManyField(Anime, blank=True) views.py @login_required def userList(request): return render(request, 'userlist.html') def add_to_userlist(request, anime_id): new_anime = get_object_or_404(Anime, pk=anime_id) #if UserList.objects.filter(user=request.user, anime_in_list=anime_id).exists(): #message fail user_list, created = UserList.objects.get_or_create(user=request.user) user_list.anime_in_list.add(new_anime) return render(request, "userlist.html") on the html where the anime shows <a href="{% url 'add_to_userlist' anime.id %}" role="button" class="btn btn-outline-success btn-lg">Add to list?</a> but navigating to the anime html page now the error NoReverseMatch at /anime/ Reverse for 'add_to_userlist' not found. 'add_to_userlist' is not a valid view function or pattern name. But I don't want to create a separate url to redirect them, I just want pressing the to add to the users list, and if the user now navigates to their /userlist, they find that it has updated with the anime they clicked the link on. Any help would be super appreciated, ty -
SwiftUI remove authorization for post requests
I'm trying to remove the authorization requirement for post requests to my Django API, but nothing seems to be working. Currently I have this basic authorization header, which allows the one user to send requests: request.addValue("Basic YWRtaW46dGVzdDEyMzQ1", forHTTPHeaderField: "Authorization") My question is, what do I need to put here to allow all requests? I tried just removing it all together, but it results in a forbidden request. I also tried adding this to my Django viewset: permission_classes = [permissions.AllowAny] Let me know if additional info is needed, thanks. -
Filter query through an ID in Django
I know this is a common to ask but I'm just confused, what is the best way to filter data from one table to another table, the case is I want to filter the name of category1 and category2 table through an ID based on the image shown below, It's very helpful for me to use this kind of implementation. It same like this Select title ,description, category1_tbl.name, category2_tbl.name from main_tbl....... JOIN TWO TABLES views.py task_tbl.objects.get(category1_id=category1_tbl.objects.get(id)) -
Django showing Zen Poetry every time on running server
vscode-screenshot I am pretty sure everything is in order but it keep showing this poetry upon running the server or refreshing the server (by saving python file). Please help, this is annoying. -
Error accesing reverse manytomany field from user to onetoone related model
Im having trouble with a model classs which has a onetoone relation with the User model, this the conflictive part: class UserInteraction(models.Model): user = models.OneToOneField(User, related_name="interactions", on_delete=models.CASCADE) users_follows = models.ManyToManyField('self', through='UserFollow', blank=True, symmetrical=False, related_name='user_follows') users_likes = models.ManyToManyField('self', through='UserLike', blank=True, symmetrical=False, related_name='user_likes') When I try to get the follows/likes by doing user.interactions.user_follows or user.interactions.user_likes I get the following error: In [18]: u = User.objects.get(id=1) In [19]: u.interactions.users_likes.all() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [19], in <module> ----> 1 u.interactions.users_likes.all() File ~\...\django\db\models\fields\related_descriptors.py:536, in ReverseManyToOneDescriptor.__get__(self, instance, cls) 533 if instance is None: 534 return self --> 536 return self.related_manager_cls(instance) File ~\...\django\db\models\fields\related_descriptors.py:826, in create_forward_many_to_many_manager.<locals>.ManyRelatedManager.__init__(self, instance) 824 self.prefetch_cache_name = rel.field.name 825 self.source_field_name = rel.field.m2m_field_name() --> 826 self.target_field_name = rel.field.m2m_reverse_field_name() 827 self.symmetrical = rel.symmetrical 828 else: File ~\...\django\db\models\fields\related.py:1598, in ManyToManyField._get_m2m_reverse_attr(self, related, attr) 1596 setattr(self, cache_attr, getattr(f, attr)) 1597 break -> 1598 return getattr(self, cache_attr) AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' Here is the follower and like models used for through in the fk: class UserFollow(TimeStampBase): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') followed = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followed') class Meta: constraints = [ models.UniqueConstraint( name="%(app_label)s_%(class)s_unique_relationships", fields=["followed", "follower"], ), models.CheckConstraint( name="%(app_label)s_%(class)s_prevent_self_follow", check=~models.Q(follower=models.F("followed")), ), ] def __str__(self): return f'{self.follower} follows {self.followed}' class UserLike(TimeStampBase): liker = models.ForeignKey(User, on_delete=models.CASCADE, … -
Get full path excluding the file extension in regex from python [duplicate]
To get the absolute file path without extension, e.g. /home/alice/hello.cpp -> /home/alice/hello I came up with re.findall(r'[^\/]+(?=\.)', file_path) but it is not working file_path = "okok/okok.okok.okok/okokok.mp3" so the result should be "okok/okok.okok.okok/okokok" -
Django Tastypie: viewing schema gets 401 Unauthorized error
I've inherited a Django project that used v0.12.1 of django-tastypie to create an API, I have updated it to use v0.14.4, and am trying to get the new site to work the same as the previous. The API Resources use DjangoAuthorization and while I can mostly* read list and details of them OK, if I try to read an api/<model>/schema/ URL I get a "401 Unauthorized" error. I should be able to view the schema whether I'm logged in or not, which was the case on the previous site. I've noticed that the DjangoAuthorization.read_detail() view is called when I try to view a schema, and that the object_list property of the passed-in bundle is None. I'm not sure if this is the cause or, if so, how to get around it. How can I continue to use DjangoAuthorization, allow anyone to view an endpoint's schema, and not change any other permissions? * There seem to be several other issues/differences with just viewing objects' data through the API, but those are probably questions for another time. -
Filtrar a traves de una lista de otro objeto Django Rest
Dado los siguientes modelos Models.Py class PurchaseRequest(models.Model): grupo_aprobador = models.ManyToManyField(settings.AUTH_USER_MODEL) ### Mas campos ### class PurchaseApproval(models.Model): usuario_aprobador = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) purchase_request = models.ForeignKey(PurchaseRequest, on_delete=models.RESTRICT) ### Mas campos ### Views.py class PurchaseApprovalViewSet(viewsets.ModelViewSet): permission_classes = [DjangoModelPermissions] serializer_class = PurchaseApprovalSerializer def get_queryset(self,pk=None): if pk is None: user = self.request.user return self.get_serializer().Meta.model.objects.filter(purchase_request__grupo_aprobador=user) return self.get_serializer().Meta.model.objects.filter(id=pk).first() Intente esto pero no funciono. Lo que quiero hacer es si un usuario, ha sido agregado al grupo aprobador, que a este solo le aparezcan los purchase request a los que el debe aprobar. -
Getting error while running heroku run python manage.py migrate
I am a beginner in heroku and django and I am trying to create an application. While I was importing my database to heroku by running command - heroku run python manage.py migrate I get an error saying - Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 87, in wrapped saved_locale = translation.get_language() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 182, in get_language return _trans.get_language() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 50, in __getattr__ if settings.USE_I18N: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 84, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 71, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 179, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'pp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line … -
Django admin TabularInline group by query
I have a TabularInline class, StockPartInlines in the inline form view I am trying to GROUP based on two fields (container_id, expiration_date) and add an additional field that is a SUM of an existing field. class Stock(models.Model): part = models.ForeignKey(Part, on_delete=models.PROTECT, related_name='stock') container = models.ForeignKey(StorageContainer, on_delete=models.PROTECT, related_name='items', null=True) quantity_change = models.IntegerField(default=0) expiration_date = models.DateField(blank=True, null=True) class PartAdmin(admin.ModelAdmin): inlines = [StockPartInlines] class StockPartInlines(admin.TabularInline): model = Stock fields = ['container', 'expiration_date', 'quantity'] readonly_fields = ['quantity'] def quantity(self, obj): return obj._quantity The equivalent SQL statement would be; SELECT part_id, container_id, expiration_date, SUM(quantity_change) FROM inventory_stock WHERE part_id = part_id GROUP BY container_id, expiration_date; I have tried to get this to work by overriding the 'get_queryset()' method of StockPartInlines def get_queryset(self, request): qs = super(StockPartInlines, self).get_queryset(request) .values('container','expiration_date') .order_by('container') .annotate(_mwa=Sum('quantity_change')) return qs This has been returning an error of 'dict' object has no attribute '_meta', traceback. I believe this is because using .values() in a queryset returns a queryset of dicts rather than a queryset of objects. Is there a different approach I could take to display the results of this query as an inline form in the admin panel? -
Is there a readily available web based GUI file manager
my org is building a web app and a huge part of it requires a web file manager UI for people to upload, view, download, store and manage their uploaded documents. A preview function of docx and pdf is particularly valuable. The UI should preferably feel like a Mac or Windows File explorer, and on mobile, feel like the iOS/Android file manager. It should support multiple uploads and downloads. Our working idea is to setup one folder for each user, using flask to handle the upload this tutorial. For GUI file management, use bootstrap-flask to connect to a bootstrap file manager template, like this one. Another idea floated around is to use a database (MongoDB gridFS/postgres large object) to store the documents directly. Boss thinks storing a file in a DB is more secure than just storing them "openly" in folders. I tend to disagree but I cannot point to any concrete justifications. Additionally, I think listing out a folder's content is easier (and probably there is a flask extension somewhere) than querying a DB and parsing the results for the front-end to consume. We suspect that the great programming community must have developed something similar and that we can … -
Django form selection affect raising another form
I wana make form on add_form.html, where first appear selection of curve type and than the right form.So somehow link them together on one page. For example user choice: Static cyclic and under this form appears CyclicCurveForm. Thanks for help. models.py: class CyclicCurve(models.Model): name = models.CharField(max_length=200, unique=True) K = models.FloatField(max_length=200) n = models.FloatField(max_length=200) comment = models.CharField(max_length=1000) material_id = models.ForeignKey(Material, on_delete=models.CASCADE) def __str__(self): return self.name class EnCurve(models.Model): name = models.CharField(max_length=200, unique=True) Sf = models.FloatField() b = models.FloatField() c = models.FloatField() Ef = models.FloatField() comment = models.CharField(max_length=1000) material_id = models.ForeignKey(Material, on_delete=models.CASCADE) forms.py: class CurveForm(forms.Form): RELEVANCE_CHOICES = ( (1, ("Static cyclic")), (2, ("En fatigue")) ) type = forms.ChoiceField(choices=RELEVANCE_CHOICES, required=True) class CyclicCurveForm(ModelForm): class Meta: model = CyclicCurve exclude = ['material_id'] class EnCurveForm(ModelForm): class Meta: model = EnCurve exclude = ['material_id'] add_form.html: {% extends "main/base.html" %} {% block title %} Create {% endblock %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type=button value="Previous Page" onClick="javascript:history.go(-1);"> <input type="submit" name="Submit"> </form> {% endblock %} views.py: ### CREATE/ADD/EDIT CURVE ### def create_curve(response, material_type_id, material_id): form = CurveForm() if response.method == "POST": form = CurveForm(response.POST) if form.is_valid(): curve_type = form.cleaned_data ..... context = {"form": form, "material_type_id": material_type_id, "material_id": material_id} return render(response, "main/add_update_form.html", context) -
Django form: visibly group or separate fields
I have a form that I'm displaying within a Django app. This form has a number of fields. To make the UI more intuitive, I would like to display the fields not simply one after the other, but instead grouped into sections - be it within a box or by separating the sections with a horizontal line or larger spacing or custom text etc. My main interest is having the subgroups visibly separated from each other. Being able to use some text (basically a label without an attached field) as section devider would be a welcome bonus. How can I achieve this? Current example code: forms.py: from django import forms class MyForm(forms.Form): color1 = forms.CharField() items_color1 = forms.CharField() # some devider here color2 = forms.CharField() items_color2 = forms.CharField() mypage.html: <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit" id="form_field" name="submit_btn"></td> </tr> </table> (I'm pretty new to Django. My previous GUI experience is mainly with PyQt5.) -
Django form DateInput: change date format from mm/dd/yyy to dd/mm/yy
I'm trying to change the default format of the date from mm/dd/YYYY to dd/mm/YYYY, but even adding a custom format (format="%d/%m%/%YYYY") the result doesn't change. date = forms.DateField(initial=timezone.now(), widget=DateInput(attrs={'class': 'datepicker'}, format="%d/%m/%Y"), label="Data", error_messages=MY_DEFAULT_ERRORS) -
Django - AttributeError: 'tuple' object has no attribute 'name'
I am trying to make an e-commerce website where the "AnonymousUser" or Guest user can order and check out items without the need to login or make their accounts. What I want to do is throw the name and email that was entered in check out form to the database. But it always returned blank in the Customer Table. And after making the payment, there was an error that says AttributeError: 'tuple' object has no attribute 'name' Here's the full traceback in Terminal: Internal Server Error: /process_order/ Traceback (most recent call last): File "C:\Users\RolfShin025\Desktop\E-COMMERCE\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\RolfShin025\Desktop\E-COMMERCE\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\RolfShin025\Desktop\E-COMMERCE\WannaCome\store\views.py", line 82, in processOrder customer.name = name AttributeError: 'tuple' object has no attribute 'name' I also have some error in the console that says: `POST http://127.0.0.1:8000/process_order/ 500 (Internal Server Error)` and `Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0` Here's my models.py file: from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = … -
Connection of Vue and Python script - creation of interactive map
I have a frontend based on Vue.js, where users input the coordinates (lat and lang). This Vue js front end is connected with Django with REST API. Now, I know how to add or remove these lat and lang data sets from DB. Separately I have a Python script, which is generating the route (using HereAPI). How can I pass the data from Vue js exactly to the Python variable, coord = [[..., ...],[..., ...]] launch the Python script and then show the output of the script, the map itself back to the frontend? I expect, it could be done with a kind of POST/GET env. variables. Any advice is appreciated.