Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access data from second external SQLite database in Django
This is my project structure I am able to access the default SQLite database db.sqlite3 created by Django, by importing the models directly inside of my views files Like - from basic.models import table1 Now, I have another Database called UTF.db which is created by someone else, and I want to access it's data and perform normal QuerySet operations on the retrieved data The problem is I don't know how to import the tables inside that database, as they are not inside any model file inside my project as it's created by someone else I tried adding the tables inside the UTF.db database to a models.py file by first adding it to the settings.py file like the following DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'otherdb':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'UTF.db', } } And then using the inspectdb command to add the tables to an existing models.py file The command I tried out - python manage.py inspectdb > models.py But, that just causes my models.py file to get emptied out Does anyone know how this can be solved? In the end, I wish to import the table data inside of my views files by … -
how to get single query set from three different models using Django..?
I have two models A and B which having many to many relation and form third model E with extra attributes . so i want to perform following sql query using Django ORM : select * from A , B , E where A.id = E.id and B.id = E.id and A.id = '107'; how i can do..? *I try this A.objects().filter(e__aid=107) it gives me only content from A model.* Please Help..! -
upload images issue. While uploading an image taking only image name but not the images how to solve this problem
By using Vuejs, Axios and Django, we're uploading "multiple images" using Vuejs form in one upload/browse attempt. After uploading, the images are getting in a list and then the list of images names are stored into backend in ImageField. The image names are saving into database but not saving into Media Folder. Here is snippet of the code. Vuejs <label> <span>Files</span> <input type="file" multiple @change="handleFileUploads($event)" /> <ul v-if="files.length"> <li v-for="(name, i) in filesNames" :key="i">{{ name }}</li> </ul> </label> <div> <img v-for="image in images" :src="image" /> </div> <br /> <button v-on:click.prevent="submitForm">Submit</button> Axiox <script> new Vue({ el: '#app', data() { return { files: [], images: [], } }, computed: { filesNames() { const fn = [] for (let i = 0; i < this.files.length; ++i) { fn.push(this.files.item(i).name) } return fn } }, methods: { handleFileUploads(event) { this.files = event.target.files; this.images = [...this.files].map(URL.createObjectURL); }, submitFile() { let formData = new FormData(); for (var i = 0; i < this.files.length; i++) { let file = this.files[i]; formData.append('files[' + i + ']', file); } submitForm: function(){ let formData = new FormData(); const fna = [] for (let i = 0; i < this.files.length; ++i) { fna.push(this.files.item(i).name) } console.log('fna'); console.log(fna); axios({ method : "POST", url: "{% … -
Django form validation failing for formset with choicefield
My formset consists of choice field with initial data populated from Views.py, Formset is generated properly with initial data but when I submit the form the form.is_valid is failing. I'm not sure what I'm missing here however tried in different ways but couldn't resolve. forms.py class RelServiceForm2(forms.Form): ebsapp = forms.CharField(widget=forms.TextInput(attrs=dict(required=True)), label=_("")) code_version = forms.ChoiceField(widget=forms.Select(), label=_(""), required=False) mscv = forms.ChoiceField(widget=forms.Select(), label=_(""), required=False) views.py mscv_versions_tup = [] mscv_versions_tup = [('9.11.041', '9.11.041'), ('9.11.040', '9.11.040')] print('mscvversions', mscv_versions_tup) my_config = update_my_config(region='us-east-1', account='prod') client = session.client('elasticbeanstalk', config=my_config) _beanstalk_apps = _ebsstageapps.filter(ebsapp__type='beanstalk') _beanstalk_apps_list = list(_ebsstageapps.values_list('ebsapp__name', flat=True)) print('_ebsstageapps : _beanstalk_apps', _beanstalk_apps_list) _response = client.describe_applications(ApplicationNames=_beanstalk_apps_list)['Applications'] RelServiceFormSet = formset_factory(RelServiceForm2, extra=0, ) formset = RelServiceFormSet(initial=[{'ebsapp': x} for x in _beanstalk_apps_list]) for _beanstalk_app in _response: code_versions = _beanstalk_app['Versions'] code_versions_tup = [] for v in code_versions: code_versions_tup.append((v, v)) for form in formset: if form['ebsapp'].value() == _beanstalk_app['ApplicationName']: print(' Form sec Matched') form.fields['code_version'].choices = code_versions_tup form.fields['mscv'].choices = mscv_versions_tup if request.method == 'POST': formset = RelServiceFormSet(request.POST,) # initial=[{'ebsapp': x} for x in _beanstalk_apps_list]) for _beanstalk_app in _response: code_versions = _beanstalk_app['Versions'] code_versions_tup = [] for v in code_versions: code_versions_tup.append((v, v)) for form in formset: if form['ebsapp'].value() == _beanstalk_app['ApplicationName']: form.fields['code_version'].choices = code_versions_tup form.fields['mscv'].choices = mscv_versions_tup else: print('unmatched') form = formset print('print form before valid', form) print('\n\n print') if form.is_valid(): … -
increase geo corrdinates such that nearest points can be found
I am working on a project which uses external API for fetching nearby shops for given Geo coordinates now the problem, if in case there is now shop available for given coordinates we should still be able to retrieve any of its nearest locations for shops that means we possibly have to increase coordinates periodically until we find such shops or locations(shops) which also means we're increasing the (GPS radius), now my question is whether there any such algorithm available which does such thing, also is my approach correct in this case because i am increasing the amount of API hits def get_nearby_stores(member_id,lat,lon): api = B2C response , status_code = api.get_nearest_location_shop( member_id=member_id, lat=lat, -
Django Save Occasionally Fails
We have a code like below and when executing process_something, sometimes the fields failed to be updated after process_something3 successfully executed. Most of the time it works normally but sometimes it just failed to update all mentioned field in the functions from django.db import models class DjangoObject(models.Model): field1 = models.PositiveSmallIntegerField() field2 = models.DateField() field3 = models.PositiveSmallIntegerField() def process_something(self): # Do something here self.save(update_fields=['field1']) self.process_something2() def process_something2(self): # Do asynchronous process self.process_something3() def process_something3(self): # Do another thing here self.save(update_fields=['field2', 'field3']) As far as i know it only happens here, so i suspect it caused by race condition by saving on same object. Is it really that or there is other cause and how to fix it ? Django version is 3.2.9 Postgresql version is psql (PostgreSQL) 12.7 (Ubuntu 12.7-0ubuntu0.20.04.1) Asynchronous process using [django-rq](https://github.com/rq/django-rq) -
How to break multiple if statements?
I have a permission class for my viewset. But it has multiple if statements and the if statements can be added others as well if some action added inside viewset. So how can I optimize my code here for better performance ? def has_permission(self, request, view): if view.action in ["update", "partial_update"]: return some_user if view.action == "create": return some_user if view.action in ["list", "retrieve"]: return some_user if view.action == "destroy": return some_user return False -
Django: I am unable to get Django to autocreate an autofield
I am calling BORROWER.objects.create(ssn=Ssn, bname=Name, address=Address, phone=Phone) from views.py to create an entry in my sqlite database. This is my models.py file with the relevant function. class BORROWER(models.Model): card_id = models.AutoField(primary_key=True, max_length=7), ssn = models.CharField(max_length=11) bname = models.CharField(max_length=71) address = models.CharField(max_length=79) phone = models.CharField(max_length=15) def __str__(self): return str(self.card_id) The database entry is successfully created. However, since I am not specifying a value for the card_id field, the value stays as (<django.db.models.fields.AutoField>,) instead of an actual key. When I try to specify a value for card_id it says something about unexpected argument. Am I calling the create function incorrectly? -
How do I make a calculation appear from models in my HTML template?
hello I am trying to do a multiplication in Django from models multiplying the quantity by the unit_price and reflecting the result in total_price) but I see that it is not reflected in my HTML template (I have some inputs and in the input where I want to reflect the result of the multiplication, it does not appear), does anyone know what is missing for me? [![Here neither the input of total_price appears][1]][1] I should also mention that it is a form and a formset to which I want to apply that models.py class Parte(models.Model): codigo=models.IntegerField() quantity=models.IntegerField() unit_price=models.IntegerField() total_price=models.IntegerField() tax_free=models.BooleanField() descripcion=models.CharField(max_length=255,blank=True, null=True) descuento=models.IntegerField() total=models.IntegerField() @property def total_prices(self): return self.quantity*self.unit_price def __str__(self): return f'{self.codigo}: {self.descripcion} {self.quantity} {self.unit_price} {self.total_prices} {self.tax_free}{self.descuento}{self.total}' presupuestos-forms.html <table class="table table-bordered table-nowrap align-middle"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_prices}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="add_more" value="+" /> </td> </tr> {{ formset.management_form }} {% for form in formset %} <tr id="formset" class="form-row"> <td> {% render_field form.codigo class="form-control" %} </td> … -
Ajax call to update sort criteria of product list in a Django template
I'm trying to make an Ajax call to update the sort criteria of a product list that is being displayed on the store page, depending on the drop-down option. The store page template extends from the main template. However, the sort isn't working. I took the liberty of removing all views that are not relevant to the question, except the store page view which is receiving the ajax call. I am wondering if there is a conflict issue since the store page is also receiving the cart total from the front end via the CartData function. Any insight would be helpful. main.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1"/> <title>MyShop</title> {# Bootstrap stylesheet#} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> {# Custom CSS#} <link rel="stylesheet" href="{% static 'css/ecomsite.css' %}"> {# Google Fonts import#} <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet"> <script type="text/javascript"> var user = '{{request.user}}' /* getToken function creates a CSRF token so that the cart.js script can communicate with the updateItem view */ function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; … -
How to perform multiple saving in django?
Am about to perform 3 saves in django, am worried about race condition and also confused to know if its the correct way to do it ! Here is my code: process.user = user process.save() user.is_updated = True user.save() actions = Actions(owner=user, action="Personal") actions.save() Am doing all this in a view function, is this a right way to do it ? Or should i use @transaction.atomic or please suggest which is a good method ? -
Django ImageField not uploading on form submit but not generating any errors
I have a simple app that uses an ImageField to upload & store a photo. I'm running the app local. The form displays as expected, and allows me to browse and select a jpg file. It then shows the selected filename next to the "Choose File" button as expected. When I submit the form, it saves the model fields 'name' and updates 'keywords' but it does not save the file or add the filename to the db. No errors are generated. Browsing the db, I see the newly added record, but the 'photo' column is empty. Any help appreciated. settings.py: MEDIA_ROOT = '/Users/charlesmays/dev/ents/ents/enrich/' models.py: class Enrichment(models.Model): name = models.CharField( max_length=255, unique=True) keywords = models.ManyToManyField(KeyWord, blank=True) photo = models.ImageField(upload_to='enrichments/', null=True, blank=True) views.py: def EnrichmentUploadView(request): if request.method == 'POST': form = CreateEnrichmentForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('index')) else: return render(request, 'createEnrichment.html', {'form':form}) else: form = CreateEnrichmentForm() return render(request, 'createEnrichment.html', {'form':form}) forms.py: class CreateEnrichmentForm(forms.ModelForm): class Meta: model = Enrichment fields = ('name', 'photo', 'keywords') enctype="multipart/form-data" -
django queryset with __date returns Nones
I have a django queryset where I want to group by created_at date value (created_at is a datetime field). (Activity.objects .values('created_at__date') .annotate(count=Count('id')) .values('created_at__date', 'count') ) I am following the accepted answer here which makes sense. However, the query returns None for all created_at__date values. When I change it to created_at it shows the actual value. The generated SQL query: SELECT django_datetime_cast_date("activity"."created_at", 'UTC', 'UTC'), COUNT("activity"."id") AS "count" FROM "activity" GROUP BY django_datetime_cast_date("activity"."created_at", 'UTC', 'UTC') -
How to setup User and (maybe) UserCreationForm model in Django?
Need help or resources for Django models. Hello, I am trying to modify/extend the django.contrib.auth.models.User class so it could register a few more fields, apart from username and password. For now I have implemented the User class only as a foreign key in another Task class. from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) # cascade deletes all tasks/items when user is deleted title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.title class Meta: ordering = ['complete'] What I tried: I've tried making it a One-to-One relation with a Employee class, but things got a little messy, as I was required to first register the user, and then later add attributes to the Employee as well as selecting the (already created) User as a primary key. That was not practical I suppose. So my question is: What is the best way to add attributes like Email, ID number, First name, Last name, etc in the User class and how to implement/render the appropriate form in the views.py? Here is my views file: from django.contrib.auth.mixins import LoginRequiredMixin # settings.py … -
Import packages from outside django project
Context: The package being considered is an application that was developed by another team and I want to use the functionality exposed as part of an API call in my django project. Directory layout: <repo> ├── org_wide_django_code │ ├── my_django_project │ │ ├── my_django_project │ │ ├── manage.py │ │ ├── requirements.txt │ │ └── my_application ├── frontend │ └── application ├── other_team_work │ ├── README.md │ ├── __init__.py │ ├── implemented_logic What is the best way for me to use other_team_work in my django project my_django_project? Prior reading: Manipulating PYTHONPATH or sys.path is an option Setting up a .whl or .egg to install other_team_work (also need to add a setup.py there) -
click table row redirect to website showing django db entry
I have a django project (form) with a database to save customer data. In URL_1 of my projects the most important db entries are shown as a table. Each row contains one customer and the columns list the relevant information. It delivers a brief overview of a database entry per row. The other URL_2 contains a search bar with a POST request. You can enter the ID of your database entry and you will see the full information for a customer on the whole page. Now I want to CLICK on the table in URL_1 and would like to land in URL_2, but already "pre-entered" the id of the customer to the search bar, so the information is shown. Now the code. This generates my "overview" table in URL_1: {% for snippet in snippets %} <tr data-href="form2"> <td id="rowid">{{snippet.id}}</td> <td>{{snippet.Titel_Person}} {{snippet.Vorname}} {{snippet.Nachname}}</td> <td>{{snippet.Kennzeichen}}</td> <td>{{snippet.Titel_Anwalt}} {{snippet.Anwalt_vorname}} {{snippet.Anwalt_nachname}}</td> <td>{{snippet.Anwalt_Straße}} {{snippet.Anwalt_ort}}</td> <td>{{snippet.Fahrzeug}}</td> <td>{{snippet.Geschlecht}}</td> <td>{{snippet.Tattag}}</td> </tr> {% endfor %} With this command I call the database entries to view in the URL_2: <form action = "{% url 'ga_form' %}" method = "POST" autocomplete="off"> {% csrf_token %} <input type="search" name="id_row" placeholder="Gutachten suchen" required> <button type="submit" name="id_row_btn" >Suchen</button> </form> which call this view method: def ga_form(request): … -
First django rest api call returns request.user as AnonymousUser but further calls return proper user
right now I have an api view that requires knowing which user is currently logged in. When I try to call it with a logged in user; however, it returns anonymous user. The odd thing is that if I call the api view again, it returns the proper user. I am using django rest framework and JSON Web Tokens with simplejwt. Right now the call in ReactJS looks like this: const fetchAuthorData = () => { axiosInstance.get('authors/') .then((res) => { setAuthor(res.data) }).catch((err) => { fetchAuthorData() }) fetchAuthorThreads() fetchAuthorArticles() } However, I know recursively calling this over and over is very dangerous, because even though I redirect if the user is actually not logged in before this recursive api call, if somehow that fails my server will be overloaded with api calls. Does anyone know how I could make it so that my api actually properly identifies on the first call whether the user is logged in? Here is the faulty view: @api_view(['GET']) def author(request): print(request.user) if request.user.is_authenticated: author = request.user serializer = AuthorAccessSerializer(author, many=False) return Response(serializer.data) else: return HttpResponse(status=400) In this, request.user is an anonymous user even though I am logged in Here is a similar part of another view … -
How to integrate a validator between python class and restful api?
I'm supposed to have a validator between my calculator and a rest-api that uses set calculator. My calculator is a python class as follows: class Calculator: reduced_tax = 7 standard_tax = 19 @staticmethod def calculate_reduced_tax(price): price_float = float(price) calculated_tax = price_float + ((price_float/100) * Calculator.reduced_tax) return calculated_tax @staticmethod def calculate_standard_tax(price): price_float = float(price) calculated_tax = price_float + ((price_float/100) * Calculator.standard_tax) return calculated_tax My (hopefully) restful api looks like this: from django.http import HttpResponse from calculator.calculator import Calculator from calculator.validator import validate_number import json def get_standard_tax(request, price): if request.method == 'GET': try: validated_input = validate_number(price) calculated_tax = Calculator.calculate_standard_tax(validated_input) response = json.dumps([{'price': price, 'with_standard_tax': calculated_tax}]) except: response = json.dumps({'Error': 'Could not calculate standard tax'}) return HttpResponse(response, content_type='text/json') def get_reduced_tax(request, price): if request.method == 'GET': try: validated_input = validate_number(price) calculated_tax = Calculator.calculate_reduced_tax(validated_input) response = json.dumps([{'price': price, 'with_reduced_tax': calculated_tax}]) except: response = json.dumps({'Error': 'Could not calculate standard tax'}) return HttpResponse(response, content_type='text/json') I tried to implement a validator as follows trying to throw a ValidationError from the django framework since my project overall uses Django: from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_number(value): if not float(value): print('a validation error should be thrown') raise ValidationError( _('%(value)s is not an number'), params={'value': value} … -
Dynamic modal content - youtube?
I have a daft question. I have a load of data coming in from a Django view - it has a column which includes a YouTube URL. At the moment, I loop through the skills & create a modal for each. Then when you click on the item, it opens the corresponding modal. However, when you have 100 items, this is a bit of a silly approach Does anyone know a better way to do it? I still want the videos embedded in a modal - but the video should be dynamically set, based on the chosen item. Thank you!! {% for skill in skill_list %} <div class="modal fade" id="{{ skill.skill_id }}" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-semi-full modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{ skill.skill_name }}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <iframe width="100%" height="100%" src="https://www.youtube.com/embed/{{skill.syllabus}}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> -
Django-q multiple clusters and tasks routing
Is it possible to have two clusters and route tasks between them? I suppose I can run two clusters using different settings files, but how to route tasks in that case? -
AttributeError: 'NoneType' object has no attribute 'lower'; password validation
When registering a User, the desired user password is checked against a list of disallowed passwords. Yet when the password is passed to a validator method, the following error is raised: AttributeError: 'NoneType' object has no attribute 'lower' Why is the validate() method being invoked as is if password is None when in fact it is truthy? from django.contrib.auth.models import User from django.contrib.auth.password_validation import ( validate_password, CommonPasswordValidator, NumericPasswordValidator ) from rest_framework import serializers class LoginSerializer(UsernameSerializer): password = serializers.RegexField( r"[0-9A-Za-z]+", min_length=5, max_length=8 ) def validate(self, data): username = data['username'] password = data['password'] try: validate_password(password, password_validators=[ CommonPasswordValidator, NumericPasswordValidator ]) except serializers.ValidationError: if username == password: pass raise serializers.ValidationError("Invalid password") else: return data class Meta: fields = ['username', 'password'] model = User -> for validator in password_validators: (Pdb) n > \auth\password_validation.py(46)validate_password() -> try: (Pdb) n > \auth\password_validation.py(47)validate_password() -> validator.validate(password, user) (Pdb) password 'Bingo' (Pdb) user (Pdb) password 'Bingo' (Pdb) s --Call-- > \auth\password_validation.py(180)validate() -> def validate(self, password, user=None): (Pdb) password (Pdb) n > \django\contrib\auth\password_validation.py(181)validate() -> if password.lower().strip() in self.passwords: (Pdb) n AttributeError: 'NoneType' object has no attribute 'lower' -
PyTube files are in root directory not in Downloads path from user
I'm coding an video converter and everything works as expected on my localhost but now on the server my converted video gets saved in the root dir from my server and not in the Downloads path from the user. This is my code: if format == "3": messages.info(request, 'The MP3 was downloaded successfully!') yt = YouTube(link) downloads = str(os.path.join(Path.home(), "Downloads")) audio_file = yt.streams.filter(only_audio=True).first().download(downloads) base, ext = os.path.splitext(audio_file) new_file = base + uuid + '.mp3' os.rename(audio_file, new_file) elif format == "4": messages.info(request, 'The MP4 was downloaded successfully!') yt = YouTube(link) downloads = str(os.path.join(Path.home(), "Downloads")) ys = yt.streams.filter(file_extension='mp4').first().download(downloads) username = request.user.username context = {'format': format, 'username': username} return render(request, 'home/videoconverter.html', context) the parameter next to .download is the path, as I already said on my localhost everything worked. So I need a way to save files in the users download dir with server. -
Reverse not working with kwargs while working in another function - why?
def test_no_errors_direct_flights_rendered_in_template(self): request = HttpRequest() response = render(request,'app1/flight-search-result.html', { 'direct_flights': [ { ---- not relevant }) self.assertContains(response, 'Direct connection') self.assertNotContains(response, 'No options for your search') self.assertNotContains(response, 'One change') # this assertContains will ensure that the searched word is not in the form - we don't pass # the form to the render function above self.assertContains(response, 'Venice Airport Marco Polo') self.assertContains(response, 'Dubai International Airport') # you can add more once you change the template url = reverse('app1:flight-search-detail-passenger-form', kwargs={'to_first': "VCEDXB2201040"}) ---- works! self.assertContains(response, '<a href="{}">'.format(url)) def test_no_errors_indirect_flights_rendered_in_template(self): request = HttpRequest() response = render(request, 'app1/flight-search-detail-passenger-form.html', { 'indirect_flights': [ { ----- not relevant { } ] } ] }) self.assertContains(response, 'One change') self.assertNotContains(response, 'No options for your search') self.assertNotContains(response, 'Direct flight') # you can add more once you change the template kwargs = {'to_first': "VCEDXB2201040"} _url = reverse('app1:flight-search-detail-passenger-form', kwargs=kwargs)------- doesn't work! self.assertContains(response, '<a href="{}">'.format(_url)) A very weird problem, but the first reverse works perfectly well while the second one throws the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'flight-search-detail-passenger-form' with arguments '('',)' not found. 2 pattern(s) tried: ['flights/detail/passenger/to=(?P<to_first>[ A-Z0-9]{13})&(?P<to_second>[A-Z0-9]{13})$', 'flights/detail/passenger/to=(?P<to_first>[A-Z0-9]{13})$'] Has someone encountered it before? How can I solve it? -
How to deploy django(back) and react(front) servers on nginx on ubuntu?
I have to to deploy web-server(django and react) on nginx server. I already have working projects, they weigh about a 2 gigabyte, there are a lot of libraries. Do I need to save them? I can't imagine how to do it in most simple way. There are information doing it using docker. Is it a common way to do it? Can you explain me how exactly a true way to do this deploying, please. -
How to send stream data using just python?
I am currently learning NodeJS and I learned a really neat way of sending big files, using streams, I already have a bit of an experience with Django but how can I do the following in Django (or python) const http = require('http') const fs = require('fs') const server = http.createServer((req, res)=>{ const fileContent = fs.createReadStream('./content/bigFile.txt', 'utf8') fileContent.on('open', ()=>{ fileContent.pipe(res) }) fileContent.on('error',(err)=>res.end(err) ) }) server.listen(5000)