Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My django, uwsgi project doesn't run because of virtual env
I will service my django project with uwsgi on Ubuntu Server, but It doesn't run. I am using python 3.6 but the uwsgi shows me it's 2.7 I changed default python to python3.6 but uwsgi still doesn't work. This is my command : uwsgi --http :8001 --home /home/ubuntu/repository/env --chdir /home/ubuntu/repository/project -w project.wsgi This is Error message : *** Starting uWSGI 2.0.18 (64bit) on [Tue Jun 4 21:03:58 2019] *** compiled with version: 5.4.0 20160609 on 04 June 2019 11:39:14 os: Linux-4.4.0-1079-aws #89-Ubuntu SMP Tue Mar 26 15:25:52 UTC 2019 nodename: ip-172-31-18-239 machine: x86_64 clock source: unix detected number of CPU cores: 2 current working directory: /home/ubuntu/repository/charteredbus *** running under screen session 1636.sbus *** detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/ubuntu/repository/charteredbus *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 15738 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8001 fd 4 spawned uWSGI http 1 (pid: 8402) uwsgi socket 0 bound to TCP address 127.0.0.1:39614 (port auto-assigned) fd 3 … -
Upload Image in the wrong direction in django ImageField
When I upload a photo, the photo is loaded successfully, but the photo is placed in the wrong direction. Instead of placing the image on the path to 'media/posts-pics/' - as I have outlined in my Post model - it is placed on the 'media' path. These are my files: models.py class Post(models.Model): index_pic = models.ImageField(upload_to=('posts-pics/')) Project.urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def add_post(request): if request.method == "POST": form = AddPostForm(request.POST, request.FILES) if form.is_valid(): new_post = form.save(commit=False) new_post.index_pic = form.cleaned_data['index_pic'] new_post.save() return redirect('view_post') else: form = AddPostForm() template = 'post/add_edit_post.html' context = {'form': form} return render(request, template, context) def edit_post(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == "POST": form = AddPostForm(request.POST, request.FILES, instance=post) if form.is_valid(): Post.objects.filter(id=post.id).update(title=request.POST['title'], index_pic=form.cleaned_data['index_pic'], ) return redirect('view_post') else: form = AddPostForm(instance=post) template = 'post/add_edit_post.html' context = {'form': form} return render(request, template, context) I used exactly the same code for add_post, and the photo was in its place, but I got into trouble in edit_post. what's wrong ? -
"Resolving Host" problem from same network
I am a little new to networking part, hence a little help is greatly welcome. I've developed a tool using Python 3.7.3 (x64) Django 2.1.2 MySql 8.1 and have hosted the same using ApacheServer 2.4 (x64) locally in 192.168.1.20:80. Problem Statement: Case 1 : When the site is accessed from any 2.x network Result : Site doesn't has any issues and renders fastly Case 2 : When the site is accessed from the same 1.x network Result : Site is too slow to render(at the bottom of any browser, I could see a message saying resolving host for atleast 10sec) Case 3 : When the site/private IP is linked with a public IP and accessed Result : Site doesn't show any slowness Other Points 1.x network doesn't has internet connection whereas 2.x has internet Django's development server faces the same problem httpd.conf has a "listen 192.168.1.20:80 and servername 192.168.1.20:80" Please help. -
Reverse for 'auth_password_reset_confirm' not found
I'm setting production environment on EC2. The exactly same code is running on Dev and Prod, but gunicorn (prod) and different settings.py. It's all working fine, but when a visitor tries to reset password he access the page "password_reset", fill the form with his email but, after submitting, get a 500 error. When this occour, i'm emailed (admin emails) with this error saying: "Internal Server Error: /accounts/password_reset/ NoReverseMatch at /accounts/password_reset/ Reverse for 'auth_password_reset_confirm' not found. 'auth_password_reset_confirm' is not a valid view function or pattern name." What i understand is that "/accounts/password_reset/" is trying to call an "auth_password_reset_confirm" that indeed does not exist (the correct url name is "password_reset_confirm"). But i don't know who is adding this "auth_" before. I've tried: 1) Confirm on dev and prod that the url name given from django.contrig.auth is "password_reset_confirm" 2) Downloaded server version of django.contrib.auth and confirm no "auth_" is being added to the call. 3) Confirm that i didn't add "auth_" on any url name on my apps. common_settings.py: INSTALLED_APPS = [ #My Apps 'institutional', #External generic public pages 'lab', #Internal pages and controllers 'shop', #External shop pages and controllers 'account', #Group of dynamics to handle users, members (profile) 'django.contrib.auth', #Here just because … -
scatter plot on map in django app raises basemap error
I created a scatter plot on indian map in jupyter notebook but when i am trying to run the same code in my djnago app. It raises ModuleNotFoundError: No module named 'mpl_toolkits.basemap' Here's the code: import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap # make up some data for scatter plot lats = np.random.randint(6, 37, size=50) lons = np.random.randint(68, 97, size=50) fig = plt.gcf() fig.set_size_inches(8, 6.5) m = Basemap(projection='cyl', \ llcrnrlat=6., urcrnrlat=37., \ llcrnrlon=68., urcrnrlon=97., \ lat_ts=20, \ resolution='c',epsg=3857) m.bluemarble(scale=1) m.drawcoastlines(color='white', linewidth=0.2) m.drawmapboundary(fill_color='#D3D3D3') x, y = m(lons, lats) plt.scatter(x, y, 10, marker='o', color='Red') plt.show() I am using the same conda interpreter in my django app. whats is the reason for this error ? -
Django AdminSite customization how to edit sites.py file? ("Properly")
My current goal is to show the number of registered Users on the admin interface for example : Users Count: {{model.count}} assuming model is already equal to the User model in order to achieve this i have to add a single line in sites.py which is located in django.contrib.admin is there any proper way to edit this file? should i copy the entire django.contrib.admin? Note: i edited the file in the venv and it works , but i want a cleaner way , where every modification is located under my admin app and not in the venv Thanks -
Exception Type:AssertionError in PasswordResetConfirmView
I am new in Django. I am developing a web-app project and want to use a setpassword form in my project that admin could reset users password without use their old password. I use a custom user model (CustomUser) . when a run this section ,result is : Request Method: GET Request URL: http://127.0.0.1:8000/account/1/changepass/ Django Version: 2.2.1 Exception Type: AssertionError urls.py: ... path('<int:pk>/changepass/',AdminChangeUserPassView.as_view(), name='change_password_user'), views.py: ... class AdminChangeUserPassView(PasswordResetConfirmView): model = CustomUser form_class = SetPasswordForm template_name = 'change_password_user.html' login_url = 'login' success_url = reverse_lazy('user_list') forms.py: ... class AdminChangeUserPassForm(SetPasswordForm): class Meta: model = CustomUser fields = ('new_password1','new_password2') what is my mistake???? -
How to write test case for fileupload in django?
In Django test case I am making use of fixtures: fixtures = ["Venter/fixtures/fixture_new_1.json"] Below given in the UploadFile test case I have worked on so far: class UploadFileTestCase(TestCase): """ Test case for user to upload xlsx file """ fixtures = ["myapp/fixtures/fixture_1.json"] def setUp(self): self.client = Client() def test_upload_valid_file(self): self.client.login(username='user1', password="1234") response = self.client.get(reverse('upload_file')) self.assertEqual(response.status_code, 200) data = open(os.path.join(MEDIA_ROOT, 'inputfile/file_1.xlsx'), 'rb') file_to_upload = SimpleUploadedFile(content = data.read(), name = data.name, content_type='multipart/form-data') valid_data = { "input_file": file_to_upload } factory = RequestFactory() request = factory.post('upload_file', valid_data, enctype='multipart/form-data') form = ExcelForm(data=valid_data, request=request) self.assertTrue(form.is_valid()) # throws error here self.assertFalse(form.errors) The ExcelForm (in forms.py) contains only one validation for the file widget: class ExcelForm(forms.ModelForm): input_file = forms.FileField( widget=forms.FileInput(), required=True, validators=[FileExtensionValidator(allowed_extensions=['xlsx'])], ) class Meta: model = File fields = ('input_file',) In the UploadFileTestCase test case, after logging in the user, I am passing the file path to the SimpleUploadedFile() and then using RequestFactory to generate a request instance that I can pass on to the ExcelForm. However for the ExcelForm() the following statement is throwing an error in my test case: self.assertTrue(form.is_valid()) # throws error: False is not True I am unsure how to proceed ahead with this. Any help would be greatly appreciated. Thanks! -
Display all error messages when validation not pass
I want to display all error messages above form when form fields are not properly validating. For example when I put number in first_name and last_name field and submit the form, the errors (2) will appear above form in li tags. At the moment all forms validators are declared in forms.py. What should I change in template/view to display not field name but ValidationError content in li tags? views.py if request.method == 'POST': person_form = PersonForm(request.POST) phone_form = PhoneForm(request.POST) email_form = EmailForm(request.POST) if person_form.is_valid() and phone_form.is_valid() and email_form.is_valid(): person = person_form.save() phone = phone_form.save(False) email = email_form.save(False) phone.person = person email.person = person phone.save() email.save() messages.success(request, f"Dodano nowy kontakt: {request.POST['first_name']} {request.POST['last_name']}") return HttpResponseRedirect('/') else: # GET person_form = PersonForm() phone_form = PhoneForm() email_form = EmailForm() return render(request, 'address_book/add_contact.html', { 'person_form':person_form, 'phone_form':phone_form, 'email_form':email_form, }) forms.py def validate_first_name(str): if any(char.isdigit() for char in str): raise forms.ValidationError('Pole Imię musi zawierać tylko litery') def validate_last_name(str): if any(char.isdigit() for char in str): raise forms.ValidationError('Pole Nazwisko musi zawierać tylko litery') class PersonForm(forms.ModelForm): first_name = forms.CharField(label='Imię', validators=[validate_first_name, ]) last_name = forms.CharField(label='Nazwisko', validators=[validate_last_name, ]) class Meta: model = Person fields = '__all__' *add_contact.html (template) * <div class="row"> <div class="addEntryBox"> {% if person_form.errors or phone_form.errors or email_form.errors %} {% … -
'django.contrib.gis.backends.postgis' isn't an available database backend (Windows)
I am struggling with configuring PostGIS db on my django 2.2.1 project. I work on Windows. What was my mistake? I installed PostgreSQL 11, PostGIS(2.5),osgeo4w, psycopg2(made "pip install..." within my environment). Here is some code from settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.backends.postgis',# 'NAME': 'Test', 'USER': 'postgres', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '5432', } } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'django_filters', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'main', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Error was : django.core.exceptions.ImproperlyConfigured: 'django.contrib.gis.backends.postgis' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Variable static file names in Django
I have many template files that have the following script at the end: {% block footer %} <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> {% endblock %} At some point, I removed the file 'js/jquery-3.3.1.min.js' and replaced it with the newer version js/jquery-3.4.1.min.js. I don't want to update all of the template files manually to the new file name. Is there any shortcut that I can use? Something like: {% block footer %} <script src="{% static 'js/{{THE_LATEST_JS_FILE_NAME}}' %}"></script> {% endblock %} -
Prepend WWW to sitemap Django
My urls are without WWW, how do I add it? <url> <loc>https://website.com/t/483/</loc> <changefreq>daily</changefreq> </url> I use the django sitemaps. https://docs.djangoproject.com/en/2.2/ref/contrib/sitemaps/ Since I force www on all my website -
adding environment variable to PYTHONPATH in a docker file
I'm trying to dockerize a Django application where I use some custom modules and in order to import them I need to add their path to PYTHONPATH the problem is when I try to do it I overwrite the PYTHONPATH so it no longer detects Django. commands i tried: ENV PYTHONPATH "${PYTONPATH}:/mypath" ENV PYTHONPATH "$PYTONPATH:/mypath" RUN export PYTHONPATH="$PYTHONPATH:/mypath" i also tried to create a .bash_profile file added the path to it and run source .bash_profile but no success : CMD echo "export PYTHONPATH='/mypath'" > ./.bash_profile CMD source ./.bash_profile the error message: Couldn't import Django. Are you sure it's installed and " 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?``` -
AWS Lambda 502 after deploy dev
This is my first time with serverless aka AWS lambda. Here is my settings zappa_settings.json { "dev": { "django_settings": "ht6m.settings", "profile_name": "aegon", "project_name": "ht6minterface", "runtime": "python3.7", "s3_bucket": "zappa-20j5uvs5p", "aws_region": "ap-southeast-1" } } Deployment went smooth and suddenly raises 502 $ zappa deploy dev Calling deploy for stage dev.. Creating ht6minterface-dev-ZappaLambdaExecutionRole IAM Role.. Creating zappa-permissions policy on ht6minterface-dev-ZappaLambdaExecutionRole IAM Role. Downloading and installing dependencies.. - psycopg2-binary==2.8.2: Downloading 100%|█████████████████████████████████████████████████████████████████████████████████████| 2.94M/2.94M [00:01<00:00, 1.95MB/s] - greenlet==0.4.15: Downloading 100%|██████████████████████████████████████████████████████████████████████████████████████| 42.4K/42.4K [00:00<00:00, 492KB/s] - gevent==1.4.0: Downloading 100%|█████████████████████████████████████████████████████████████████████████████████████| 5.44M/5.44M [00:01<00:00, 5.01MB/s] - cffi==1.12.3: Downloading 100%|███████████████████████████████████████████████████████████████████████████████████████| 431K/431K [00:00<00:00, 1.48MB/s] - sqlite==python3: Using precompiled lambda package 'python3.7' Packaging project as zip. Uploading ht6minterface-dev-1559645572.zip (42.2MiB).. 100%|█████████████████████████████████████████████████████████████████████████████████████| 44.2M/44.2M [00:22<00:00, 1.96MB/s] Scheduling.. Scheduled ht6minterface-dev-zappa-keep-warm-handler.keep_warm_callback with expression rate(4 minutes)! Uploading ht6minterface-dev-template-1559645689.json (1.6KiB).. 100%|█████████████████████████████████████████████████████████████████████████████████████| 1.65K/1.65K [00:00<00:00, 17.7KB/s] Waiting for stack ht6minterface-dev to create (this can take a bit).. 100%|███████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:16<00:00, 5.44s/res] Deploying API Gateway.. Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. I don't see any error in the zappa tail $ zappa tail Calling tail for stage dev.. [1559645713491] Instancing.. File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlockededdule [1559645730278] [DEBUG] 2019-06-04T10:55:30.278Z 466c2217-3fd7-4a2e-b97c-732866c5df54 Zappa Event: {'time': '2019-06-04T10:54:50Z', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': … -
Django : how to purge unreferenced uploaded images?
Let's take a model like this : class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) avatar = models.ImageField( upload_to='avatars/%Y/%m/%d/', blank=True, null=True) ... When an Image is uploaded, it is placed into avatars/%Y/%m/%d/ but when the image is being replaced, the previous image is not automatically removed from filesystem. The same thing may occur in case of exceptions, bad validation, debug sessions etc... So how to do some cleaning in the storage by removing unreferenced images : what is the best practice ? -
Apply a filter on multiple views in django
Im new to the django, 1)I have created three models like 1)library1 2)library2 3)library3 2)from that models,I create seperate views and separate HTML. 3)In html i get a book name as a text which is same in all html like below, <form action="" method="post"> <label for="fileInput">File input</label> <input type="text" name="book" id="fileInput"> </form> I want to apply the filter in all the three views.It should be display the filtered data when i change the views. Please send some codes or reference to sort out this problem. Thanks. -
How do I render 3d image of Dicom in Django
I am making a project of Alzheimer Detection. I take .nii or .dcm file as an input and predict it. Also, I need to render the 3d image of the scans which I can easily generate in python but I am confused on how to do the same in Django. I upload a file of the above two formats and then access it and convert it to Numpy to get the prediction I simply save the 2d images and render them on HTML but I also want a 3d render of the file. -
Unable to install django-crispy-forms via pip
I tried to install django-crispy-forms inside a virtual environment, but what I am getting is this. Collecting django-crispy-forms Could not find a version that satisfies the requirement django-crispy-forms (from versions: ) No matching distribution found for django-crispy-forms I used the following commands: pip install --upgrade django-crispy-forms pip install django-crispy-forms Can anyone help me in finding the issue! Thanks -
displaying coupon codes on google pay using python(django)
I am new to Django and am currently working on a project in which we have Django code that generates coupons. Can somebody help me how to display this coupon on google pay gift cards section as I don't quite understand how to work with google pay API and the Django code? I have searched for examples but I really couldn't get way through. I hope he question is clear and will not be closed saying overbroad.. -
X axis label in Highcharts graph in Django app
I have created Highcharts graph by this code: def chart_data(request): dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate( c=Sum('weight')).values('month', 'c') chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Weight Dispatched by Months'}, 'series': [{ 'name': 'Months', 'data': [{'name': row['month'], 'y': row["c"]} for row in dataset] }] } return JsonResponse(chart) How can I add the X axis labels such that it shows month name instead of 0 and 1 ? This is the one row of dataset from which the graph is plotted {'month': datetime.datetime(2019, 6, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>), 'c': 17600} -
The executable permission of file after downloading is getting changed. Is there any protocol or way to intact the permission?
I have deployed a Django application on AWS EC2 and application is targeted for Linux desktop users. There are some files which get downloaded in browser when clicking some links and are meant to be run by clicking on the files. I am setting the permission of the file to executable before deploying but the file permission gets changed after downloading. I am using the HTTPS protocol. Is there any protocol or way to keep the permission of files after downloading so users don't need to do chmod in terminal? The executable files are generated by using tool pyinstaller. -
Why can I save a django model instance without defining all non-null fields
When I define a non nullable field in django it allows me to save a model instance without specifying any value for this non-nullable field. This is not what I would expect. How can I force this to yield an error? Postgres 9.1 django 2.1 windows python 3.6 from django.db import models class Wwtp(models.Model): name = models.CharField(max_length=100, null=False, blank=False, unique=True) short_name = models.CharField( max_length=10, null=False, blank=False, unique=True) As expected, I am not allowed to save it with an explicit empty short_name. mdl.Wwtp.objects.create(name='Wwtp4', short_name=None) But I am allowed to save an instance of Wwtp without specifying short_name: mdl.Wwtp.objects.create(name='Wwtp4') and when I try: mdl.Wwtp.objects.create() it gives me django.db.utils.IntegrityError: duplicate key value violates unique constraint "api_wwtp_short_name_key" DETAIL: Key (short_name)=() already exists. Apparently django filled the database with an empty value for short_name while it is not allowed to do so... How can I force the database to not allow this? -
How to insert values in two different database tables simultaneously in django?
I have two models classes in django.I want to insert values in the models simultaneously using a csv file. Two models are User and User_Stats. User_stats has a foreign key from User.I want to insert some rows from the .csv file to User and some to User_stats.I am not sure how this will be done. class User(models.Model): full_name = models.CharField('Full Name',max_length=100) username = models.CharField('Username',max_length=100,unique=True) photo = models.ImageField(upload_to = 'photos/%Y/%m/%d/',blank=True) email_id = models.EmailField('Email Id',blank=True) class User_Statistics(models.Model): username = models.ForeignKey(Influencer,on_delete=models.CASCADE) total_posts = models.PositiveIntegerField('Total Posts') followers = models.PositiveIntegerField('Followers') following = models.PositiveIntegerField('Following') def write_to_db(file): with open(str(file),encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile) next(csvreader,None) for row in csvreader: _,created = User.objects.get_or_create( full_name = row[0], username = row[1], email_id = row[2], external_url = row[8], brands_worked_with = _,stats = User_Statistics.objects.get_or_create( username =Influencer.objects.get() ) What query/function should I write in User_Statistics so that both the tables are syncronized. -
Include/inherit single django form into multiple templates
I have a django form that i would like to be replicated/included among many templates of my django website similarly to the way you use the {% include %}, is there a good way to do this without having to repeat my code in all the views of the templates that require the form? here is my forms.py class ServiceForm(forms.Form): SERVICE = ( ('service 1','service 1'), ('service 2','service 2'), ('service 3','service 3'), ('service 4', 'service 4') ) name = forms.CharField(max_length=80) phone = forms.IntegerField() email = forms.EmailField() service = forms.ChoiceField(widget=forms.Select, choices=SERVICE) message = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 4, 'cols': 40}))` -
$ (this) does not work in js function Thank you for letting me know why
$(this) does not work in js function Thank you for letting me know why. button <input type="text" name="" value="{{p.content1}}" size="40" id="select-this1" class="form-control"> <button class="btn btn-outline-primary btn-sm myinput float-right" onclick="copyShortCut()">copy</button> Function function copyShortCut(){ alert("click ") document.execCommand('copy', false, $(this).parent().find('#select-this1').select()); alert("copy is completed") }