Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loading Template in Admin Form for Custom Fields
I learned that I can add a custom button in my Admin form by adding it to fields = ["connect"] readonly_fields = ('connect',) def connect(self, obj): return format_html("<button></button>") connect.allow_tags=True connect.short_description = '' However, the html I want to add to the connect is getting out of control. I was wondering if there's a proper (Django-nic) way to move that to a template and load and return the content of the template in the connect function. I can think of reading the content of the template file (open('file.html', 'r')) to read the content, however, I am looking for a suggestion that aligns Django standards (if any). P.S. I also tried creating a view for getting the HTML content of the connect file, but that for some reason doesn't seem to work and feels unnatural to do. -
Can't correctly receive data in Django from Ajax
I wand to receive array data in Django view from jquery/Ajax request but in some reason I cannot correctly do it. This is the piece of js code: var arr = [1, 2]; $.ajax({ type: 'POST', url: '/go/', data: {arr: arr}, success: function (data) { console.log('Success!'); }, }); And this is from Django view: def go(request): if request.method == 'POST': arr = request.POST['arr'] It gives me KeyError: 'arr' If I do print(request.POST) in Django it prints it like this: <QueryDict: {'arr[]': ['1', '2']}>. Some square brackets appear after 'arr' key. Then if I do arr = request.POST['arr[]'] using the key with square brackets it assings arr value 2, so only the last value of the array. Can someone please explain to me why this is happening? -
can i do process with form django python
there is a input and select with options in form tag. i want to get input value and option that entered. and i will do somethings on backend with python that value and option than i will return a result to website. but i dont use to forms.py. how can i do? is it possible? <form action="" method="post"> {% csrf_token %} <input type="text" name="getinputValue"> <select name=""> <option value="1"></option> <option value="2"></option> <option value="3"></option> </select> <button type=""class=""></button> <p>{{result}}</p> </form> -
Why this django formset has stopped saving the content all of a sudden?
I had this view that rendered a form and a formset in the same template: class LearnerUpdateView(LearnerProfileMixin, UpdateView): model = User form_class = UserForm formset_class = LearnerFormSet template_name = "formset_edit_learner.html" success_url = reverse_lazy('pages:home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) learner = User.objects.get(learner=self.request.user.learner) formset = LearnerFormSet(instance=learner) context["learner_formset"] = formset return context def get_object(self, queryset=None): user = self.request.user return user def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) user = User.objects.get(learner=self.get_object().learner) formsets = LearnerFormSet(self.request.POST, request.FILES, instance=user) if form.is_valid(): for fs in formsets: if fs.is_valid(): # Messages test start messages.success(request, "Profile updated successfully!") # Messages test end fs.save() else: messages.error(request, "It didn't save!") return self.form_valid(form) return self.form_invalid(form) Then i wanted to make it prettier and i added the select2 multicheckbox widget and the django-bootstrap-datepicker-plus Nothing has changed elsewhere, yet when i submit the post it only saves the data relative to User and not to Learner (which relies on the formset) According to the messages, the formset data is not validated, I don't understand why since i didn't touch the substance at all but just the appearance. Being a beginner im probably missing something big, I thank in advance whoever can help me find out the problem. … -
Django dumpdata slow after delete all records in table
I cleared a table using RulesUsed.objects.all().delete() There were about 35,000 records in the table (out of a total database of 45,000 records in all tables). python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db_input.json dumpdata went from about 17 seconds before delete to more than 19 minutes after. I have tried rebuilding the container and loading the data with json file from dumpdata -- so there is no data in the (now) empty table. dumpdata time on the new database is the same -- 19 minutes. python manage.py loaddata --ignorenonexistent /scripts/db_input.json I feel I have misunderstood something and there is some relation slowing things down. I tried clearing from command line with same result of 19 minutes; python manage.py shell from appname.models import RulesUsed RulesUsed.objects.all().delete() The table is a child of another, the model is; class RulesUsed(models.Model): hs_input = models.ForeignKey( hs_input, on_delete=models.CASCADE, related_name='rules_used' ) Rule_Type = models.CharField(max_length=50) Rule = models.CharField(max_length=50) Value = models.CharField(max_length=256) Rule_Comment = models.CharField(max_length=100) class Meta: ordering = ['hs_input','Rule_Type','Rule'] def __str__(self): return f'{self.hs_input} : {self.Rule_Type} : {self.Rule} : {self.Value}' def as_dict(self): return {'id': self.hs_input, 'Rule type' : self.Rule_Type, 'Rule' : self.Rule, 'Value' : self.Value, 'Rule comment' : self.Rule_Comment } The database is Postgres. Python 3.8. Django 2.2.5. Running … -
DRF data not validating nexted object while processed with file data (multipart/form-data)
===========JS========== const data = { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d8", "logo": null, "name": "Company 1", "account": { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d9", "name": "Account Name", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, "modules": [ { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d1", "name": "Module 1" }, { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d2", "name": "Module 2" }, ], "addresses": [ { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d4", "name": "Address 1", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d5", "name": "Address 2", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, ], } let formData = new FormData(); Object.keys(data).map(key=>{ formData.append(key, typeof data[key] === "object" && key!=="logo"? JSON.stringify(data[key]):data[key]) }) const config = { headers: {'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'} }; //axios.put(url, data).then(res => {console.log(".....Response!!! UPDATE")}).catch(err => {console.log(err.response.data)}) axios.put(url, formData, config).then(res => {console.log(".....Response!!! UPDATE")}).catch(err => {console.log(err.response.data)}) ===========Models========== class Address(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('name'), max_length=254, unique=True) company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="our_addresses") class Module(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=32) class Account(CompanyBaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=32) company = models.OneToOneField("Company", on_delete=models.CASCADE, related_name="account") class Company(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('name'), max_length=254, unique=True) logo = models.ImageField(_('Company Logo'), upload_to=logo_path, storage=PublicMediaStorage(), blank=True, null=True, default=None) addresses = models.ManyToManyField(Address, related_name="companies") modules = models.ManyToManyField(Module) ===========Serializers========== class AddressFormSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=False, required=False, allow_null=True) class Meta: model = Address fields = '__all__' read_only_fields = ['company', ] class ModuleFormSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=False) # required ONLY for … -
How can I use Pathlib for configuring the settings for the project in Django/Faker?
Right now I'm trying to put some fake data in my database using Faker just for the checking purposes. I've created separate file, but before starting to work with Faker itself and data manipulation, I need to configure the settings for the project in this separate file. Before DJANGO==3.1 all people have been using OS module and the following syntax. import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') But now, when Django versions higher than 3.1 switched from OS module to PATHLIB module, how should I write this code using PATHLIB, not OS? Any help would be helpful! -
Can someone pleas tell me why my form is not valid
I'm stuck. I tried to get this forms.py to work but django never said that the form or things i write into the form at the webpage is valid I thought i made this in a nother app excactly the same way and it works there. class Recipe(models.Model): DIFFICULTY_EASY = 1 DIFFICULTY_MEDIUM = 2 DIFFICULTY_HARD = 3 DIFFICULTIES = ( (DIFFICULTY_EASY, u'einfach'), (DIFFICULTY_MEDIUM, u'normal'), (DIFFICULTY_HARD, u'schwer'), ) EVALUATION_V_SATISFIED = 5 EVALUATION_SATISFIED = 4 EVALUATION_NEUTRAL = 3 EVALUATION_DISSATISFIED = 2 EVALUATION_V_DISSATISFIED = 1 EVALUATION_DUNNO = 0 EVALUATIONS = ( (EVALUATION_V_SATISFIED, u'sehr zufrieden'), (EVALUATION_SATISFIED, u'zufrieden'), (EVALUATION_NEUTRAL, u'neutral'), (EVALUATION_DISSATISFIED, u'unzufrieden'), (EVALUATION_V_DISSATISFIED, u'sehr unzufrieden'), (EVALUATION_DUNNO, u'k. A.'), ) CATEGORY_KOCHEN = 1 CATEGORY_BACKEN = 2 CATEGORIES = ( (CATEGORY_KOCHEN, u'Kochen'), (CATEGORY_BACKEN, u'Backen'), ) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=u'Autor',related_name="recipe", null=True, default=1) published = models.DateField(default=timezone.now, editable=False) #picture später hinzufügen mit MEDIA_ROOT title = models.CharField(max_length=250) img_url = models.TextField(null=True,blank=True) evaluation = models.SmallIntegerField(choices=EVALUATIONS, default=EVALUATION_NEUTRAL) category = models.SmallIntegerField(choices=CATEGORIES, default=CATEGORY_KOCHEN) subcategory = models.ManyToManyField(SubCategory,verbose_name=u'Unterkategorien') portions = models.PositiveIntegerField() duration_ges = models.PositiveIntegerField(null=True, blank=True) duration_working = models.PositiveIntegerField(null=True, blank=True) duration_cooking = models.PositiveIntegerField(null=True, blank=True) difficulty = models.SmallIntegerField(u'Schwierigkeit', choices=DIFFICULTIES, default=DIFFICULTY_MEDIUM) tags = TaggableManager() class Meta: verbose_name = u'Rezept' verbose_name_plural = u'Rezepte' ordering = ['-published'] def __str__(self): return self.title this is my forms.py class RecipeForm(forms.ModelForm): class Meta: model = Recipe … -
django simple history doesn't show in admin
I have followed the Django-simple-history documentation to display history from the admin page but somehow the history doesn't seem to appear from the admin page. I am using Django version 3.1.2 Here is my admin from django.contrib import admin from simple_history.admin import SimpleHistoryAdmin from .models import Company admin.site.register(Company, SimpleHistoryAdmin) -
display PIL image object in django template
i have edited the user profile photo with PIL library and trying to display the new image in my django template but somehow the image is not displaying ,here is my code in views.py : enterim = Image.open(get_user_model().objects.get(username=request.user).avatar) width, height = im.size newsize = (50, 50) image = im.resize(newsize) buffer = BytesIO() image.save(buffer, "PNG") img_str = buffer.getvalue() return render(request, '../templates/templates_v2/update_location.html', {'updatelocation_form': updatelocation_form,'user_info':user_info,'img_str':img_str}) and this is the img tag in html template: <img src='data:image/png;"+ {{img_str}} + "'/> Thanks in advance -
Django long model text field not loading from database but value exist in database
Django long model text field not loading from database but value exist in database. Databse used is Postgres. Since value is saved to database without issue I think problem is with Django loading afterwards. file_name in database: 2020-11-20-17-06-29_7e3410a8-4aa2-42d1-8225-3152757d433_v2ol-tHLIO_z7kyOPHfVAUHd13mcIE-7gD2OhFWowLc3RTfS1HKxxnPQ.mp3 In model.py class TestModel(models.Model): ... file_name = models.TextField(null=True) ... In view.py test_model = TestModel.objects.get(id=id) print(test_model.file_name) # file_name is None -
How to parse multipart form data by `MultipartParser`
I try to send list of values as a multipart form data by Swagger but I received comma separated array. attachments = "1,2,3,4" How I can send list of ids instead of comma separated array? class ProjectViewSet(UpdateModelMixin, CreateModelMixin): serializer_class = ProjectSerializer parser_classes = (MultiPartParser, ) permission_classes = (IsAuthenticated,) queryset = Project.objects.all() def create(self, request, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): project = serializer.create(serializer.validated_data, user=request.user) return Response(self.get_serializer(project).data) -
CSS from static folder in Django
my first question here. I'm still new to both Django and CSS. I'm trying to use CSS from Static folder in my Django project. It's all at a pretty basic stage. In the 'static' subfolder 'css' I have one main.css file with example code: body{ font-size: 20px; background-color: black; } h1{ color: #008000; } In my settings.py file I have: import os (...) DEBUG = True (...) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] And in my base.html template: {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Shopping List</title> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> </head> <body> <h1>TEST</h1> {% block content %} {% endblock %} </body> </html> I've tried moving the css file, changing the view/url, and adding/deleting bootstrap (which alone works). In the end my page just turns light blue-ish. Thanks in advance. -
DRF Reverse Relationship Unable to Filter in Serializer
Having an interesting problem with DRF and wondering if anyone has any ideas. For a simplified example, take these two Django models: class Vote(models.Model): user_who_voted = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) vote = models.IntegerField(choices = [(-1, "down"), (1, "up")]) timestamp_voted = models.DateTimeField(auto_now = True) sample_model = models.ForeignKey('SampleModel', on_delete=models.CASCADE, related_name = 'sample_model_votes') class Meta: constraints = [models.UniqueConstraint(fields=['user_who_voted', 'sample_model_id'], name='one_vote_pp_sample_model')] class SampleModel (models.Model): #does some stuff In serializing SampleModel, I want to be able to get the value for vote for the request user (of which there is guaranteed to only be one vote, if any). In a Django shell, I can pull an instance/item of SampleModel easily: samplemodelexample = SampleModel.objects.get(pk = 1) and then I can traverse the reverse relationship to Vote successfully to return the vote value: samplemodelexample.sample_motel_votes.filter(user_who_voted_id = 1).get().vote Taking this exact same code (simplified to show relevant portions) into DRF seems to create an issue: class SampleModelSerializer(serializers.ModelSerializer): user_vote = serializers.SerializerMethodField() class Meta: model = SampleModel fields = ['user_vote'] read_only_fields = fields def get_user_vote(self, obj): try: vote = obj.sample_model_votes.filter(user_who_voted == self.context['request'].user).get().vote #stacktrace on this line return f"{vote}" except: traceback.print_exc() return '0' I get an error on the line indicated that NameError: name 'user_who_voted' is not defined Does anyone have any idea why? … -
AttributeError at /admin/pizza/topping/add/ 'NoneType' object has no attribute 'attname'
When i try to add entries from admin server i get the above error class Pizza(models.Model): name_text = models.CharField(max_length=200) def __init__(self): self.name_text class Topping(models.Model): name = models.ForeignKey(Pizza, on_delete=models.CASCADE) text = models.CharField(max_length=100) def __init__(self): self.text -
Dynamic Display of Address on Google Map Triggered by Selection
I have a list of products that I display on a web page. Each product has a seller with an address. When I click on a product, I want a Google Map on the same page to show the address of the seller of that product on the map. I'm using Django for my server-side technology but the solution I'm looking for can be pure HTML/CSS/JavaScript which I will then integrate. Any help would be greatly appreciated. Thanks. -
can't find mod_wsgi.so after yum installation
I'm trying to move an old client to a new server and get WSGI working for his django backend. I installed wsgi using yum; the httpd -M command shows that it is installed. However, the file mod_wsgi.so appears to be nowhere on the server. Earlier I had tried to include a WSGIScriptAlias command in the httpd.conf file, and received this error: /etc/apache2/conf.d/includes/pre_main_global.conf.tmp: Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration --- /etc/apache2/conf.d/includes/pre_main_global.conf.tmp --- 1 ===> WSGIScriptAlias /spdre /home/pdr887629/django/sullivan/wsgi.py <=== --- /etc/apache2/conf.d/includes/pre_main_global.conf.tmp --- Another Stack Overflow solution on that error message said I should include this first: LoadModule wsgi_module modules/mod_wsgi.so But the mod_wsgi.so file does not actually exist in that directory, or anywhere else on the server. How can I get mod_wsgi working? Do I need to reinstall via another method, or is there somewhere I can go from here (with the current install)? Thank you for any assistance. -
The proper way to upset field in Mongodb using Djongo?
I have following Person model class Person(models.Model): id = models.ObjectIdField() # ----------------- CharFields ------------------ name = models.CharField(max_length=255) city = models.CharField(max_length=255) status = models.CharField(max_length=20) phone_number = models.CharField(max_length=10) objects = models.DjongoManager() def __str__(self): return self.name and comment model class Comment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) comments = models.JSONField() objects = models.DjongoManager() The add_coment method looks like this @api_view(['POST']) def add_comment(request): comment_data = JSONParser().parse(request) comment_serializer = CommentSerializer(data=comment_data) if comment_serializer.is_valid(): comment_serializer.save() return JsonResponse(comment_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(comment_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then I call add_coment methods twice with the same request instead of update this field it create the other document. What is the proper way to perfume upsert operation? -
Creating Keycloak user from docker container
I am having problems creating users using the Keycloak REST API from my docker container running a Django application. The following works using postman: Fetch admin token Create user: The following does NOT work in python, and returns 401 Unauthorized: Fetch admin toke (This successfully returns a token): Create user (This returns 401): I am using the exact same user credentials in both scenarios,and since I am able to get this to work in postman I don't think there's any problem with access/roles etc. Any help is greatly appreciated. Thanks! -
Django model.save() not updating model instance
I am trying to update a handful of fields if the record has been marked as deleted. When I debug, I can see that the values are being assigned in the view, but not being updated in the DB. I'm not sure what I'm missing. views.py contact_formset = ContactFormSet(request.POST, prefix='contact') for contact in contact_formset.deleted_forms: contact = contact.cleaned_data print(contact) instance = contact['id_cnt'] contact_id = instance.id_cnt contact_object = get_object_or_404(AppContactCnt, id_cnt=contact_id) contact_object.deleted_cnt = True contact_object.date_deleted_cnt = '2020-11-23' contact_object.deleted_by_cnt = 'adeacon' contact_object.save() -
How to combine these 2 fields?
I have total Count of comments for 1 movie comments = Comment.objects.filter(movie_id=object_id).count() How to Count all comments in time period (start_date,end_date) I know About Q filter filter=Q(Comments__pub_date__range=( start_date, end_date)) so, how compine those two Fields and get the answer?? -
DJANGO + windows: .bat file: open a command prompt and run the commands
I have to run the following set of commands after opening a windows cmd prompt D: cd Dev\project\backend .\venv\Scripts\activate python manage.py runserver How to write a script(.bat) file for running these commands and the runserver will stay showing the output I tried to put these commands in django.bat and double click, but a cmd window opens and within a fraction of second it closes. Dont know what happened -
What answer to make on OPTIONS request in CRUD on Django?
I have code that handles django requests. It must respond to user requests. He has registered answers to POST and GET requests. But the frontend sends an options request, and it makes no response. What should I prescribe? @csrf_exempt def user_api(request, email=""): # if request.method == "GET": # users = User.objects.all() # users_serializer = UserSerializer(users, many=True) # return JsonResponse(users_serializer.data, safe=False) # if email is not specified in address line by http://127.0.0.1:8080/user/some-email # then django returns data of ALL objects in json print(email) print(request.method) if request.method=="OPTIONS": return if email == "" and request.method == "GET": users = User.objects.all() users_serializer = UserSerializer(users, many=True) return JsonResponse(users_serializer.data, safe=False) elif email == "" and request.method == "POST": user_data = JSONParser().parse(request) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("New user was created successfully", safe=False) else: return JsonResponse("Failed to create user", safe=False) else: # search the specified email and return data in json if request.method == "POST": try: user = User.objects.get(email=email) user_serializer = UserSerializer(user, many=False) print(user_serializer.data) return JsonResponse(user_serializer.data, safe=False) except ObjectDoesNotExist: return JsonResponse("User does not exists", safe=False) elif request.method == "PUT": user_data = JSONParser().parse(request) user = User.objects.get(email=user_data['email']) # щоб знати конкретного юзера, інфу якого змінюватимемо user_serializer = UserSerializer(user, data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse("User information was updated … -
django-cacheops with aws redis Encryption
I have set up redis with Encyption in transit and rest. I have come across https://dev.to/yuki0417/easy-way-to-connect-to-amazon-elasticache-redis-with-password-from-django-app-40il and Connect to AWS ElastiCache with In-Transit Encryption. As I am using https://github.com/Suor/django-cacheops shows nothing regarding ssl how can I implement ssl to use the aws redis with encryption? I have tried CACHEOPS_REDIS = { 'host': "redis://{}".format(os.environ.get("REDIS_LOCATION")), 'socket_timeout': 3, 'ssl': True, } -
Show values of last three months in columns and change column names to current month and of 2 months before
I have a csv file containing column names of the months. I made a dataframe (df24) containing the columns as followed: [['Januari','February', 'March','April','May','June', 'July','August','September','October','November','December']] I used dictionary to push the values to my frontend context['Table']= df24.to_numpy() My frontend html looks like this: <tr> <th>Current Month</th> {%comment%}Display name Current Month{%endcomment%} <th>Current Month-1</th> {%comment%}Display name Current Month-1{%endcomment%} <th>Current Month-2</th> {%comment%}Display name Current Month-2{%endcomment%} </tr> <tbody> {% for y in Table %} <tr> <td>{{ y.0 }}</td> {%comment%}Current Month{%endcomment%} <td>{{ y.1 }}</td> {%comment%}Current Month-1{%endcomment%} <td>{{ y.2 }}</td> {%comment%}Current Month-2{%endcomment%} </tr> {% endfor %} I want to display three columns with their corresponding values in the html above according to the current month, the month before current month and the month before that. It needs to keep 'moving'. Is it also possible to change the column names 'Current Month', 'Current Month-1', 'Current Month-2' to the actual current month name and current month-1 , -2?