Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializers not working on multiple levels as expected in Django
I have 4 models and 3 serializers. 1 model is a simple through table containing information about which user posted which reaction about which article. models.py class User(AbstractUser): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) username = models.CharField(max_length=250, unique=True) ... class Article(models.Model): id = models.CharField(max_length=36, default=generate_unique_id, primary_key=True) title = models.CharField(max_length=50) author = models.ForeignKey(User, related_name='authored', on_delete=models.PROTECT) ... class Reaction(models.Model): user_id = models.ForeignKey(User, related_name='reacted', on_delete=models.CASCADE) article_id = models.ForeignKey(Article, related_name='article_details', on_delete=models.CASCADE) sentiment = models.ForeignKey(Sentiment, related_name='sentiment', on_delete=models.CASCADE) class Sentiment(models.Model): like = models.IntegerField(default=1) dislike = models.IntegerField(default=-1) serializers.py class UserSerializer(serializers.ModelSerializer): authored = ArticleDetailSerializer(many=True, read_only=True) reacted = ReactedSerializer(many=True, read_only=True) class Meta: fields = ( 'id', 'username', 'authored', 'reacted', ) model = User class ArticleDetailSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'title', ) model = Article class ReactedSerializer(serializers.ModelSerializer): article_details = ArticleDetailSerializer(many=True, read_only=True) class Meta: fields = ( 'sentiment', 'article_id', 'article_details', ) model = Reaction Currently, the output for a GET request for a User shows authored correctly. I copied the logic so reacted can be a multi-level object containing sentiment and the relevant article information. I've tried many solutions yet the result for the User field reacted never includes the article_details field. I've ensured the related_name field in in the Reacted model is article_details so what am I missing? I've … -
Django override save method with changing field value
I need some help with overriding save method with changing field value. I have such structure: models.py class Category(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE ) class Product(models.Model): name = models.CharField(max_length=255, validators=[MinLengthValidator(3)]) to_category = models.ForeignKey(Category, on_delete=models.SET_NULL, blank=True, null=True, ) to_categories = models.ManyToManyField(Category, blank=True, related_name='categories', ) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) So I can`t find a correct sollution for save method. I can select category on the "to_category" and categories on "to_categories" field, but I need if I selected one of the categories on the "to_category" field then save the Product, this selected field must be automatically selected on the "to_categories" field. Thanks for help. -
Correct escaping to use in Django templates to avoid Unterminated string literal errors in VS Code
Consider the following in a Django .html template <button onclick="location.href='{% url 'my-route' pk %}'"> # Warns because of this -------^.......^ VS Code will warn of an unterminated string literal as it doesn't understand that inside {% %} is processed first by the template engine. It works just fine, but the VS Code warnings (complete with red highlighting) are distracting. Any way to fix this either by escaping ' or " or changing some VS Code config? -
Dynamically define model attributes / database fields in Django
I would like to define a Django Model looking like this: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Foo(models.Model): object_id_1 = models.UUIDField() content_type_1 = models.ForeignKey(ContentType) object_id_2 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) object_id_3 = models.UUIDField() content_type_3 = models.ForeignKey(ContentType) # etc. d1 = GenericForeignKey("content_type_1", "object_id_1") d2 = GenericForeignKey("content_type_2", "object_id_2") d3 = GenericForeignKey("content_type_3", "object_id_3") # etc. Obviously, the more dimensions (d stands for "dimension") I add, the messier it gets: this isn't very DRY, all the more since I've removed the many fields options in this example. Is there a way to dynamically define these model attributes, for instance in a for loop, without using eval? If not, what would be the cleanest and safest way to resort to eval here? I've found a very similar Stackoverflow question here but it is more specific and it hasn't got any generic answer. -
Change DRF url query filter pattern
The default DRF url pattern for search is "?search=<...>", where you search by a field you add in view's search_fields. How can I change it to "?field_name=<...>" ? How can I change "?field_name__lte=" to "?field_name[lte]=" ? -
how can I display or return a instance of a django model by using another instance(which is primary key)
I have Wallet class. user and Walletname are the instance of this class. when a new user is registered, the Wallet class is created by signal. the thing that ı would like to do is that displyaing or returning the Walletname of the current logged user. thank you I tried filtering but ı got error which is related with id it says %s is expected integer value? However ı have never created a instance named as id -
DRF APITestCase force_authenticate make request.user return tuple instead of User object
I have a custom authentication class following the docs class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) and I used it in my APIView: class profile(APIView): permission_classes = () authentication_classes = (ExampleAuthentication,) def get(self, request, format=None): try: print('user', request.user) serializer = GetUserSerializer(request.user) return JsonResponse({'code': 200,'data': serializer.data}, status=200) except Exception as e: return JsonResponse({'code': 500,'data': "Server error"}, status=500) when I try to call it normally from the API through postman I got the following result from the print and it worked normally: user (<User: User(143)>, True) I written a test as following: class BaseUserAPITest(APITestCase): def setUp(self): # self.factory = APIRequestFactory() self.user = models.User.objects.get_or_create( username='test_user_1', uid='test_user_1', defaults={'agent_type': 1} ) def test_details(self): url = reverse("api.profile") self.client.force_authenticate(user=self.user) response = self.client.get(url) self.assertEqual(response.status_code, 200) I got server error because the print of request.user return a tuple instead of a User object, this is the print from the test log user (<User: User(143)>, True) I tried searching up and seem like there no result or explanation on why this happening My version: django==2.2.8 djangorestframework==3.10.2 -
solr search object and object_list print None
I have implemented solr in django 4+ when i hit the query it return me result but when i run a loop sqs = SearchQuerySet().models(Post).all() sqs.count() # output 3 and run a loop for result in sqs: print(request) output <WSGIRequest: GET '/blogs/search?query=abc'> <WSGIRequest: GET '/blogs/search?query=abc'> <WSGIRequest: GET '/blogs/search?query=abc'> but object or object_list give me None for x in sqs.object_list: print(x) # None output or for x in sqs: print(x.object) # None solr-9.0.0 I want to print fields like x.title and x.publich etc what i am doing wrong please let me know -
Is this login fail? or?
when click login the page no blank to home page just stay in login page the terminal show me "GET /login/?csrfmiddlewaretoken=LK82SQKdzu802NaUuXom8CWRn3S86WWK0XrzEqFCCrUmGGCe06MXoMgFtt0JLDRN&username=tim&password=tim123 HTTP/1.1" 200 3148 and the browser link this http://127.0.0.1:8000/login/?csrfmiddlewaretoken=MWNadf5CSlSmTnCFIlJ5aoJDKHL1ShJJ196HZP01ViEIxg4Zeu7Gqy3rQ7TCxYEM&username=tim&password=tim123 login.html {% extends "main/base.html" %} {% block title %} Login Here {% endblock title %} {% load crispy_forms_tags %} {% block content %} <form class="from-group" method="get"> {% csrf_token %} {{form | crispy}} <button type="submit" class="btn btn-success">Login</button> <p>Don't have an account? Create one <a href="/register">Here</a></p> </form> {% endblock content %} settings.py (i just skip to STARIC it so long STATIC_URL = 'static/' CRISPY_TEMPLATE_PACK = "bootstrap4" (add) LOGIN_REDIRECT_URL = "/" (add) urls.py from django.contrib import admin from django.urls import path, include from register import views as v urlpatterns = [ path('admin/', admin.site.urls), path('register/', v.register, name='register'), path('', include('main.urls')), path('', include('django.contrib.auth.urls')), ] -
Django - problem with adding extra variable to the context that will count matched filters?
I have a function that gives me HTML with filtered products based on several filters that users can use on the website. The filters are the list of checkboxes (multiple choice of course). I managed to pass a product title but I also want to add the number of matched options next to each product title so if the user will select 3 out of 8 checkboxes in Filter 1 and Filter 2 lists then the list of matched product titles and the number of matched filters will be updated. For now the page it looks like this: What I want is this: Where 3 means that this product matches to all 3 options I selected and second product with 1 means that only 1 option matches from Filter 1 and Filter 2. I suppose that I need to add annotate with Count method but how can I do that if my fulter1 and filter2 is a list, not a queryset. views.py def filter_data(request): filter1 = request.GET.getlist('filter1[]') filter2 = request.GET.getlist('filter2[]') product_list = Product.objects.all() if len(filter1) > 0: product_list = product_list.filter(filter1__title__in=filter1).distinct() # how to add matched_products_count in here? if len(filter2) > 0: product_list = product_list.filter(filter2__title__in=filter2).distinct() # how to add matched_products_count in … -
Python-Docx - Jinja2: Populate word document without messing the template
I am trying to populate my word template with info from database. But it keep messing up the template. Any other way to make the result exactly the same as the template? template.docx result.docx Here's my code for views.py def save_devicedemoteapplication(request): samples = DeviceDemoteApplication.objects.all()[0:10] document = DocxTemplate("template.docx") context = { 'content': [], } for sample in samples: count = 0 samp= [count, sample.device.device_name, sample.device.asset_number, sample.device.device_model, sample.device.serial_number, sample.demote_reason, sample.demote_time, sample.device.buy_time, sample.technology_administrator, sample.quality_administrator] context['content'].append(samp) document.render(context) document.save('result.docx') return redirect('/DeviceDemoteApplication/') -
How to get uploaded file in views?
I'm trying to get uploaded data in my views. Firstly, I'm getting the path and after that I have to read the file but Django gives me an error FileNotFoundError: [Errno 2] No such file or directory: '/Users/edc/PycharmProjects/wl/SM/uploads/meetings notes (1).docx but I have that file. How can I fix that? upload = Upload(file=f) content = ScanDocument(upload.file.path) upload.save() def ScanDocument(file_path): text = docx2txt.process(file_path) return text Note if I use url instead of path then it returns: FileNotFoundError: [Errno 2] No such file or directory: '/media/Meeting%20notes%20notes%20%(1).docx' -
Dynamically change db_table django Meta
Sorry for my English I have a table to manage list of database configurations. Table post in all db have same fields but different name. Eg. table post name is md_post, table post in other db is tdt_post. So, when I access a db configuration I want to remote that database. I did it! But how can I change tb_name in Meta Django Model? These Datatables configurations are non-permanent and may change when I add/update/delete record. I tried it, but it only works one time. Post._meta.db_table = `tdt_post` Post._meta.original_attrs['db_table'] = `tdt_post` When I change the db_table back to 'md_post', it doesn't work. I have looked at the following posts, but it doesn't solve my problem: Django model: change db_table dynamically Change table name for django model in runtime -
I am getting error when to limit foreign keys
Goal: I want to limit(20) the number of Students per Group. I was trying to make validation (based on this question - Limit number of foreign keys), but got a problem - it's working when I am trying to make 21 Student in group in my Django admin panel, but when I'm trying to change login(or other parameters) of Student (the group in this moment has 20 Students), who already in group it turns up an error, because it seems like I already have 20 students and trying to add new one def validate_number_of_students(value): if User.objects.filter(group=value).count() >= 20: raise ValidationError('Already 20 students in group (20)') class User(AbstractUser): role = models.CharField(max_length=max([len(role[0]) for role in ROLES]), choices=ROLES, default=USER, ) group = models.ForeignKey('structure.Group', on_delete=models.SET_NULL, related_name='users', blank=True, null=True, validators=(validate_number_of_students, ) ) I tried to use this method with constraint (limit number of foreign key using Django CheckConstraint) but get an error, maybe I'm doing something wrong? (I have two apps - structure with Group model and users with User model) models.CheckConstraint( name="limit_students_in_group", check=IntegerLessThan( models.Count("group", filter=models.Q(group=models.F("group"))), 20), ) -
Django - problem with saving data in Createview with ModelForm to non-default database
I've got problem with saving data to non-default database. In models.py I've got: grid_fs_storage = GridFSStorage(collection='tab_userinquiries', base_url='mydomain.com/userinquiries/',database='mongo_instance') class DocsUserInquiry(models.Model): query_pk = models.CharField(blank=False, null=False, unique=True, max_length=150, primary_key=True) # auto - calculated query_file_md5 = models.CharField(blank=False, null=True, unique=False, max_length=200) # auto - calculated query_file = models.FileField(upload_to='userinquiries',storage=grid_fs_storage,null=True) # auto from form In views.py: class UploadInquiryFileView(CreateView,LoginRequiredMixin): model=DocsUserInquiry template_name ='new_inquiry.html' success_message = "You've added your new Token successfully" form_class = UploadInquiryFileForm def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): file_name = request.FILES['query_file'].name print(f'file...{file_name}') q_pk = random_id() file_in = self.request.FILES.get('query_file') f_md5 = calculate_md5(file_in) form.instance.query_pk = q_pk form.instance.query_file_md5 = f_md5 form.save() return HttpResponse(self.success_message) The problem is every time when I submit form I've got Exception Type: TypeError Exception Value: database must be an instance of Database I've tried added this to post method: instance = form.save(commit=False) instance.save(using='mongo_instance') but the error is the same. Any ideas how to resolve this issue? NOTE: This issue is related only with modelform or when I use custom list of fields in view. When I'm using CreateView without ModelForm but with fields = 'all' and additionally with the logic passed to form_valid method of the view instead of post everything works fine. Then files are added to my mongo db. -
how to display first_name in database on django
`views.py from allauth.account.views import SignupView from .forms import HODSignUpForm class HodSignUp(SignupView): template_name = 'account/signup.html' form_class = HODSignUpForm redirect_field_name = '' view_name = 'hod_sign_up' def get_context_data(self, **kwargs): ret = super(HodSignUp, self).get_context_data(**kwargs) ret.update(self.kwargs) return ret forms.py from .models import Admin from po.models import User from allauth.account.forms import SignupForm class HODSignUpForm(SignupForm): first_name=forms.CharField(required=False) last_name=forms.CharField(required=False) class Meta: model= Admin fields = ['first_name','last_name'] def save(self,request): user = super(HODSignUpForm, self).save(request) user.is_hod = True user= User(first_name=self.cleaned_data.get('first_name'), last_name=self.cleaned_data.get('last_name')) user.save() return user models.py from po.models import User class Admin(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=30, db_column='first_name') last_name = models.CharField(max_length=30, db_column='last_name') po.models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_active = models.BooleanField(default=True) is_hod= models.BooleanField(default=False) first_name = models.CharField(null=True, max_length=50) last_name=models.CharField(null=True, max_length=50) admin.py from po.models import User class Schooladmin(admin.ModelAdmin): list_display = ("id","is_active","is_hod","first_name","last_name") list_filter = ("is_active","is_hod") add_fieldsets = ( ('Personal Info', { 'fields': ('first_name', 'last_name') }), ) admin.site.register(User,Schooladmin) enter image description here i want this image show name but how does show firstname and lastname on database? -
Can't describe POST request with BaseHandler
sorry for my bad english get request works fine, the data is displayed correctly, but it's not possible to add new data, it shows a server error status 500 Class Test(models.Model): id = models.AutoField(u'id', primary_key=True) name = models.CharField(u'name', max_length=255, null=True) class Meta: db_table = u'test' verbose_name = u'test' verbose_name_plural = u'tests' Class TestHandler(baseHandler): def read(self, request, id=None): return self.model.object.all() enter image description here def create(self, request, id=None): f=Test(request.POST) new=f.save() return new POST http://127.0.0.1:8000/test/ 500 (INTERNAL SERVER ERROR) I tried this, but it doesn't work either: def create(self, request, id=None): new_test = SmartCheckpointVideo( id=request.POST['id'], name=request.POST['name'] ) new_test.save() return new_test and this def create(self, request, id=None): new_test = SmartCheckpointVideo( name=request.POST['name'] ) new_test.save() return new_test I don't understand how to work with BaseHandler, if there is detailed documentation, please share it -
DRF: many=True causes array instead of returning a regular object
I'm using a nested serializer to access the facility address of each facility. The only way the values will actually show is when i add many=true to the "LeadFacilityDetailFacilitySerializer". But the issue is that it will add [] around my address object. Which leads to "undefined" whjen i try to access the items inside my address object: {info.LeadFacilityDetailFacility.AddressInfo.City} serializers.py class LeadAddressSerializer(serializers.ModelSerializer): class Meta: model = FacilityAddress fields = ( "PrimaryAddress", "SecondaryAddress", "City", "RegionOrState", "PostalCode", ) class LeadFacilityDetailFacilitySerializer(serializers.ModelSerializer): AddressInfo = LeadAddressSerializer(source="fa", many=True) class Meta: model = Facility fields = ('mainimage', 'Name', 'AdministratorCell', 'AddressInfo') class LeadFacilityDetailSerializer(serializers.ModelSerializer): LeadFacilityDetailFacility = LeadFacilityDetailFacilitySerializer(source="assigned_facilities") class Meta: model = LeadFacilityAssign fields = ('assigned_facilities', 'datetime', 'id', 'LeadFacilityDetailFacility') models.py class FacilityAddress(models.Model): PrimaryAddress = models.CharField(max_length=150, null=True, blank=True) SecondaryAddress = models.CharField(max_length=150, null=True, blank=True) City = models.CharField(max_length=150, null=True, blank=True) RegionOrState = models.CharField(max_length=50, null=True, blank=True) PostalCode = models.CharField(max_length=30, null=True, blank=True) Geolocation = models.CharField(max_length=30, null=True, blank=True) AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') class Facility(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) -
Calling the list created using getlist on the form
In my Django project, I save the data in a field that I have made multiple selections to the database using the getlist function and the POST method. Then I pull this data from the database and print it on an html form, but I cannot access the list data properly unless I split it here. views.py def record_form(request): if request.method == "POST" and 'registrationSave' in request.POST: records = Records() records.medications = request.POST.getlist('medications') records.scale_used = request.POST.getlist('scale_used') records.save() return redirect('/index/tables') def editRecords(request,id): edit_records = Records.objects.get(id=id) if edit_records.medications is not None: edit_records.medications = edit_records.medications.split(",") if edit_records.scale_used is not None: edit_records.scale_used = edit_records.scale_used.split(",") institutionName = Institution.objects.all() medicationName = MedicationName.objects.all() return render(request,"update_record.html",{"Records": edit_records, "institutionName":institutionName,"medicationName":medicationName}) update.html <div class="col-4"> {% for medication in Records.medications%} <div class="mb-3 col"> <label for="">İlaç Adı:</label> <select class="form-select" name="medications" id="medications"> <option {% if medication == '{{medicationName.medicationName}}' %} selected {%endif%}>{{medication}}</option> {% if medicationName%} <p>{{medicationName}}</p> {% for medicationName in medicationName %} <option value="{{medicationName.medicationName}}">{{medicationName.medicationName}}</option> {%endfor%} {%endif%} </select> </div> {%endfor%} </div> I'm sharing my code pieces above with you, and I'm leaving the screenshot of the update.html page below. How can I follow a method to avoid [ ] and ' ' signs? enter image description here Thank you in advance for your help -
Does a function based view in Django returning JSON response considered RESTful?
A function based view in Django which authenticates the user based on the sessionid and requests using X-CSRFToken(for POST calls) which returns data in JSON is considered RESTFul? I am currently not using djangorestframework for my project. -
Need Inline ManytoMany Field add in django admin
I am creating a manytomany field in my model and creating a Inline Tabular with though also. but on django admin it is showing dropdown. and if I add new then it shows a Popup. But I dont want Popup. Instead of that I want inline add as in case of Foreign Key. Thanks in advance. Please help... class ExamInline(admin.TabularInline): # classes = ['collapse'] model = Form.exam.through extra = 0 -
django-advanced-filters text contains not working
I would like to set a filter that gives me all items where "@test.com" is in the email. When setting up the filter, the field only allows me to select something from the autocomplete list of existing entries. Else it does not save. There is no possibility to add a custom string here. I am using python 3.10.4, django 3.0, django-advanced-filters 2.0.0 I tried to insert any different string but it would not save. I would expect the contains to allow for only a part of a string to compare and not to specify an existing string of the field that is already used. -
How to return choices tuple value in string format in django Admin panel
I've been trying to get tuple value from choices tuple of CharField() in Model to display in the Django Admin Panel row whenever a table is accessed I'm aware of the following answer... get_foo_display() but it returns the following error AttributeError: 'device_table' object has no attribute 'get_device_type_display' Here's the model: device_table(models.Model): device_type = ( ('AD' , 'Android'), ('IO' , 'iOS'), ('WD' , 'Windows'), ('MO' , 'MacOS'), ('LX' , 'Linux') ) user_device_type = models.CharField(choices = device_type, null = True, max_length=3) class Meta: verbose_name = ('Device Table') def __str__(self): return self.get_device_type_display() I'm running django 4.0.8 by the way -
Django -- connection to local postgresql to docker container
Hello everyone i try to connect local postgres db to the docker container in django project. as mention in this post it works on my local machine which is ubuntu 20.04 LTS but cannot run same project on ubuntu-server which is ubuntu 20.04 LTS. screenshots are give below pg_hba.conf postgres.conf Error in terminal this is my dockercompose file -
When using django's queryset union function, data in the queryset at the back may be lost
When using django's queryset union function, data in the queryset at the back may be lost. The structure of the model I used is as follows. class Genre(models.Model): name = models.CharField(max_length=50) class Top_Movie(models.Model): title = models.CharField(max_length=100) release_date = models.DateField() popularity = models.FloatField() vote_count = models.IntegerField() vote_average = models.FloatField() overview = models.TextField() poster_path = models.CharField(max_length=200) backdrop_path = models.CharField(max_length=200) genres = models.ManyToManyField(Genre, related_name="top_genre") year = models.IntegerField() ranking = models.IntegerField() class Now_Movie(models.Model): title = models.CharField(max_length=100) release_date = models.DateField() popularity = models.FloatField() vote_count = models.IntegerField() vote_average = models.FloatField() overview = models.TextField() poster_path = models.CharField(max_length=200) backdrop_path = models.CharField(null=True, max_length=200) genres = models.ManyToManyField(Genre, related_name="now_genre") year = models.IntegerField() ranking = models.IntegerField() Top_Movie.objects.all().union(Now_Movie.objects.all()) In the above situation, the genres field data of Now_Movie is lost. Now_Movie.objects.all().union(Top_Movie.objects.all()) In the above situation, genres field data loss of Top_Movie occurs. I don't know why this is happening. Please help. I solved the problem by not using union , but I want to know why this happened. My guess is that the ManyToManyField is causing something, but I don't know exactly why.