Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Image upload issue Cloundinary
i'm learning Django at present and just about getting to the deployment stage at hit a problem serving static/media with Cloudinary, following guides how to do this, it seems straight forward enough. I've checked the Cloudinary support but I can't find anything to help, just wondering if anyone has any input. The problem I have is that I am using Exiffield (to get image info) and ImageSpecField from ImageKit to resize the images for thumbnails and I think this is giving me problems with Cloudinary. Firstly I can't upload images from Admin, I get a Exception Value:Empty file error. Secondly I get 400 Client Error: Bad Request for url: https://res.cloudinary.com/ **path to file*** when trying to open my site (which is being served locally and in development This is using ImageField as upload. I would change it to CloudinaryField but my model heavily relies on ExifField which wont read from it. Model below. image = models.ImageField(upload_to='images') mid_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(220, 150)], format='JPEG', options={'quality': 100}) gallery_thumbnail = ImageSpecField(source='image', processors=[ResizeToFit(300, 250)], format='JPEG', options={'quality': 100}) gallery_detail = ImageSpecField(source='image', processors=[ResizeToFit(1000, 850)], format='JPEG', options={'quality': 100}) title = models.CharField(max_length=100) albums = models.ManyToManyField(Album, blank=True, related_name='photos') feature_image = models.BooleanField(default=False) description = models.CharField(editable=False, max_length=150, blank=True) posts = models.ManyToManyField(Post, blank=True, … -
Django - Paypal Cancel Suscription
I recently used the django-paypal library in my project. All is working fine, the only problem I'm facing is that I don't find the way to implement a cancel button (to cancel a suscription) or an upgrade button (to change the suscription plan). There is no mention of those buttons in the documentation, so I guess I'm asking this question here to confirm that it can't be achieved with the django-paypal library -
Django IndexError: list index out of range error
I am trying out this code i found online. When i tried commands like runserver, migrate and make migrations. All of them showed this error Traceback (most recent call last): File "C:\Django\OLD\ToDo_Application-master\ToDo_Application-master\todos\views.py", line 129, in check_time task() File "C:\Django\OLD\ToDo_Application-master\ToDo_Application-master\todos\views.py", line 155, in is_expired if splited_notification_time[1] == "minutes": IndexError: list index out of range CODE OF is_expired : def is_expired(): connection = sqlite3.connect('db.sqlite3') cursor = connection.cursor() cursor.execute( " SELECT * FROM todos_todo where email_notification != '' AND notification_time != 'None' AND sent_reminder == 'False' ") rows = cursor.fetchall() todo_notify_time = 0 for row in rows: todo_item_id = row[0] due_date_in_ms = int(datetime.fromisoformat(row[3]).timestamp() * 1000) current_date = int(datetime.now().timestamp() * 1000) splited_notification_time = str(row[6]).split(" ") receiver_email = row[5] sent_reminder = row[7] date_in_pst = due_date_in_ms - (7 * 60 * 60 * 1000) time_remaining = date_in_pst - current_date if splited_notification_time[0] != "None": if splited_notification_time[1] == "minutes": todo_notify_time = int( (splited_notification_time[0])) * 60 * 1000 elif splited_notification_time[1] == "hours": todo_notify_time = int( (splited_notification_time[0])) * 60 * 60 * 1000 elif splited_notification_time[1] == "day": todo_notify_time = int( (splited_notification_time[0])) * 60 * 60 * 24 * 1000 if time_remaining <= todo_notify_time: todo_item_expire = "Your todo_item name - " + \ str(row[1]) + " will expire in " + … -
Make select field toggle another field using Django Forms WITHOUT jQuery
How can I create a toggling behavior using Django form fields such as shown in the gif purely using Django? In the example below the user is prompted to choose only a Division or Center, if the division is chosen, center will automatically be prompted to None and vice versa. In order to create the effect shown, I am using jQuery and some beginner Django code: <div class="col-md-5"> <label>Division </label> <select id="division" name="division" class="form-control select2"> {%for division, name in divisions%} <option value="{{ division }}">{{ name }}</option> {% endfor %} </select> </div> <div class="col"> <h3><strong>OR</strong></h3> </div> <div class="col-md-5"> <label>Center</label> <select id="center" name="center" class="form-control select2"> {%for center, name in centers%} <option value="{{ center }}">{{ name }}</option> {% endfor %} </select> </div> $(document).ready(function () { // Set option selected onchange $("#center").change(function () { // Set selected if ($("#division").val() != "None" && $("#center").val() != "None") { $("#division").val("None"); $("#division").select2().trigger("change"); } return; }); $("#division").change(function () { // Set selected if ($("#division").val() != "None" && $("#center").val() != "None") { $("#center").val("None"); $("#center").select2().trigger("change"); } return; }); }); However the rest of my fields are declared using django forms: class NewTitlesForm07(forms.Form): def __init__(self, *args, **kwargs): super(NewTitlesForm07, self).__init__(*args, **kwargs) self.fields['start_month'] = forms.ChoiceField(choices=MONTH_CHOICES, widget=forms.Select(attrs={'class': 'select2 form-control'})) self.fields['start_year'] = forms.ChoiceField(choices=YEAR_CHOICES_07, widget=forms.Select(attrs={'class': 'select2 form-control'})) … -
Set value of GeoDjango map widget in change form based on other field using jQuery
I'm working on a project that uses GeoDjango and django-cities. I have one model: class Site(models.Model): name = models.CharField(max_length=60) assigned_to = models.ForeignKey( to=User, on_delete=models.PROTECT, null=True, blank=True ) country = models.ForeignKey( to=Country, on_delete=models.PROTECT, null=True, blank=True ) # Region selection should be limited to country region = ChainedForeignKey( to=Region, chained_field="country", chained_model_field="country", on_delete=models.PROTECT, null=True, blank=True, ) # City selection should be limited to region city = ChainedForeignKey( to=City, chained_field="region", chained_model_field="region", on_delete=models.PROTECT, null=True, blank=True, ) location = PointField(null=True, blank=True) This is the planned workflow: User sets the country of the site User sets the region of the site (selection is limited by country) User sets the city of the site (selection is limited by region) When the city changes, the point on the map widget for the location field jumps to the location of the city The user then fine-tunes the location manually and saves In order to achieve this, I have added this js file using the Media class in SiteAdmin: $(document).ready(function() { $("select[name='city']").change(function(e) { const cityId = e.target.value geodjango_location.clearFeatures() // Get the location of the selected city $.ajax({ "type" : "GET", "url" : `/sites/admin/city-location/${cityId}/`, "dataType" : "json", "cache" : false, "success" : function(json) { // Use the city's location as the value … -
Processing a Django form
I have a problem using Django forms while learning Django and adapting code from a variety of online courses and examples. As a result, the code may be “messy” – but if I can get it to work the way I need, I can improve my coding style later. I wish to display a template that contains a form. Some of the data displayed in the page rendered in the template is read from one table/model, polls_CC_Questions, and I wish to write data input in the page into a related table, polls_CC_Resp_NoFK. The models used are: class CC_Questions(models.Model): q_text = models.CharField('Question text', max_length=200) C1_Type = models.CharField('Choice 1 Type', max_length=2) Choice1_text = models.CharField('Choice 1 text', max_length=100) C2_Type = models.CharField('Choice 2 Type', max_length=2) Choice2_text = models.CharField('Choice 2 text', max_length=100) # def __str__(self): return self.q_text[:20] class CC_Resp_NoFK(models.Model): Person_ID = models.IntegerField() Test_date = models.DateTimeField('date test taken') Q_ID = models.IntegerField() Response_value = models.IntegerField(default=0, validators=[MaxValueValidator(100), MinValueValidator(-100)]) # def __str__(self): return self.Person_ID Now I can display the template containing valid data when I enter the url: http://localhost:8000/polls/p2vote/4/ This is processed in urls.py app_name = 'polls' urlpatterns = [ ….. …… # ex: /polls/p2vote/<q_id> path('p2vote/<int:q_id>/', p2_views.p2vote, name='p2vote'), ….. The views.py entry that is used: def p2vote(request,q_id): #next line … -
How to check if the Django-background process is running in server?
The command to start the background process is, nohup python manage.py process_tasks & Similarly in Linux which is the command used to check running status? -
Django static file images not displayed on IBM Cloud Foundry
I've read some other threads, googled, and tried reading docs but can't find what I'm looking for. I am new to playing with Django, fyi. This same code runs alright on my local and also on pythonanywhere.com My web app displays a list of 'interests', 'images', and a 'urls'. The 'image' is actually a path to the local image file. The app deploys fine to IBM Cloud Foundry and works, except that the images in static files do not display only the broken image icon displays. When I deploy, I see in the logs the message "153 static files copied to '/tmp/app/static'" which leads me to believe the collectstatic ran without issue. from models.py: class Interest(models.Model): interest = models.CharField(max_length=100) **image = models.ImageField(upload_to='interest/images')** url = models.URLField(blank=True) def __str__(self): return self.interest From the html template: {% extends 'portfolio/base.html' %} {% block about-class %} about-color-class {% endblock %} {% block content %} {% load static %} <!-- Interests --> <section class="interests"> <div class="container"> <div class="row"> <h1>Some of my interests...</h1> </div> <div class="row-images"> {% for interest in interests %} <div class="col-lg-1 col-md-1 col-xs-1"> <a href="{{ interest.url }}"><**img src="{{ interest.image.url }}" alt=""**></a> </div> {% endfor %} </div> </div> </section> <!-- Interests End --> From settings.py: … -
Django REST framework - How i can unittest model serializer?
can anybody help. I really can't figure out how to test my model seriazlier. I'm using ModelViewSet. Cant find any information in google. tests where i'm trying to test serializer def test_company_serializer(self): self.user1 = User.objects.create_user( username='user1', password='password', ) self.user2 = User.objects.create_user( username='user2', password='password', ) serializer_data = CompanySerializer(self.company1, self.company2, many=True).data expected_data = [ {'name': 'test_company1', 'owner': 'user1'}, {'name': 'test_company2', 'owner': 'user2'}, ] self.assertEqual(serializer_data, expected_data) asserterror looks like this AssertionError: When a serializer is passed a `data` keyword argument you must call `.is_valid()` before attempting to access the serialized `.data` representation. You should either call `.is_valid()` first, or access `.initial_data` instead. models.py class Company(models.Model): name = models.CharField(max_length=255, unique=True, help_text='Название') owner = models.OneToOneField(User, on_delete=models.CASCADE, help_text='Владелец') created = models.DateTimeField(auto_now_add=True, help_text='дата регистрации компании') slug = models.SlugField( max_length=255, unique_for_date='created', blank=True, validators=[validate_slug] ) class Meta: ordering = ['-created'] verbose_name_plural = 'Companies' def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Company, self).save(*args, **kwargs) serializers.py class CompanySerializer(serializers.ModelSerializer): medicines = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='medicine-detail', ) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Company fields = ( 'url', 'pk', 'name', 'owner', 'created', 'medicines', ) -
Python/Django json.loads() error when loading JSON File
In my Django project I have the following directory structure: project/build/contracts/MyFile.json And I am writing code in the following directory project/homeapp/views.py In my views.py I have the following code: with open("../build/contracts/MyFile.json", "r") as f: data = json.loads(f.read()) abi = data["abi"] When I try to python manage.py runserver I get the following error: The strange part is that I couldn't figure out what was wrong so I made a viewstest.py and placed the exact same code in it. When I run it with python .\viewstest.py and print the JSON to console, it works perfectly fine. I even tried importing the abi variable from viewstest.py to views.py but got the same error. So I assume that it is an error relating to Django, but I can't seem to figure it out. Thanks! -
Is Django a good framework for microservice?
Microservices architecture has multiple microservices running. Is Django a good choice for implementing a microservice? I am not concerned about how microservices will talk to each other. I am just concerned about the choice of framework for implementing a microservice. -
Postgres data base engine value
Hi there is a full full traceback error that told to supply engine value to postgres data base main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Users/dmitry_tok/Desktop/Projects/foodgram-project-react/venv/lib/python3.8/site-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Im try to switch my SQlite3 data base to postgres There is a settings.py: 'default': { 'ENGINE': os.getenv('DB_ENGINE'), 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('POSTGRES_USER'), 'PASSWORD': os.getenv('POSTGRES_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT') } } the .env file: DB_ENGINE=django.db.backends.postgresql … -
cudart64_110.dll Loading Multiple Times
I am working on a Django Web Application that uses Tensorflow for some image processing on the backend. As such I have installed CUDA and when I run the web application initially it loads the cudart64_110.dll and provides the following message, which is fine. tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cudart64_110.dll Within my application I have a Pool.map function for multiprocessing (which is not related to the tensorflow processing, but only to generate some jpegs) as below: pool = Pool(4) pool.map(func_star, zip(index_arr, nrrd_path_arr, user_path_arr, g_img_arr, g_contour_arr, itertools.repeat(results))) The issue I am facing is that whenever this function runs, it also loads the cudart64_110.dll corresponding to the number of processes that I specify in the Pool(x). In the above instance it loads the .dll 4 times as below: This leads to memory issues and crashes the app. I am not entirely sure why this is happening or how can I approach about solving this issue. Any help on how can I avoid this issue would be really appreciated! -
How to make post form like twitter in django?
It is very simple to create a post form which takes text, images and gif, but I need to make it dynamic like twitter. twitter can take number of images at once and can display them line by line as the user posted them (ordered). -
KeyError at /report_save django
I have an issue when trying to save data to model I have a code that seperate number by comma. If I type number < 1000, I can save data and type of the field is int. If the number >=1000, I cannot save data to model and the error appears the error This is my code in my views: form=AddReportForm(request.POST) if form.is_valid(): so_tien=form.cleaned_data["so_tien"] dien_thoai=form.cleaned_data["dien_thoai"] daily_report=report(so_tien=so_tien,dien_thoai=dien_thoai) daily_report.save() return HttpResponseRedirect(reverse('chi_tiet_hop_dong', kwargs={'so_hd': so_hd})) my js code to seperate number in my template: <script language="JavaScript"> function numberWithCommas(){ var input = document.getElementById('{{ form.so_tien.id_for_label}}'); input.value = parseInt(input.value).toLocaleString() } </script> my template: <div class="form-group row"> <div class="col-md-4">Số tiền</div> <div class="col-md-4">{{ form.so_tien }}</div> </div> my form: so_tien=forms.IntegerField(label="Số tiền",widget=forms.TextInput(attrs={"class":"form-control", 'onfocusout': 'numberWithCommas()',}),required=False) dien_thoai=forms.CharField(label="Điện thoại",max_length=12, widget=forms.TextInput(attrs={"class":"form-control"})) Please help me solve the issue -
How to render python dictionary values in Javascript Fetch API (forEach)?
I am trying to render python dictionary values inside a Javascript Fetch API. I tried various ways to do so such as serializing values and using dictionary keys to access the dictionary values. I got no error message but the values I rendered are all "undefined" on my webpage. Python def portfolio_position(request): positions = Portfolio.objects.filter(owner=request.user, off_portfolio=False).order_by('-symbol').values() return JsonResponse([position for position in positions], safe=False) Javascript function load_portfolio_position() { fetch('/portfolio_position') .then(response => response.json()) .then(positions => { console.log(positions); var table = document.getElementById("portfolio-table"); positions.forEach(position => { var row = table.insertRow(1); row.id = `row_${position.symbol}`; var symbol = row.insertCell(0); var price = row.insertCell(1); var change = row.insertCell(2); var average_cost = row.insertCell(3); var position = row.insertCell(4); var pnl = row.insertCell(5); var pnl_percent = row.insertCell(6); symbol.innerHTML = `${position.symbol}`; price.innerHTML = `${position.price}`; change.innerHTML = `${position.change}`; var avc = parseFloat(position.cost).toFixed(3); average_cost.innerHTML = `${avc}`; position.innerHTML = `${position.position}`; pnl.innerHTML = `${position.pnl}`; pnl_percent.innerHTML = `${position.pnl_percent}`; }); }) } This is the dictionary with values from console log This is the undefined result I got in my webpage Appreciate your help! -
How to sum queryset elements in forloop in django template
I have a problem inside a django template. Basically, what I'd like to achieve is this kind of table: Below each column where there is Absent or present I'd like to sum the duration. The total duration is on the rightmost column but I'd like to have filtered, student per student, each duration. To better explain myself, Student A and Student D, in this example, should have printed 5:00. I post some code here: models.py class Attendance(models.Model): course = models.ForeignKey( TheoryCourse, on_delete=models.DO_NOTHING, null=True, blank=True) instructor = models.ForeignKey( Instructor, on_delete=models.DO_NOTHING, null=True, blank=True) subject = models.ForeignKey( Subject, on_delete=models.DO_NOTHING, null=True, blank=True) date = models.DateField(blank=True, null=True) start_time = models.TimeField(blank=True, null=True) end_time = models.TimeField(blank=True, null=True) learning_objectives = models.TextField(null=True, blank=True) duration = models.TimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class AttendanceReport(models.Model): attendance = models.ForeignKey(Attendance, on_delete=models.CASCADE) presence = models.CharField(max_length=100, null=True, blank=True) student = models.ForeignKey(Student, on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField() fiscal_code = models.CharField(max_length=50) phone = models.CharField(max_length=50) license = models.ForeignKey( License, on_delete=models.PROTECT, blank=True, null=True) picture = models.ImageField( blank=True, null=True, default='default.png') id_card = models.ForeignKey( IDCard, on_delete=models.PROTECT, blank=True, null=True) address = models.CharField(max_length=100) cap = models.CharField(max_length=10) city = models.CharField(max_length=100) province = models.CharField(max_length=100) country = … -
Django-Import-Export Customize admin import forms
I want to add an additional field to my Import-Form on the Admin page. I did everything the Docs say but when the entered values for year and calender_week wont show up. resources.py class ForecastListResource(resources.ModelResource): year = fields.Field(column_name="Jahr", attribute="year") calender_week = fields.Field(column_name="Kalenderwoche", attribute="calender_week") brand = fields.Field(column_name="Marke", attribute="brand") material = fields.Field(column_name="Material", attribute="material") material_short_text = fields.Field(column_name="Materialkurztext", attribute="material_short_text") gmc = fields.Field(column_name="GMC", attribute="gmc") gmc_text = fields.Field(column_name="GMC Text", attribute="gmc_text") bed_date = fields.Field(column_name="BedTermin", attribute="bed_date") bed_amount = fields.Field(column_name="BedMenge", attribute="bed_amount") bed_week = fields.Field(column_name="BedWoche", attribute="bed_week") code_last_bed_week = fields.Field(column_name="Code letzte KW", attribute="code_last_bed_week") fabric_number = fields.Field(column_name="Stoffnummer", attribute="fabric_number") print_stage_3 = fields.Field(column_name="Druckstufe 3", attribute="print_stage_3") average_filling = fields.Field(column_name="Mittelwert Abfüllung", attribute="average_filling") net = fields.Field(column_name="Netto", attribute="net") class Meta: model = ForeCastList use_bulk = True skip_unchanged = True forms.py class ForecastDoDImportFormMixin(forms.Form): calender_week = forms.IntegerField(label="Kalenderwoche", required=True) year = forms.IntegerField(label="Jahr", required=True) class ForecastDoDImportForm(ForecastDoDImportFormMixin, ImportForm): pass class ForecastDoDConfirmImportForm(ForecastDoDImportFormMixin, ConfirmImportForm): pass admin.py @admin.register(ForeCastList) class ForeCastList(ImportExportModelAdmin): resource_class = ForecastListResource def get_import_form(self): return ForecastDoDImportForm def get_confirm_import_form(self): return ForecastDoDConfirmImportForm def get_form_kwargs(self, form, *args, **kwargs): if isinstance(form, ForecastDoDImportForm): if form.is_valid(): kwargs.update({"calender_week": form.cleaned_data["calender_week"], "year": form.cleaned_data["year"]}) return kwargs def get_import_data_kwargs(self, request, *args, **kwargs): print(kwargs) return super().get_import_data_kwargs(request, *args, **kwargs) Import-Form Result -> related Part from the Doc´s: https://django-import-export.readthedocs.io/en/latest/getting_started.html#customize-admin-import-forms -
Django can't find templates with jinja2 engine
I'm going to change django's template engines to jinja2, but after setting the setting.py of my project, jinja2 engines doesn't work, the followings are my codes. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [ BASE_DIR / 'templates', ], 'APP_DIRS':True, 'OPTIONS':{ 'environment':'emotion.jinja2.environment', } }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] the following is jinja2.py jinja2.py def environment(**options): env = Environment(**options) env.globals.update( { 'static':static, 'url':reverse, } ) return env But while I runserver, it seems like jinja2 doesn't work. jinja2 doesn't search the file I want. Debug result The django engine is perfect work but I change the file name to test where it search. While I rename it back to correct name, django's engine work, jinja2 doesn't. My project name is 'emotion', which has a app name catalog. html's path is emotion/catalog/templates/catalog/jinja.html -
A simple tool that allows users to generate a PDF by entering data into a form using django
A simple tool that allows users to generate a PDF by entering data into a form On the front end, the user enters the following details:- a. Seller name, phone and address b. Buyer name, name and address c. Individual items (along with price, tax and quantity) On submitting, The system should generate a pdf invoice based on the above information (Template at the bottom) Optional requirements (Will get more marks if these methods are used) Create a REST API that takes the above data as input and generates invoices. You can use the Django REST framework to expose the API Create a simple front-end that consumes that above API. The front-end should be mobile responsive. Technology Backend a. Django and Django REST Framework Frontend (Any technology: Web or Mobile) a. The candidate can use any technology like Angular etc. b. The candidate can also make a frontend in Django, making it mobile responsive with a toolkit like bootstrap, materialize, foundation etc. c. The candidate can also use mobile technologies like ReactNative, Ionic, Native Android, Flutter etc. -
redirect to routes that has the same url in multiple apps
I'm new to coding so excuse me if this was a silly question but I couldn't find a clear answer anywhere. So I have a django project with two apps inside it, both of them has the root '/',what is the exact format and implementation to use return redirect('/')to let django differentiate between these two roots in different apps maybe using naming routes. a step by step guide will be appreciated, thank you in advance. -
Django REST get() returned more than one object
I'm trying to use nested serializers to get a response which includes fields from two models. However i get this error get() returned more than one Location -- it returned more than 20! When looking for a solution it seems that this error comes up when using get but in my view i use filter instead. I am trying to understand what part of the code causes the error. Models.py class Microcontrollers(models.Model): name = models.CharField(max_length=25) serial_number = models.CharField(max_length=20, blank=True, null=True) type = models.CharField(max_length=15, blank=True, null=True) software = models.CharField(max_length=20, blank=True, null=True) version = models.CharField(max_length=5, blank=True, null=True) date_installed = models.DateField(blank=True, null=True) date_battery_last_replaced = models.DateField(blank=True, null=True) source = models.CharField(max_length=10, blank=True, null=True) friendly_name = models.CharField(max_length=45, blank=True, null=True) private = models.IntegerField() datetime_updated = models.DateTimeField(db_column='DateTime_Updated') # Field name made lowercase. class Meta: managed = True db_table = 'microcontrollers' verbose_name_plural = "Microcontrollers" def __str__(self): return self.friendly_name class StationStatus(models.Model): microcontroller = models.ForeignKey(Microcontrollers, models.DO_NOTHING) date_from = models.DateField() date_to = models.DateField(blank=True, null=True) location = models.CharField(max_length=45) active = models.IntegerField() notes = models.CharField(max_length=100, blank=True, null=True) datetime_updated = models.DateTimeField(db_column='DateTime_Updated') # Field name made lowercase. class Meta: managed = True db_table = 'station_status' verbose_name_plural = 'Station Status' Serializers.py class StationInfoSerializer(serializers.ModelSerializer): def create(self, validated_data): pass def update(self, instance, validated_data): pass class Meta: model = StationStatus … -
Choices in django form
in my form i want to select department from 2 options: some object(every time only one) and None. my form.py class TeamGoalForm(ModelForm): def __init__(self, *args, **kwargs): employees = kwargs.pop('employees') department = kwargs.pop('department') super().__init__(*args, **kwargs) self.fields['employees'].queryset = employees #self.fields['department'].choices = [(1, department), (2, None)] #self.fields['department'].initial = [1] class Meta: model = TeamGoal fields = ('team_goal_title','department','employees', 'team_goal_description', 'gpd_year','team_factor_0','team_factor_1','team_factor_2','team_factor_3','team_factor_weight') widgets = { 'team_goal_title': forms.TextInput (attrs={'class':'form-control', 'placeholder':'Enter the title of goal'}), 'department': forms.Select (attrs={'class': 'form-control', 'placeholder':'Select department'}), } in my view.py I have had: if request.method == 'POST': form = TeamGoalForm(request.POST, employees=employees, department=department) if form.is_valid(): form.save() Here my department is an object. How to implement something like this, 'cos my solution does't work? -
django-rest-framework speed-up endpoint with http requests
I have an application on DRF and there is an endpoint inside which sends an http requests in the loop for each item. Endpoint is very slow because of this, any ideas how to speed it up? example of code class MyView(APIView): def get(self, request: Request) -> Response: for cat in Cats.objects.all(): data = CatsInfoService.get_info(cat) # send http request return Response({"message": "ok"}) -
django form data to pdf or A4 paper
Is it possible to design an A4 paper and create a form in which the user fills in information in the form on the site and django converts the information to the paper that you designed previously and prints it?