Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer for JSONField nested representation
In my application there's a model that stores a configuration in one of it's fields. A field is defined as JSONField. I have a strict structure how content of this field should look like, but I'm struggling to find a way how to serialize it to validate data in API requests. The solution that works for now, but does not validate what's inside config_field and blindly accept anything that complies with being a json object: A simplified version of my model: class MyModel(models.Model): config_field = JSONField(...) ... For the sake of this question here's simplified version of data structure stored in config_field: {"some_config_int": 42, "some_config_vars": ["foo", "bar"]} And here's simplified version of my serializer: class MyModelSerializer(serializers.ModelSerializer): config_field = serializers.JSONField(required=False) class Meta: model = MyModel fields = ('config_field', ...) What I'd like to achieve though is have a serializer for nested representation (reference to DRF documentation) of what's inside config_field. What I've tried so far (but does not work): class ConfigFieldsSerializer(serializers.Serializer): some_config_int = serializers.IntegerField(required=True) some_config_vars = serializers.ListField(child=serializers.CharField(...), required=True) class MyModelSerializer(serializers.ModelSerializer): config_field = ConfigFieldsSerializer(required=False) class Meta: model = MyModel fields = ('config_field', ...) This way it will be optional to post/put object with configuration, but once config_field is in the body of … -
serialize django model queryset with serializers.serialize() function
How can I return JSON response of model queryset from a view using django serializer ? from django.core import serializers from django.http.response import JsonResponse def some_view(request): qs = SomeModel.objects.all() serialized_obj = serializers.serialize('json', qs) return JsonResponse(serialized_obj, safe=False) According to code snippet, the view producess a non-json response. -
Is there any problem with using django form just to do the validation on the server side?
Currently the app I'm developing uses html forms and validation is done with the required value attribute. That is to say, it validates in the frontend. However, I want to use django forms because I have heard that it is a safer way to validate information. Reviewing the documentation seems to be something complicated to render my forms through django forms, since my forms have quite a few peculiarities in terms of design. Considering the above, and that I already have the forms designed in html, I would like not to change them and only use django forms for validation on the server side. Is it possible to do this? Is it a bad idea? -
Django model with automatic username and data creating through factory
I want to create two new django models (clients and advisors) in my current app and create some test data with factory. The problem is that I can not define a user_name in my model consisting of first and last name (separated with a dot) automatically and don't know how to handle this variable in the factory setup. Additionally, I am not sure about how an advisor instance will know about all the clients they have. In the code, I have first the two class definitions and following the two factory classes for creating the sample data. From models.py file from django.db import models from django.utils import timezone import factory import factory.django class Client_Profile(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) advisor = models.ForeignKey("Advisor_Profile", null=True, on_delete=models.SET_NULL) def __str__(self): return f"{self.first_name} {self.last_name} Client Profile" def _get_user_name(self): return f"{self.first_name}.{self.last_name}" user_name = property(_get_user_name) class Advisor_Profile(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) user_name = models.CharField(max_length=255) def __str__(self): return f"{self.first_name} {self.last_name} Advisor Profile" def _get_user_name(self): return f"{self.first_name}.{self.last_name}" user_name = property(_get_user_name) class Advisor_Profile_Factory(factory.django.DjangoModelFactory): class Meta: model = Advisor_Profile first_name = factory.Faker("first_name") last_name = factory.Faker("last_name") user_name = f"{first_name}.{last_name}" class Client_Profile_Factory(factory.django.DjangoModelFactory): class Meta: model = Client_Profile first_name = factory.Faker("first_name") last_name = factory.Faker("last_name") user_name = f"{first_name}.{last_name}" advisor = factory.Iterator(Advisor_Profile.objects.all()) The … -
Django: How to attach a file without referencing a file destination?
I am looking to attach a file to an email which includes all the content a user inputs from a contact form. I currently refer a PDF which records their inputs, and I attach that PDF from a file destination. However, I do not know how to attach additional files which the user provides on the contact form. In this case, this is represented by "msg.attach_file(upload_file)." My thoughts are: Have the file be uploaded to a destination; however, it needs to renamed to a uniform name each time so I can refer to it during the attachment process (msg.attach_file). Figure out a way to use request.FILES to attach it immediately without having to worry about its file name or upload destination (I am not sure if msg.attach_file is a valid command for this method). Is there a right way to perform this action? I am attempting to perform method 2 with my views.py file which refers to my forms.py file, but it is giving me an error. Views.py def quote_req(request): submitted = False if request.method == 'POST': form = QuoteForm(request.POST, request.FILES) company = request.POST['company'] contact_person = request.POST['contact_person'] upload_file = request.FILES['upload_file'] description = 'You have received a sales contact form' if … -
How to split ldap parameter in Django
I mapping users with django ldap. It works but my ldap 'cn' parameter contains first name and last name. I would like to split it and property assign. ex.(cn:Adam Smith) Probably I should do in place where user is created. But I don't well know where exaclly is it. I try split in settings.py, but it's impossible or am I wrong ? AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'cn', } list=cn.split(' ') first_name = list[0] last_name = list[1] -
Why am I reaching my connection limit and timing out queries when I use Heroku-Redis for multithreading?
I'm hosting a Django web app on Heroku, and it uses Redis to run a task in the background (this gets kicked off by the user when they submit a form). The task often has to make multiple queries to an API using pexpect, sequentially. When I had it all set up locally, I had no problems with timeouts, but now I regularly run into two problems: TIMEOUT in the pexpect function and "max client connections reached". I'm using the free tier of Heroku-Redis, so my connection limit is 20. This should be more than enough for what I'm doing, but I notice on the Redis dashboard that when I run the program, the connections stay open for a while afterwards (which is what I suspect is causing the "max connections" error -- the old connections didn't close). I used heroku-redis on the command line to set it so idle connections should close after 15 seconds, but it doesn't seem like they are. I also should only have 4 concurrent connections at the same time (setting in Django settings.py), but I regularly have 15 or so spawned for a single run. How do I actually limit the number of redis … -
Efficient way to test logs with Django
In my Django files, I make some logging entries pretty simply this way: # myapp/view.py import logging logger = logging.getLogger(__name__) ... # somewhere in a method logger.warning("display some warning") Then, suppose I want to test that this warning is logged. In a test suite, I would normally do: # myapp/test_view.py ... # somewhere in a test class def test_logger(self): with self.assertLogs("myapp.view") as logger: # call the view self.assertListEqual(logger.output, [ "WARNING:myapp.view:display some warning" ]) This way, the output of the logger is silenced, and I can test it. This works fine when I run tests for this view only with: ./manage.py test myapp.test_view but not when I run all tests: ./manage.py test where I get this error: Traceback (most recent call last): File "/home/neraste/myproject/myapp/test_view.py", line 34, in test_logger # the call of the view AssertionError: no logs of level INFO or higher triggered on myapp.view So, what should I do? I can use unittest.mock.patch to mock the calls to logger but I find this way ugly, especially if you pass arguments to your logger. Moreover, assertLogs is simply designed for that, so I wonder what is wrong. -
Django runs many strange queries on the database
We had made a few changes on our Django website. After that, many strange queries are sent to our database in a short period of time (thousands of similar queries in a few seconds), for example: SELECT "core_base"."id", "core_base"."created_time", "core_base"."updated_time", "core_base"."delete_flag", "core_base"."child_name", "core_base"."creator_id", ............ FROM "core_base" WHERE ("core_base"."delete_flag" = false AND "core_base"."delete_flag" = false ...................................................... AND "core_base"."id" = 4682) I removed the AND "core_base"."delete_flag" = false which was repeated 450 times!!! We use Postgresql database. -
How to query through a Foreign key field inside django inline forms?
I have these models: class Purchase(models.Model): company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True) party_ac = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='partyledger') purchase = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='purchaseledger') total = models.DecimalField(max_digits=10,decimal_places=2,null=True,blank=True) class Stock_total(models.Model): company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True,blank=True) purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') total = models.DecimalField(max_digits=10,decimal_places=2,default=0.00,null=True,blank=True) This are my forms: class Purchase_form(forms.ModelForm): class Meta: model = Purchase fields = ('Company','Party_ac', 'purchase', 'sub_total') def __init__(self, *args, **kwargs): self.User = kwargs.pop('User', None) self.Company = kwargs.pop('Company', None) super(Purchase_form, self).__init__(*args, **kwargs) self.fields['party_ac'].queryset = Ledger1.objects.filter(Q(Company = self.Company) , Q(group1_Name__group_Name__icontains='Sundry Creditors') | Q(group1_Name__group_Name__icontains='Bank Accounts') | Q(group1_Name__group_Name__icontains='Cash-in-hand') | Q(group1_Name__Master__group_Name__icontains='Sundry Creditors') | Q(group1_Name__Master__group_Name__icontains='Bank Accounts') | Q(group1_Name__Master__group_Name__icontains='Cash-in-hand')) self.fields['party_ac'].widget.attrs = {'class': 'select2_demo_2 form-control',} self.fields['purchase'].queryset = ledger1.objects.filter(Q(Company = self.Company) ,Q(group1_Name__group_Name__icontains='Purchase Accounts') | Q(group1_Name__Master__group_Name__icontains='Purchase Accounts')) self.fields['purchase'].widget.attrs = {'class': 'select2_demo_2 form-control',} self.fields['total'].widget.attrs = {'class': 'form-control',} class Stock_Totalform(forms.ModelForm): class Meta: model = Stock_Total fields = ('stockitem', 'Total_p') def __init__(self, *args, **kwargs): super(Stock_Totalform, self).__init__(*args, **kwargs) self.fields['stockitem'].widget.attrs = {'class': 'select2_demo_2 form-control',} self.fields['total'].widget.attrs = {'class': 'form-control',} Purchase_formSet = inlineformset_factory(Purchase, Stock_Total, form=Stock_Totalform, extra=3) I want to perform a queryset method for stockitem field in Stock_Totalform which I will make specific to Company like I have done for Party_ac and purchase in Purchase_form above.. When I try to do the same for Stock_Totalform objects it gives me no result.. I tried like above doing: self.Company = kwargs.pop('Company', None) using the get_form_kwargs function in … -
Django pre_save signal called upon changes made to bridge table
Context I have the models AppVersion, App & DeployApp. In the AppVersion model users can upload APK files to the filesystem. I am using a pre_save signal to prevent uploading APK files with the same version_code for a specific App like this: @receiver(pre_save, sender=AppVersion) def prevent_duplicate_version_code(sender, instance, **kwargs): qs = AppVersion.objects.filter(app_uuid=instance.app_uuid, version_code=instance.version_code) if qs.exists(): raise FileExistsError("Version code has to be unique for a specific app") This signal does what I want, except it also raises the error when I am trying to create an object in the bridgetable DeployApp. Models # models.py class App(models.Model): app_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) app_name = models.CharField(max_length=100) class AppVersion(models.Model): app_version_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) app_uuid = models.ForeignKey(App, on_delete=models.CASCADE, related_name='app_versions') app_version_name = models.CharField(max_length=100) version_code = models.IntegerField(blank=True, null=True, editable=False) source = models.FileField(upload_to=get_app_path, storage=AppVersionSystemStorage()) class DeployApp(models.Model): deploy_app_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) app_version = models.ForeignKey(AppVersion, on_delete=models.CASCADE) device_group = models.ForeignKey(DeviceGroup, on_delete=models.CASCADE) release_date = UnixDateTimeField() My guess is that when creating an object of DeployApp the related AppVersion is also saved and thus the pre_save signal is called and raises the Exception. I also tried to override the save() method for the AppVersion model but the results are the same. How do I make sure that the Exception … -
Django Form Wizard with activation of forms through condition radio button
I'm using Django 2.17 and trying to implement a HTML Form that can change due a radio button selection. According with the choice a django form must be loaded. I've read about Django Formtools (https://swapps.com/blog/how-to-do-a-wizard-form/), it's something close, except the conditional clause that I want. It'll be 3 options, so 3 different Django Forms to my Views. The flux will be something like: Radio button choosing one of 3 options. HTML Table to one of the 3 Forms. Passing the data of the Form to another page. I've also read these: Branching with Django Form Wizard -> I don't want to redirect to another page. Django form wizard handling Django form wizard dispatcher -> This one seems close to what I want, but I'm confused if the first part of the code is in url.py or in view.py, as the first tutorial recommends. I guess it would be a first form just with the radio button, than the conditions to one of the other 3 Forms, as the third link suggest. But I'm stuck into the doubt that I've appointed. If possible, add codes as sample for a better understanding and explanation. Thanks in advance =) -
How to speed up fixture loading time on python unittests on macOS?
I had a couple of fixtures for a model, which has about 900 objects. While those objects were loaded from a couple of fixtures, tests were quite fast. But I had to split those fixtures into one fixture per object principle. And now, when I am loading all fixtures on tests, it takes about 40 secs on every setUp on macOS, but on Linux it didn't do significant difference on loading time. I have created a CoreBaseTestCase class which gets all fixtures from directory and puts it to variable, then it provides those fixtures names to fixtures variable. class CoreBaseTestCase(TestCase): core_fix_base_path = 'core/fixtures/' fiat_pairs_fixtures = ['pairs/fiat/' + f for f in os.listdir('core/fixtures/pairs/fiat')] crypto_pairs_fixtures = ['pairs/crypto/' + f for f in os.listdir('core/fixtures/pairs/crypto')] crypto_currency_fixtures = ['currencies/crypto/' + f for f in os.listdir('core/fixtures/currencies/crypto')] fiat_currency_fixtures = ['currencies/fiat/' + f for f in os.listdir('core/fixtures/currencies/fiat')] fixtures = \ ['country.json', 'market.json', 'currency_algorithm.json', 'transaction_price.json'] + \ crypto_currency_fixtures + \ fiat_currency_fixtures + \ crypto_pairs_fixtures + \ fiat_pairs_fixtures What could be the solution on shortening fixtures loading time on macOS? on macOS setUp takes 45.77s, on Linux setUp takes 7.4s For example, the test test_something would take 6 times more time on macOS than on Linux: class SomeTestCase(TestCase): fixtures = … -
How to rewrite data from a template in JSON?
I have this model: class Category(models.Model): name = models.CharField(max_length=150, unique=True) description = models.CharField(max_length=250) def get_absolute_url(self): return reverse('categories_url', args=[str(self.id)]) class Company(models.Model): name = models.CharField(max_length=150, unique=True) country = models.CharField(max_length=50) class Motobike(models.Model): name = models.CharField(max_length=150) company = models.ForeignKey('Company', on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.CASCADE) And in view i do so.. class CategoryView(DetailView): model = Category template_name = 'bikes_site/categories_detail.html' pk_url_kwarg = 'pk' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = self.get_object() context['motobikes'] = Motobike.objects.filter(category_id=category.pk) return context And display everythng in the template {% for motobike in motobikes %} <ul> <p> Name: {{ motobike.name }}</p> <p> Company: {{ company.name }}</p> <p> Category: {{ object.name }}</p> <p> Description: {{ object.description }} </p> </ul> {% endfor %} How to rewrite it to be displayed in JSON format(such task)? It's necessary through HttpResponse. Here's my test: client = Client() category_id = Category.objects.get(name='Мотоциклы').id response = client.get(f'/categories/{category_id}/') assert response.status_code == 200 response_data = json.loads(response.content.decode('utf-8')) assert len(response_data) == 2 assert response_data[1]['name'] == 'Ninja Turbo' assert response_data[1]['vendor'] == 'Kawasaki' assert response_data[1]['category'] == 'Мотоциклы' assert response_data[1]['description'] == '' How else to push the name of the company?? -
How can I test get request with curl on django?
I am trying to test if a get request works but I am not sure how to do it in django.I have postgre database connected to django server and I am trying to test if I can get a GET request to work but I can't find nothing specific on the internet. I have some experience with Flask testing apis but not with Django. views.py from django.contrib.auth.views import login_required from django.shortcuts import render from django.http import HttpResponse #from cameras.models import CameraQuerySet, Camera, CameraAuthenticationToken, CameraGroupQuerySet, CameraGroup, CameraStatusUpdate, CameraGroupLog from . import models #if not up @login_required def camera_lookup(request): serial_number = request.GET.get('serial_number') found = 0 if serial_number != None: serial_number = serial_number.lower() found = Camera.objects.filter(serial_number=serial_number).count() return HttpResponse(str(found), content_type="text/html", status=200) urls.py from . import views from django.urls import path app_name = 'cameras' urlpatterns = [ path('add/', views.add, name='add'), path(r'api/1.0/camera/', views.camera_lookup, name='camera_lookup'), models.py class Camera(TimeStampedModel): public_identifier = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) serial_number = models.CharField(max_length=100, unique=True, null=True) name = models.CharField(max_length=50, blank=True, null=True) group = models.ForeignKey('CameraGroup', on_delete=models.SET_NULL, null=True, related_name='cameras', related_query_name='cameras') group_tracker = FieldTracker(fields=('group',)) objects = CameraQuerySet.as_manager() #identifier from assembly (what parts does the camera consist of) bom = models.CharField(max_length=50, blank=True, null=True) #what firmware is the camera on (mender artifact name) firmware = models.CharField(max_length=50, blank=True, null=True) #last seen … -
How to run javascript scripts in a Django app on heroku
I am having trouble getting my app to work online. I am doing posts using javascript and while this is working on my machine, I cant get it to work in production on heroku. Basically I have a table with 10 rows, each row has columns for singer, song and a submit button. The javascript checks the row of the button that a user clicked to retrieve the corresponding singer and song. The following snippet is the javascript code that sends the post data to my app. I have left out a chunk of code that gets the singer,song and csrf token: <script> ... const params = { song: song, singer: singer, }; var xhttp =new XMLHttpRequest(); xhttp.open("POST","https://exampleapp.herokuapp.com/playlist",true); xhttp.setRequestHeader("X-CSRFToken", csrftoken); xhttp.send(JSON.stringify(params)); var t=xhttp.responseText; location.reload(true); }; </script> and the views.py function looks like this : def playlist(request): form = FormCreator(request.POST) if request.method=='POST': data=request.body data2=data.decode('latin-1') dicti=json.loads(data2) #Gets the genre of the song song_genres=genre_master(dicti) context= {'all_entries':song_genres} context['form']=form template=loader.get_template('index.html') return HttpResponse(template.render(context,request)) In settings.py ALLOWED_HOSTS = ["exampleapp.herokuapp.com",'localhost', '127.0.0.1'] And the app's urls.py looks like this: from django.urls import path,re_path from . import views urlpatterns=[ path('playlist/',views.playlist, name="playlist") ] I dont get an error on heroku and the page reloads accordingly after clicking a submit button due … -
Pytest object is not updated during action
My view user_actions allows to set an user inactive. Here is how: def user_details_actions(request, username=None): user = get_object_or_404(User, username=username) if 'set_inactive' in request.POST: user.is_active = False user.save() return redirect(reverse('dashboard_staff:user_details', kwargs={'username': username})) I use quite often this straightforward pattern and it works fine. I'd like to test it now. My user test is created as following. @pytest.fixture def user(db) -> settings.AUTH_USER_MODEL: return UserFactory() and the factory class: class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") first_name = Faker("first_name") last_name = Faker("last_name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).generate(extra_kwargs={}) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] Here is the test that fails: class TestUserActions: url = "dashboard_staff:user_actions" def test_set_user_inactive(self, staff_client, user): assert user.is_active url = reverse(self.url, kwargs={'username': user.username}) resp = Client().post(url, data={'set_inactive': ''}, follow=True) assert resp.status_code == 200 assert user.is_active is False and the exception: assert customer_manager.is_active E assert False E + where False = .is_active -
Designing Django models for questions to have different answer types
I am create a survey app that I want to be fully dynamic the Quiz model will have many to many relationship with the Question model for a Survey can have multiple questions and the question can be used in multiple survey. My problem is the Answers model for questions. I want to allow different types of answers like (multiple choice or essay or whatever other type) but for each Quiz the question will have only one answer type thats related to it. what can I design that ? -
timedelta.seconds is returning a wrong value
I need to get time difference in seconds .But my function returns huge values ,which I assume are microseconds. When I try to put days, I get -1 value.Can someone tell me how to get the difference in seconds.Thank You from datetime import datetime, date, time, timedelta time_now2 = datetime.strptime(time_now, "%Y-%m-%d %H:%M:%S.%f") lt2 = datetime.strptime(LT, "%Y-%m-%d %H:%M:%S.%f") ftime = lt2 + timedelta(seconds=1200) waiting_time = (time_now2 - ftime).seconds -
How to fix 'TypeError: write() argument must be str, not dict' in Django
i setup webhook for payments using stripe. But i always get 500 error anytime i test.Below are the code and error @csrf_exempt def check_subscription_status(request): data = """ PASTE COPIED JSON REQUEST HERE """ if request.method == "POST": event_json = json.loads(request.body) jsonObject = event_json try: output = open("home/check_subscription.html", "w") output.write(jsonObject) output.close() except IOError: pass subscription_id = jsonObject['data']['object']['subscription'] customer_id = jsonObject['data']['object']['customer'] amount = jsonObject['data']['object']['amount_paid'] / 100 types = jsonObject['type'] customersubscription = UserOrder.objects.get(order_id=customer_id, subscription= subscription_id) if types == 'customer.subscription.deleted' and customer_id: if customersubscription: customersubscription.status = "inactive/deleted" customersubscription.save() billing = BillingHistory(user=customersubscription.user, amount=amount, subscription_id=subscription_id, status="inactive/deleted") billing.save() user = CustomUser.objects.get(email=customersubscription.user.email) user.role = 6 user.save() elif types == 'invoice.payment_failed' and customer_id: if customersubscription: customersubscription.status = "failed" customersubscription.save() billing = BillingHistory(user=customersubscription.user, amount=amount, subscription_id=subscription_id, status="Failed") billing.save() user = CustomUser.objects.get(email=customersubscription.user.email) user.role = 6 user.save() elif types == 'invoice.payment_succeeded' and customer_id: if customersubscription: customersubscription.status = "success" customersubscription.save() billing = BillingHistory(user=customersubscription.user, amount=amount, subscription_id=subscription_id, status="success") billing.save() user = CustomUser.objects.get(email=customersubscription.user.email) user.role = 3 user.save() #Record time of response from webhook try: tryf = TryFreeRecord.objects.get(user=user) tryf.webhook_response = datetime.now() tryf.save(update_fields=['webhook_response']) except TryFreeRecord.DoesNotExist: pass return HttpResponse(status=200) return HttpResponse(status=200) then i get this error: Traceback (most recent call last): File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) … -
csv error while uploading file in django admin
I'm uploading a file via admin and I'm doing a small cleaning and saving the data in the Model. So in utils I have a small function def _map_file_to_model(row): _into_product = { "qr_id": "", "ean": "", "description": "", "category": "", "marketing_text": "", "bullet": "", "brand_image": "", "image": "" } return { _into_product[key]: value for key, value in row.items() } this is a representation of the model. In the admin I'm doing this @admin.register(Product) class ProductAdmin(admin.ModelAdmin): change_list_template = 'product/products_blob.html' date_hierarchy = 'created_at' def get_urls(self): urls = super().get_urls() qr_urls = [ path('import-file/', self.import_file, name='import-file'), ] return qr_urls + urls def import_file(self, request): if request.method == "POST": _file = request.FILES['text_file'] reader = csv.reader(_file) self.message_user(request, "You're text file has been imported") _read_file = [_map_file_to_model(row) for row in reader] _product_model = _read_file Product.objects.bulk_create([ Product(**data) for data in _product_model ]) form = QrImportForm() payload = {"form": form} return render( request, 'product/text_form.html', payload ) and the complete Traceback Traceback: File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/copser/Documents/Project/qr-backend/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/contextlib.py" in inner 74. return func(*args, **kwds) File "/home/copser/Documents/Project/qr-backend/server/products/admin.py" in import_file 36. _read_file = [_map_file_to_model(row) for row in reader] File … -
What Does This Error On docker-compose mean while building for Django?
Below is docker-compose.yml file and when I run docker-compose up I get the following error. ERROR: The Compose file './docker-compose.yml' is invalid because: Unsupported config option for services: 'app' -
Django Project: Logic for manipulating text input in a browser - where could it go?
In relation to form input (e.g a user types in a message in a form text box), does all the logic pertaining to manipulating the text input always have to go in the html page (using Django Templating Language) or is it possible to somehow create the project such that Django templating langauge is used as little as possible and the logic can be written in python itself (e.g in models, forms or views or in another file) I suppose my question is relating to how little Python actually appears to being used (for the actual logic) when using Django and the fact that Python programmers start to use Django, only to learn they have to learn and use DTL far more for the logic than anything else. In this specific example, could someone explain where the logic would go, and if there are different ways of 'writing' this logic (e.g is it possible for it not to be created in the html page using Django Templating language). Example: Enter your hobbies/interests: _______________________________ *User enters a sentence. *The user's input is checked against an array (1. where could the array go assuming it is hard coded and not being drawn … -
Where do I put my Django root dir in my Linux VPS
I have a VPS on which runs Apache. I created a simple html file just to test if my domain works on the internet and it works. This file is : /var/www/html/index.html But now I want to replace this by Django directories structure. Should I go in /var/www/html then run django-admin startproject projectname ? I also would like to notice that I code the site on my laptop, not directly in the vps, so I host all the code on GitLab then I clone it from my vps, is it a good practice ? -
Render additional forms in admin change_form with defined model_form
We are trying to build a custom workflow for comparing entries of a database with the help of django-admin and the django-admin-json-editor. While it was easy to get one form running, we do not really know how to render a second form with the same layout, but different queryset-object. We already added the content of the second query into the extra_content of our admin models change_view function def change_view(self, request, object_id, form_url='', extra_context=None): chosen_object = Community.objects.get(pk=object_id) updated_object = Community.objects.get(community_id=chosen_object.community_id, community_updated=True) extra_context = extra_context or {} extra_context['community_data_queryobject'] = updated_object extra_context['community_update'] = updated_object.community_updated return super().change_view( request, object_id, form_url, extra_context=extra_context, ) We are using a custom change_form.html template where we can see our extra_context - but we don't have any real clue in which place we should create the second form using the model/widgets for the data in a proper way. The form: class CommunityForm(ModelForm): class Meta: model = Community fields = '__all__' widgets = { 'president': JSONEditorWidget(person_schema.person_schema, editor_options=options), 'directorate': JSONEditorWidget(person_schema.person_schema, editor_options=options), 'synagogue': JSONEditorWidget(synagoge_schema.synagogue_schema, editor_options=options), 'rabbi': JSONEditorWidget(rabbi_schema.rabbi_schema, editor_options=options), }