Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileNotFoundError: [Errno 2] No such file or directory: 'corpus_or_AB_FMC.xlsx'
I have a directory which contains a lot of excel files. My aim is to read all those excel files and extract some information in them. I used the script below to read the directory but I am still getting an error. The files are identified but the code tell it is not founding them which is strange because there is a line to print the name of the file. But when reading the file with pandas, it is not founded. /home/geta/kelo/eXP/Test/corpus -----File in processed : corpus_or_AB_FMC.xlsx Traceback (most recent call last): File "test_vec.py", line 111, in <module> sentences = pd.read_excel(file, sheet_name= 0) File "/home/getalp/kelodjoe/anaconda3/lib/python3.7/site-packages/pandas/util/_decorators.py", line 208, in wrapper return func(*args, **kwargs) File "/home/geta/kelo/anaconda3/lib/python3.7/site-packages/pandas/io/excel/_base.py", line 310, in read_excel io = ExcelFile(io, engine=engine) File "/home/geta/kelo/anaconda3/lib/python3.7/site-packages/pandas/io/excel/_base.py", line 819, in __init__ self._reader = self._engines[engine](self._io) File "/home/geta/kelo/anaconda3/lib/python3.7/site-packages/pandas/io/excel/_xlrd.py", line 21, in __init__ super().__init__(filepath_or_buffer) File "/home/geta/kelo/anaconda3/lib/python3.7/site-packages/pandas/io/excel/_base.py", line 359, in __init__ self.book = self.load_workbook(filepath_or_buffer) File "/home/geta/kelo/anaconda3/lib/python3.7/site-packages/pandas/io/excel/_xlrd.py", line 36, in load_workbook return open_workbook(filepath_or_buffer) File "/home/geta/kelo/anaconda3/lib/python3.7/site-packages/xlrd/__init__.py", line 111, in open_workbook with open(filename, "rb") as f: here is the code : dir = "/home/geta/kelo/eXP/Test/corpus" for root, subdirs, files in os.walk(dir): print(root) for file in files: #print(files) print("-----File in processed :", file) # -----File in processed : corpus_or_AB_FMC.xlsx # this file … -
All paths open a single page
I am new to Django and doing something wrong. I've tried many templates and examples and always run into the same problem. No matter what path I try to use, I get the same file. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my apps 'strategicplan.apps.StrategicplanConfig', 'house.apps.HouseConfig', ] Main site urls.py from strategicplan import views as sp_views from house import views as house_views urlpatterns = [ path('house/',house_views.index), path('strategicplan/',sp_views.index), ] house/urls.py from django.urls import path from house import views urlpatterns = [ path('', views.index, name='index'), ] house/templates/index.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Houses</title>{% endblock %} </head> <body> house </body> </html> strategicplan/urls.py from django.urls import path from strategicplan import views urlpatterns = [ path('strategicplan/', views.index, name='index'), ] strategicplan/templates/index.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>strategic plan</title>{% endblock %} </head> <body> strategic plan </body> </html> No matter what I put in the url http://127.0.0.1 or http://127.0.0.1/house or http://127.0.0.1/stategicplan, I get the strategicplan/index.html page. Both http://127.0.0.1 and http://127.0.0.1/house end up with http://127.0.0.1 in the address bar, but still show the strategicplan page. The http://127.0.0.1/strategicplan page holds the correct address in the address bar, which is also the correct page. Thanks!! -
python django help me pls
hello this is my code i need to insert data in datatable user_id and subject_id .The select box is filled form database subjects table. this are my code files: models.py from django.db import models class ShowSubjects(models.Model): subject=models.CharField(max_length=100) class Meta: db_table ='subjects' views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from directory.models import ShowSubjects @login_required def directory(request): results=ShowSubjects.objects.all() return render(request, 'directory/directory.html',{'ShowSubjects':results}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.directory, name='directory'), ] html {% block content %} <div class="dir-left"> </div> <div class="dir-right"> <form method="POST"> {% csrf_token %} <select name="selectedsubject"> <option disabled="true" selected> Select subject </option> {% for results in ShowSubjects %} <option>{{results.subject}}</option> {% endfor %} </select> <div class="form-group"> <br> <button class="addsubject" type="submit">Add subject</button> </div> </form> </div> {% endblock %} help me pls -
The form to change email/profile pictures doesn't appear?
Any guidance on this issue will be greatly appreciated. I entered the necessary fields so that on the profile page the user would be able to edit the profile picture and the username and email. when I created the form, it only displayed the update button and the "Profile Info" text. How can fix this so that the form to edit the user information appears? in views.py ''' @login_required def profile(response): if response.method == "POST": u_form = UserUpdateForm(response.POST, instance=response.user) p_form = ProfileUpdateForm(response.POST, response.FILES, instance=response.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(response, f'Your account has been updated!') return redirect("/profile") else: u_form = UserUpdateForm(instance=response.user) p_form = ProfileUpdateForm(instance=response.user.profile) args = {} args['u_form']= u_form, args['p_form']= p_form return render(response, 'register/profile.html') ''' in forms.py ''' from django import forms #from django.contrib.auth. import login, authenticate from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from .models import Profile from django.forms import ModelForm class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email", "password1", "password2"] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ["username", "email"] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] ''' in profile.html {% extends "register/base.html" %} {% load crispy_forms_tags %} {% block content %} … -
Как сделать выпадающий список моделей в Django в админке [closed]
Имеются следующие модели Как реализовать следующую мысль? Я хочу, чтобы при добавлении городов в админ панели выпадающим списком сначала предлагалось выбрать страну, потом область и после всего этого написать название города и сохранить. Сделал похожую реализацию в модели UserLocation,но там пришлось использовать ChainedForeignKey. Здесь хочется модели не трогать, всю голову сломал. -
My change to models.py isn't being reflected in the admin portal
I've added a model called 'ads' into my models.py (which already contained a model called 'video', but the only model showing in the admin portal is the 'video' model. This is my model: from django.db import models # Create your models here. class video (models.Model): VID_CHOICES = ( ('News', 'News'), ('Stam', 'Stam'), ('Music', 'Music'), ('Ad', 'Ad'), ) url = models.CharField(max_length=1000) title = models.CharField(max_length=100) description = models.CharField(max_length=1000, blank=True) show_after_time = models.DateTimeField('show after') category = models.CharField(max_length=20, choices=VID_CHOICES) tag = models.CharField(max_length=100, blank=True) def __str__(self): return self.title class ad (models.Model): AD_CHOICES = ( ('Constant', 'Constant'), ('Temporary', 'Teporary'), ('Filler', 'Filler'), ) redirect = models.URLField(blank=True) pic = models.URLField() first_day = models.DateTimeField('first day') last_day = models.DateTimeField('last day') kind = models.CharField(max_length=21, choices=AD_CHOICES) def __str__(self): return self.title I've run the migrations and everything, why isn't it working? PS - I currently use postgres, but started with sqlite3. Meaning, I created the model 'video' on sqlite3, and am trying to make 'ads' on postres. -
ImportError when trying to use Django
apologies if this question has been asked a ton, I'm sure it has, and I've been trying for days to figure this out, but I can't wrap my head around it. I've been developing in Python for over 1.5 years, so I'm not a complete beginner. I can't get Django to work in my command prompt. An example is, when I try to use py .\manage.py makemigrations this is what I get: Traceback (most recent call last): File ".\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File ".\manage.py", line 22, in <module> main() File ".\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Now, I can see what the error says. The thing is my virtual environment is activated and it has Django installed, as seen here. Moreover, even if I executed outside my venv, it still doesn't work, even though I have all necessary Python directories in my PATH, as seen here. I have verified … -
Django: Save two models (Customer and Addresses) in one Form
I have this models.py: class Customers(models.Model): ID = models.AutoField(primary_key=True) IsBusinessCuster = models.BooleanField(default=True, blank=True, null=True) CustomerSalutation = models.ForeignKey('Salutation', on_delete=models.DO_NOTHING) Title = models.CharField('Title', max_length=20) Firstname = models.CharField('Firstname', max_length=200) Lastname = models.CharField('Lastname', max_length=200) Orders = models.ForeignKey('Order', on_delete=models.DO_NOTHING, blank=True, null=True) CustomerNo = models.IntegerField('Zip', blank=False, null=False) Addresses = models.ForeignKey('CustomerAddresses', on_delete=models.DO_NOTHING) CustomerGroup = models.ForeignKey('CustomerGroups', on_delete=models.DO_NOTHING) IsActive = models.BooleanField(default=True, blank=True, null=True) CVR = models.IntegerField('CVR', blank=True, null=True) Company = models.CharField('Company', max_length=128, blank=True, null=True) Created_Date = models.DateTimeField(auto_now_add=True) PhoneNumber = models.CharField('PhoneNumber', max_length=20, blank=True, null=True) UserID = models.ForeignKey('MasterData', on_delete=models.CASCADE) Email = models.EmailField('EMail', max_length=128, blank=True, null=True) def __str__(self): return str(self.Lastname) class CustomerAddresses(models.Model): ID = models.AutoField(primary_key=True) Salutation = models.ForeignKey('Salutation', on_delete=models.DO_NOTHING) Title = models.CharField('Title', max_length=20, blank=True, null=True) Address_Firstname = models.CharField('Firstname', max_length=200) Address_Lastname = models.CharField('Lastname', max_length=200) Zip = models.IntegerField('Zip') City = models.CharField('City', max_length=128) Address_Company = models.CharField('Company', max_length=128, blank=True, null=True) Is_Default_Shipping_address = models.BooleanField(default=True, blank=True, null=True) Is_Default_Billing_address = models.BooleanField(default=True, blank=True, null=True) Country = models.CharField('Country', max_length=32, blank=True, null=True) def __str__(self): return str(self.ID) and this form.py: class CustomerForm(forms.ModelForm): IsBusinessCuster = forms.BooleanField( widget=forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'customSwitch2'}), initial=False, required=False) class CustomerAddressesForm(forms.ModelForm): Title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control mb-3', 'autofocus': True}), required=False) Shorten version... You can see that address are an must have field in Customer's form. I build an form in html where you have all fields, but how can I save both … -
no values from jquery in a template to my view function
I am using django and I am getting all id from checkboxes and now I want to pass them to my view function, but I don't know how. I've tried request.GET.getlist('vals') but with no success. any suggestions? events.html: <script> $(document).ready(function(){ $("button").click(function(){ type: 'POST'; var vals = []; $.each($("input[name='checkb']:checked"),function(vals){ vals.push($(this).attr('id')); }); alert("values: " + vals.join(", ")); }); }); </script> <td><a href="eprint"><button><i class="bi bi-sim"></i></button></a></th> {% for l in object_list %} <tr> <td> <form> <label><input type="checkbox" id={{l.pk}} name="checkb"></label> <form> ... urls.py: path('eprint',views.eprint,name='eprint'), views.py: def eprint(request): print('eprint') v=request.GET.getlist(vals) -
How to add drag & drop feature for uploading multiple files using django-forms with dropzone.js?
I wanna add a drag and drop multiple file upload field in my existing form using django-forms with dropzone.js. These are my files 👇 forms.py 👇 class RaiseRequisitionForm(forms.Form): position_required = forms.CharField(required=True, label="Position Required" , max_length=2000, widget=forms.TextInput(attrs={"class":"form-control"})) requirement_choices = ( ("New", "New"), ("BackFill", "BackFill") ) requirement = forms.ChoiceField(required=True, label="Requirement" , choices=requirement_choices ,widget=forms.Select(attrs={"class":"form-control"})) candidate_name = forms.CharField(required=True, label="Candidate Name" , max_length=2000 ,widget=forms.TextInput(attrs={"class":"form-control"})) department = forms.CharField(required=True, label="Department" , max_length=2000 ,widget=forms.TextInput(attrs={"class":"form-control"})) post = forms.CharField(required=True, label="Post" , max_length=2000 ,widget=forms.TextInput(attrs={"class":"form-control"})) requirement_type = ( ("Permanent", "Permanent"), ("Temporary", "Temporary"), ("Fixed Contract", "Fixed Contract") ) requirement_time_period = forms.ChoiceField(required=True, label="Requirement Time Period" ,choices=requirement_type , widget=forms.Select(attrs={"class":"form-control"})) work_type = ( ("Full-Time", "Full-Time"), ("Part-Time", "Part-Time") ) work_type = forms.ChoiceField(required=True, label="Work Type" ,choices=work_type , widget=forms.Select(attrs={"class":"form-control"})) duration_start_date = forms.DateField(required=True, label="Duration Start Date", widget=forms.DateInput(attrs={"type":"date", "class":"form-control"})) duration_end_date = forms.DateField(required=False, label="Duration End Date ( If Temporary Or Fixed Contract )", widget=forms.DateInput(attrs={"type":"date", "class":"form-control"})) requisition_reason = forms.CharField(required=True, label="Requisition Reason", widget=forms.Textarea(attrs={"class":"form-control"})) min_qualification = forms.CharField(required=True, label="Minimum Qualification", max_length=1000, widget=forms.TextInput(attrs={"class":"form-control"})) max_qualification = forms.CharField(required=True, label="Desired Qualification", max_length=1000, widget=forms.TextInput(attrs={"class":"form-control"})) min_experience= forms.CharField(required=True, label="Minimum Experience", widget=forms.TextInput(attrs={"class":"form-control"})) max_experience= forms.CharField(required=True, label="Maximum Experience", widget=forms.TextInput(attrs={"class":"form-control"})) models.py 👇 I added the "documents" variable for uploading files. class Requisition(models.Model): id = models.AutoField(primary_key=True) position_required = models.CharField(max_length=2000, default="") requirement_choices = ( ("New", "New"), ("BackFill", "BackFill") ) requirement = models.CharField(max_length=100, choices=requirement_choices, default="") candidate_name = models.CharField(max_length=2000, default="") department … -
Connection Refused when using "createdb" to deploy Wagtail site to Heroku
Im attemtping to deploy my first Wagtail site to Heroku but seem to be facing issues with the first steps. When using the createdb command, I get the following 2 errors: I've set ALLOWED_HOSTS to ['*'] to cover everything but i'm unsure of where to update the port number to 5432. The code in my production.py looks like this: from __future__ import absolute_import, unicode_literals from .base import * import dj_database_url import os env = os.environ.copy() SECRET_KEY = env['SECRET_KEY'] DEBUG = False DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['*'] try: from .local import * except ImportError: pass and my dev.py: from .base import * import os env = os.environ.copy() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXX' # SECURITY WARNING: define the correct hosts in production! ALLOWED_HOSTS = ['*', '127.0.0.1'] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' try: from .local import * except ImportError: pass Any help or pointers to get this up and running on Heroku would be much appreciated. If any additional information is needed I'll happy to provide. -
How to filter the list of a foreign_key form and change the display name in Django admin?
I know I can get the list of values that is displayed in a ForeignKey form in my add/change form filtered based on a queryset if I override the get_form method. But how can I also change the display name of these fields? I know I can use formfield_for_foreignkey method but then I don't have the object to filter the queryset. I couldn't use both because one overrides the other. def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) value = ... #some value used for filtering form.base_fields['some_field'].queryset = ( MyModel.objects.filter(other_field=value) .order_by('name') ) return form Also, when I use the get_form with the queryset filtered, if I am accessing a change_form page, that field is blank even though the instance of the model that I am editing has a value for it. Any thoughts? Reference: formfield_for_foreignkey -
Django, Python unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
I'm creating an appointment application in Django where the end time of the appointment = the start_time + 30 min but I get this error I try a few solutions in stackoverflow, but nothing work for me this is my forms.py class AppointmentForm(forms.ModelForm): doctor = forms.ModelChoiceField(queryset=User.objects.filter(type_of_user=TypeOfUser.DOCTOR)) date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), input_formats=settings.DATE_INPUT_FORMATS) start_time = forms.TimeField(widget=forms.DateInput(attrs={'type': 'time'})) class Meta: model = Appointment fields = ('doctor', 'date', 'start_time',) and this is the views.py from datetime import timedelta import datetime as dt @login_required def create_appointement(request): user = User() if request.user.is_patient(): form_appointement = AppointmentForm(request.POST or None) if request.method=='POST': form_appointement = AppointmentForm(request.POST or None) if form_appointement.is_valid(): form_app = form_appointement.save(commit=False) form_app.user_ho_add = request.user form_app.end_time = form_app.start_time + dt.timedelta(minutes=30) ### form_app.save() messages.success(request, 'appointment added') else: messages.error(request, 'Error') return render(request,'appointement/add_appointement1.html',{'form':form_appointement}) -
How can I send Json Data from python to javascipt
i have this segment of code in a django view (views.py) that returns me a json document, I would like this json document to be sent to a javascript file using fetch. Hope you can help me def get_all_monitors_with_last_data(request): token_type = "Bearer" user = request.user company_user = CompanyUser.objects.get(user=user) company = Company.objects.get(id=company_user.company_id) refresh_time = 60*60*3 now = int(time.time()) get_last_datetime_data = company.last_date_token u_get_last_datetime_data = int(get_last_datetime_data.timestamp()) + refresh_time if(company.token == None or u_get_last_datetime_data < now): token = get_token(company.username, company.password, company.config_grant, company.client_id, company.client_secret) if(token != {}): company.last_date_token = datetime.now() company.token = token["access_token"] company.save() token_access = company.token BASE_API = "http://url"; req = {} params = {} try: req = requests.get(BASE_API+"/urlcomplements/", params = {}, headers = { 'Content-Type': "json", 'Authorization': token_type + " " + token_access }).json(); except requests.exceptions.HTTPError as e: req = {} return JsonResponse(req, safe=False) -
Using Django Framework
Is it a necessity to create a virtual environment when using a Django framework? I have been trying to activate my virtual environment on windows to no avail. What should I do -
django verbose_name remove remove capitalization
How to remove the capitalization of verbose name? a field in models.py betondeckung= models.FloatField(null=True, blank=True, default=None, verbose_name='Betondeckung [cm]') is processed in a html-table with django template language (tempalate.html) using <th scope="col" style="text-align:left">{{ model|get_verbose_field_name:field}}</th> where the following filter is used from templatetag.py @register.filter def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ return instance._meta.get_field(field_name).verbose_name.title() The problem is that django produces a html that is sent to the browser with: Betondeckung [Cm] Every single word is capitalized, which is not correct for german and here even "cm" becomes "Cm". I tried with css, but the capitalization is already in django. Setting all to lower case using css can also be wrong. Any idea how to switch off the capitalization of the verbose name (in django)? -
Trouble upgrading pop on ElasticBeanstalk
I'm getting the following error (in eb-activity.log) when trying to install a Django application in ElasticBeanstalk Collecting cryptography==3.4.7 (from -r /opt/python/ondeck/app/requirements.txt (line 16)) Downloading https://files.pythonhosted.org/packages/9b/77/461087a514d2e8ece1c975d8216bc03f7048e6090c5166bc34115afdaa53/cryptography-3.4.7.tar.gz (546kB) Complete output from command python setup.py egg_info: =============================DEBUG ASSISTANCE========================== If you are seeing an error here please try the following to successfully install cryptography: Upgrade to the latest pip and try again. This will fix errors for most users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip =============================DEBUG ASSISTANCE========================== Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-edwbzxg0/cryptography/setup.py", line 14, in <module> from setuptools_rust import RustExtension ModuleNotFoundError: No module named 'setuptools_rust' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-edwbzxg0/cryptography/ You are using pip version 9.0.1, however version 21.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2021-03-29 16:07:25,516 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (ElasticBeanstalk::ExternalInvocationError) In .ebextensions/02_install.config I do have the … -
How to pass value from template to views on django?
I want to create an input field for comparison in such way that when a user submits a query that goes to a list to compare with subsequent queries objects up to 3 times. I have also set the autocomplete jquery ui widget to suggest the user to submit a query that matches the query with name (one of the model's field) for comparison. So far, I am able to capture the inputs of the user in JS array but I don't know how to pass that in views and display specific objects. views.py from universities.models import Universities universities = Universities.objects.all() uni_names = [] for university in universities: uni_names.append(university.name) def college_comparison_page(request): context = { 'universities': universities, 'uni_names': uni_names, } return render(request, 'college_comparison/college_comparison.html', context) template: <!-- Search --> <div class="search"> <input type="text" name="search" class="searchTerm" id="university-search" placeholder="Search for Universities.."> </div> <!-- JQuery Autocomplete Start --> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> const uniNames={{ uni_names|safe|escape }}; $(function() { $("#university-search").autocomplete({ source: function(request, response) { var results=$.ui.autocomplete.filter(uniNames, request.term); response(results.slice(0, 10)); } }); }); // JQuery Autocomplete End // Getting Search Value var unisForCompare=[] var searchValue=document.getElementById('university-search'); searchValue.addEventListener("keydown", function(e) { if (e.key==="Enter") { var uniQuery=searchValue.value; if (uniNames.includes(uniQuery)) { if (unisForCompare.length<3&&(!unisForCompare.includes(uniQuery))) { unisForCompare.push(uniQuery); console.log(unisForCompare); } } } }); // … -
Python ,Django insert into datatable
Hi guys I have a little problem in Django. I need to insert current user id and subject id in data table called user_subjects. I now that I can get currently logged in user id with request.user command. this is my html code where selects options are filled rom database table subjects. <div class="dir-right"> <form method="POST"> {% csrf_token %} <select name="selectedsubject"> <option disabled="true" selected> Select subject </option> {% for results in ShowSubjects %} <option>{{results.subject}}</option> {% endfor %} </select> <div class="form-group"> <br> <button class="addsubject" type="submit">Add subject</button> </div> </form> </div> views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from directory.models import ShowSubjects from directory.models import SelectedSubject @login_required def directory(request): results=ShowSubjects.objects.all() return render(request, 'directory/directory.html',{'ShowSubjects':results}) def connectsubject(request): if request.method =='POST': if request.POST.get('selectedsubject'): return render(request, 'directory/directory.html') else: return render(request, 'directory/directory.html') models.py from django.db import models from django.db import connections class ShowSubjects(models.Model): subject=models.CharField(max_length=100) class Meta: db_table ='subjects' class SelectedSubject(models.Model): user_id= models.IntegerField() subject_id = models.IntegerField() class Meta: db_table ='user_subjects' -
Why is the regex pattern not matching in django 1.11?
I am trying to pass the ID as an argument to another page on the website using regex using django framework version 1.11: <h2><li><a href="{{school.id}}/">{{ school.name }}</a></li></h2> urls.py from django.conf.urls import url from . import views app_name = "basic_app" urlpatterns = [ url(r'^schools_list/$', views.SchoolList.as_view(), name='list'), url(r'^(?P<pk>\d+)/$', views.SchoolDetail.as_view(),name='detail'), ] However I am getting a 404 Page not found after running the local server: ^basic_app/ ^(?P\d+)/$ [name='detail'] The current path, basic_app/schools_list/1/, didn't match any of these. -
Boolean Filter on Django Admin
I'm trying to build a filter that corresponds to the has_images method on my Django admin, but I can't because it strictly says that has_images is not a field of the model. I tried setting it up as a property, but it also didn't work. I thought about defining has_images as a field and really calculating it, based on the changes on the model, but I think that would be not optimal. What would be a good solution here? models.py class Product(models.Model): name = models.CharField("Name", max_length=255) def has_images(self): return self.images.all().count() > 0 has_images.boolean = True class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="images") file = models.ImageField("Product Image") Expected result: -
keep_lazy for translation messages sent through Django API
I'm working on translation (French to German) of some messages my app send through Django Api. My problem was that translation worked only if i put LANGUAGE_CODE="de-de". So i thought was a problem with lazy translation. I found keep_lazy() decorator but, being really a baby web dev, i can't find the way to incorporate keep_lazy() on my existing decorator. Here is my py file sending message through api request (create document here) : @method_decorator( reponse_toast_decorator(Toast(message=gettext("Votre nouveau document a été créé.")), data_field_name="document"), name="create", ) Here is my function from utils : def reponse_toast_decorator(toast=None, data_field_name=""): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): response = func(*args, **kwargs) if not isinstance(toast, Toast): raise ValueError("L'argument 'toast' doit être une instance de la classe Toast") if isinstance(response, Response): if response.status_code == status.HTTP_204_NO_CONTENT: response.status_code = status.HTTP_200_OK if response.data is None: response.data = {} if not data_field_name: response.data.update({"toast": toast.data}) return response response.data = {data_field_name: response.data, "toast": toast.data} return response return wrapper return decorator Being a baby web dev, i can't find the way to incorporate -
Do I have to use Django Models to use the API?
We are migrating our intranet application and have decided to choose the Django framework. We control all of our database via source control and managed scripts, so we do not use the migrate feature to create tables for us. Views and Tables can change, all business logic is held in the database. I want to make Django API endpoint which is basically select * from my_table_or_view; and Django can return a JSON response with the column names and values. Some database tables have close to 100 columns each so I don't want to write out each and every field name and type just to return a query. What happens if we add another column to the view - will I have to update it in Django as well? What if I change the column type - will my application fail as well? The frontend is written in VueJS - it makes a request to the API endpoint and should use the columns selected in the frontend, obviously if I remove a column it will break but I don't want to have to add the column in the django framework even if it is not used. I've read the raw SQL … -
How to prevent Apache web server accepting requests from unknown hosts
I have a Django app running on Elastic Beanstalk which keeps creating redundant sentry error logs when bots make requests with HOST headers not matching my ALLOWED_HOST Django setting. How do configure Elastic Beanstalk to stop Apache accepting any request without my host name (e.g www.example.com) ? There are similar questions on here however they do not explain exactly how to change the Apache configurations during deployment. -
how to deploy a mobile app built with React Native and backend REST Api like Django
I am familiar with ReactJS and recently decided to start building a mobile application with react native. When you are using a front end library like ReactJS + backend framework like Django(Django Rest Framework), assuming they are separated in the infrastructure, you can make them talk to each other reactjs on port 3000 and django on port 8000 using cors-headers then deploy it to a hosting provider like AWS on www.fullstackapp.com as a domain name example where React has a subdomain and django as well but both technology is displayed to the user under a single domain name. As I never deployed a mobile application before, I wonder, what is the way to achieve the same result for a mobile application talking to the backend in production (to be able to deploy that full stack mobile app on Apple Store or Google Play Studio)? Thank you in advance.