Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Impossible to connect to my postgreSQL Database
I'm using docker and I have started a new project. I have a backend in Django and I want to use a postgreSQL Database. I can't connect to my database with Django or with PGAdmin. This is what I Got when I try to connect to my database (with Django or with PGAdmin) He is a part of my docker-compose file: services: db: image: postgres container_name: db_wishlist restart: always volumes: - ./postgres-data-wishlist:/var/lib/postgresql/data env_file: - env/base/db.env - env/dev/db.env ports: - "5432:5432" networks: wishlist: aliases: - db pgadmin: image: dpage/pgadmin4 container_name: pgadmin depends_on: - db ports: - "5051:80" env_file: - env/base/db.env - env/dev/db.env environment: PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin.org PGADMIN_DEFAULT_PASSWORD: root restart: always networks: wishlist: aliases: - pgadmin api: container_name: backend build: context: .. dockerfile: Docker/Dockerfiles/Django command: python manage.py runserver 0.0.0.0:8000 volumes: - ../Django/:/api ports: - "8000:8000" env_file: - env/base/db.env - env/dev/db.env depends_on: - db links: - db:db networks: wishlist: aliases: - api Here is my db.env: POSTGRES_DB=wishlist POSTGRES_USER=maxdal1 POSTGRES_PASSWORD=demo Here is my settings.py in Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'wishlist', 'USER': 'maxdal1', 'PASSWORD': 'demo', 'HOST': 'db', 'PORT': 5432, } } Here is an additional screenshot when I try to connect to my db with PGAdmin: Error with PGAdmin I checked … -
Cannot iterate a queryset in Django
I have this model class AgeRange(models.Model): frm = models.CharField(max_length=20, blank=False) to = models.CharField(max_length=20, blank=False) Now, when I try to fill a dropdown list by values contracted from frm+to fileds. So, I run this queryset: class ReportForm(forms.ModelForm): ranges = AgeRange.objects.all().values() print(ranges) for item in ranges: print(item.frm) It prints ranges as following: <QuerySet [{'id': 2, 'frm': '1', 'to': '18'} ..... so on. Then, I get this error : print(item.frm) AttributeError: 'dict' object has no attribute 'frm' I'm confused why it could not recogniez "frm" when I try to iterate the queryset : for item in ranges: print(item.frm) -
Django form returns 404 Page not found if input type file included
I am using Django==2.1 and Pillow==7.1.2 When I include <input type="file"> in django form and post it, 404 page not found is the error i get. My template consists of this form: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if success %} <p>Success</p> {% endif %} <input type="file" name="file"> <input type="submit"> </form> views.py is: from django.shortcuts import render from myapp.models import Upload def upload(request): if request.method == "POST": myfile = request.FILES.get('file') upload = Upload(myfile=myfile) upload.save() data = { 'success': "Success" } return render(request, 'file.html', data) else: return render(request, 'file.html') urls.py is: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.upload, name="upload"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: MEDIA_ROOT = '/my/path/to/media' MEDIA_URL = '/media/' The code works fine on localhost but I get error when I host it on CPanel shared hosting. If I remove the <input type="file"> and try <input type="text"> it works properly. Also my media files are being served properly only the upload is causing issue -
Connecting django website to Google drive API
Is it possible + legal to have a website where when people register, a personal google drive is created for them? Trying to create a website where people can upload audio files in a post, which would be displayed for other users. Can the drive be used as a hosting platform for the uploaded files? If yes, then how can this be done? -
Django Model: Create instance from third party model
I have 2 Django models as demonstrated below. What could be wrong with the implementation of create_b()? What would be the alternative(s)? Any other tricks are welcome. Also, this is for learning purposes. I understand there are easier ways to accomplish what I want. I'm curious to know the issue with my implementation. Any other 'hacky' implementation is most welcome. Thank you Class A(models.Model): name = models.CharField(...) def create_b(self, some_arg): b_instance = B(self, some_attr=some_arg) ) b_instance.a = self b.save() class B(models.Model): a = models.ForeignKey(A) some_attr = models.CharField(...) -
How to resolve getting video data from Django api to reactjs
Hello so I am working on a ReactJS and Django project, I have the Django API all set and ready with all the data now I just have to get the data from React and one of the data that I want to grab is a video. So I tried to use JSON.parse() so I do not know if I am handling all this wrong but I am getting an error that says: JSON.parse: unexpected character at line 1 column 1 of the JSON data Code Below: Where I am trying to grab directly the video import React from 'react'; import './stylesheet/videoList.css'; const VideoList = (props) =>{ let videos = props.listVideos return( <div> {videos.map(content =>{ return( <div key={content.id}> <h3>{content.lecturer}</h3> <video src={JSON.parse(content.video)} className='lecture__video'/> </div> ) })} </div> ) } export default VideoList -
How to pass custom parameters to Django Custom RelatedField Serializer
I have written a Custom relational Field class CustomField(serializers.RelatedField): def to_representation(self, obj): print(self.context) return { 'id': obj.test_id, 'name': obj.test_name, } def to_internal_value(self, data): try: try: return self.get_queryset().get(test_id=data) except KeyError: raise serializers.ValidationError( 'id is a required field.' ) except ValueError: raise serializers.ValidationError( 'id must be an integer.' ) except: raise serializers.ValidationError( 'Obj does not exist.' ) This is how the CustomField is used sample_field = CustomField(queryset=SampleModel.objects.all()) If I want to pass additional parameters that will be later accessed like self.var in the to_representation and to_internal_value functions of the CustomField, how should I do that? -
Does Django ManyToMany field's set() operation clear existing relations?
Is there any difference between below 2 cases in Django ORM operation? Will there be any performance gains etc? obj.manytomanyfield.clear() obj.manytomanyfield.add(1,2,3,4,5) and obj.manytomanyfield.set([1,2,3,4,5]) -
How can I correctly make signals in django 3?
I have users app written on django3(python 3.8). and model Profile which is extending User model. So i wanna do that each time when user creates account, django automaticly makes Profile for this. I have signals.py file on user app: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender = User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user = instance) @receiver(post_save, sender = User) def save_profile(sender, instance, **kwargs): instance.profile.save() and it's my users/apps.py: from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals All working, no exceptions, errors. But It doesnt create profiles for new users. note: i had wrote print() in the ready method. But it doesnt print. When i make profile in admin site, there are no problem. But why signals doesnt work? -
Find out if an object or model is a through model
I have a list of objects (all with a ManyToOne or ManytoMany relation to a user) which I'm trying to assign to a different user. I'm using the Django Admin NestedObjects to collect all the objects related to the user. In my list with objects I have objects that are actually a through model instance. How can I determine while looping over the objects if the object I'm currently dealing with is an through model instance? Example: class SurveyQuestion(models.Model): question = models.ForeignKey('app.Question') survey = models.Foreignkey('app.Survey') order = models.IntegerField() class Question(models.Model): text = models.Charfield() class Survey(models.Model): title = models.Charfield() questions = models.ManyToManyField('app.Question', through='app.SurveyQuestion') If I encounter a SurveyQuestion instance in my list how do I know this is a through model instance? I've tried the model._meta.auto_created but this value is only True if you don't specify the through in the ManyToManyField I'm looking for a generic solution, using only the object and it's (protected) attributes. Can it be done? -
Secure way of Fetching Django Forms
I want to get and show Django form into my HTML through Fetch. As I understand, I have two options to do this: 1. The API will get {{ forms.as_ul }} and I will use it as it is inside my HTML Form tag: My code and result in API page: def FormBotAPI(request): form = UserForm(request.POST or None) if form.is_valid(): form.save() form = UserForm() context = { 'form': form.as_ul } return HttpResponse(form) 2. I will serialize my Django form into JSON and render it to HTML in client-side. By using this example: https://stackoverflow.com/a/36289460/9190503 My question: Does first method contain any security leaks? Or are they equally secure to use? Any advantages or disadvantages between them and your advice please. -
How can I add placeholder to Django generated input?
for login, I am using auth_views.LoginView and I want to add a placeholder to Django generated input, how can I do that? -
Every url in a django app only renders home.html
So, I am not really lucky with latest django version tutorials, so I've had some problems with things that changed between some versions. One of this things is: althought I do exactly as I read/watch in the tutorials I always get the same result - all urls redirect to the same HTML page. Here is my root urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('theblog.urls')), ] Here is my app urls: from django.conf.urls import url, include from .views import HomeView, ArticleDetailView urlpatterns = [ url('', HomeView.as_view(), name='home'), url('^article/<int:pk>', ArticleDetailView.as_view(), name='article-detail'), ] For example, when I go to localhost:8000/articles/1 (or any other pk), it renders home.html (HomeView class) as if it was localhost:8000/. Hope you can help me. Thanks! -
Python-decouple raises a warning while importing in settings.py? [pycharm]
[USING PYCHARM] I'm trying to use .env file details in settings.py using python-decouple. decouple installed perfectly but when I tried to import it, it raises a warning: Package containing module 'decouple' is not listed in project requirements. you can see the package details from here: https://pypi.org/project/python-decouple/3.1/ warning i'm getting while importing decouple error in terminal : raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: EMAIL_BACKEND not found. Declare it as envvar or define a default value. .env file export EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend export EMAIL_HOST=smtp.gmail.com export EMAIL_HOST_USER=xxxxxxx@gmail.com export EMAIL_USE_TLS=True export EMAIL_PORT=587 export EMAIL_HOST_PASSWORD=xxxxxxxxx; settings.py EMAIL_BACKEND = config('EMAIL_BACKEND') EMAIL_HOST = config('EMAIL_HOST') EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_USE_TLS = config('EMAIL_USE_TLS') EMAIL_PORT = config('EMAIL_PORT') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') I tried creating requirements.txt and added python-decouple==3.3 in it but it still not working. one more thing i'm using pipenv package was that can be the issue? -
How can i use regexp style for my Validation Errors Django?
I am trying to show an error when two fields are blank, i want to be one of them blank and one not. So i am raising a Validation error but it looks like this: This is the Validation error now And i want to be like the regexp type of popup, i tried different types of raising the validation but i don't know how to pop up the error like this. This is pop up validation error I have been researching for some time and i did not find something very useful, I am a beginner in Django development and i think is a javascript problem or css but i don't know how to do this. So can you guys help me? Thank you in advance, if is not a good question or is very low level delevoping i am sorry. I will post also the code from the ModelForm to let u see what i have done. class Upload_Document(forms.ModelForm): def clean(self): cleaned_data=super().clean() url=cleaned_data.get('site') file_upload=cleaned_data.get('file_upload') msg='This field or File field is required' if bool(file_upload) ==False and bool(url)==False: self.add_error('site',msg) class Meta: model= Form_Data fields =['title','author','email','document_type','keywords','abstract','authentication','site','comments','file_upload'] I will put the model too: class Form_Data(models.Model): title=models.CharField(unique=True,max_length=100,blank=False) author=models.CharField(max_length=100) email=models.EmailField(max_length=250,blank=False,null=True) document_type=models.CharField(choices=DOCUMENT_TYPES,max_length=255,blank=False,default=None) keywords=models.CharField(max_length=500) abstract=models.TextField(null=True,blank=True) authentication=models.CharField(choices=DOCUMENT_AUTHENTICATION_LEVEL,blank=False,default=None,max_length=500) … -
pass value to html table
there is a python script codal.py thats print json data peace of output: {"t_a5_b": "66350750", "t_a5_c": "62832475", "t_a5_d": "56874586", "t_a15_b": "127194761", "t_a15_c": "110163944", "t_a15_d": "62220525", "t_a34_b": "371949378", ...} then run script in view.py def external(request): out= run([sys.executable,'/home/masih/projects/django/buttonpython/buttonpython/codal.py'],shell=False,stdout=PIPE) return render(request,'home.html',{'json_view':out.stdout}) in home.html file i can get json data by {{json_view}} how can i use json_view value in html table eg: "t_a5_b": "66350750" <table style="width:100%"> <tr> <th>ta_a5_b.value</th> <th>something</th> <th>something</th> </tr> </table> -
TemplateNotFound(Error 500) raised while using Flask even though template file exists;jinja2.exceptions.TemplateNotFound
I want to implement a machine learning model but i implement flask,i am getting this error template not found even though i have template folder. I have tried all the possible solution given on stack overflow but nothings works,please help me. The basic code is to run the index page and even that is not working. from flask import Flask,render_template app = Flask(__name__, template_folder="C:/Users/sweet/Music/Rumor_Detection_Project_Copy/Front_End/templates") app.debug=False @app.route('/') def index(): with app.app_context(), app.test_request_context(): template = render_template('C:/Users/sweet/Music/Rumor_Detection_Project_Copy/Front_End/templates/index.html') if __name__ == "__main__": app.run() Thing which I have tried are: Renaming templates to template Using the proper sub-directory Debug feature both on and off Catch statement for error 500 PLEASE HELP AS THIS IS THE BASIC AND I HAVE TO DO A LOT OF OTHER THINGS TOO code with error description -
Get task args if hard timelimit exceeded
Is it possible to get task info if HardTimeLimit occured? Also in the following situation @app.task(soft_time_limit=9, max_retries=0, time_limit=10) def task(): try: do_something() except SoftTimeLimit: return is it possible that TimeLimitExceeded is raised? If yes, how can I catch it? -
How to reduce the processing time of looping with 1million rows of data with Django
I have an excel file that consists of 2k rows, For each row, I needed to loop through 500 rows in my database to output a list of dictionary = 1million list of dictionary. I needed to loop through the 1million list of dictionary to make an update or insert to the database. It's taking 20mins to finished processing, How can I reduce the execution time? I am using python with Django. I can't use bulk_update since the filter and the value to update is different for each row. Here is a pseudo-code: data_rows = [] for row in excel_rows: for map in mapping: data_dict = { 'first_name': map['first_name'], 'grade': map['grade'], 'year': row[1], 'section': row[2], } data_rows.append(data_dict) for row in data_rows: updated = Models.objects.filter(year=row['year'], section=row['section'], first_name=row['first_name']).update(grade=row['grade']) if updated == 0: Models.objects.create(year=row['year'], section=row['section'], first_name=row['first_name'], grade=row['grade']) -
Django issues with filtering objects by month and year
I'm building a website in Django and I want to make a page as an archive for the Spendings objects that I have in my models.py file, I'm trying to make a form where a users can select a year and a month and after they click submit I want to show them all the spendings that they had on that month of the year. This is my code from views.py file def archive(request): if request.method == 'POST': budget = Budget.objects.filter(user=request.user) year = datetime.strptime(request.POST['year'], '%Y') month = datetime.strptime(request.POST['month'], '%m') spendings = Spending.objects.filter( user=request.user, date_created__year=year.year, date_created__month=month.month) total_spendings = spendings_assembly(spendings) return redirect('archive') else: budget = Budget.objects.filter(user=request.user) spendings = Spending.objects.filter(user=request.user) total_spendings = spendings_assembly(spendings) context = { 'title': 'Archive', 'spendings': spendings, 'total_spendings': total_spendings, 'budget': budget, } return render(request, 'users/archive.html', context) and this is what is on my archive.html file: <div class="container"> <form method="POST" action="{% url 'archive' %}"> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-prepend"> <label class="input-group-text" for="inputGroupSelect01">Year</label> </div> <select name="year" class="custom-select" id="inputGroupSelect01"> <option value="2017">2017</option> <option value="2018">2018</option> <option value="2019">2019</option> <option value="2020">2020</option> </select> </div> <div class="input-group mb-3"> <select name="month" class="custom-select" id="inputGroupSelect02"> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> … -
Is there a way to add fields to form model from admin panel in Django 3.1?
I want to change admin panel, so that it will allow to add fields to a form model. i.e. click on button "add field" then type its name and save. Idea is on the screenshot. I find on the net either old Django 1.7-1.8 info, either non-appropriate. Actually, I need it not only in admin panel. But at least it will serve as a pointer for me. I tried jacobian style, but the problem is that it does not create a model at all. I even tried to integrate this method with dynamic model creation, but failed - it needs python manage.py makemigrateion and python manage.py migrate after each time new field is created. -
Is it possible to accept a single value to many-to-many field form in django?
TLDR: I have a form with submit button only and want to send data about page to m2m field and it doesn't work So my situation is: I have a model with m2m field and a form, that relates to that model. In the forms.py I set to that m2m field a widget of forms.HiddenInput() and I initialize that data in get_context_data method in views.py.When a user clicks the button, it responds with an error of Enter a list of values. I guess it's somehow related to the m2m field, which can only accept lists of values. Question: can one submit to a form with the m2m field with only one value? Thanks -
Drf how to retrieve/update OnetoOneField user?
I need think def get_queryset(self): in my View, how to create it right? so when I try to open url with auth user it show his OnetoOne field my urls path('someurl/', views.SomeViewSet.as_view({ 'get': 'retrieve', 'patch': 'partial_update', }), name='someurl') my View: class SomeViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = SomeSerializer my Serializer: class SomeSerializer(serializers.ModelSerializer): class Meta: model = SomeModel my Model: class SomeModel(models.Model): user = models.OneToOneField(User, models.CASCADE, related_name="somemodel") info = models.CharField(max_length=255) -
Django ignore get parameters in path
I have a simple website where I need to parse an url like this: http://127.0.0.1:8000/products/updateproduct?id=1 so I wrote the following django path for it: path('updateproduct?id=<int:id>', views.updateProduct, name='updateproduct'), I also tried it like this: path('updateproduct', views.updateProduct, name='updateproduct'), Both of these paths are appended to the /product/ part of the url like this: path('products/', include('products.urls')), essentially what I want is for django to match any path that starts with updateproduct and ignore any get variables (the ? and everything after that). Is this possible? -
Get token after creating a user
I have a problem with authenticating a user. When I send Post request to 127.0.0.1:8000/auth in postman I get status 500 and a long html in response regardless of whether I provided username and password or not. My routing: from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('auth/', obtain_auth_token) ] My User serializer: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from .models import Room class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, data): user = User.objects.create_user(**data) Token.objects.get_or_create(user=user) return user And finally instead of a token I get the following response (I couldn't paste all of it because it's too long): <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>RuntimeError at /auth</title> <style type="text/css"> html * { padding: 0; margin: 0; } body * { padding: 10px 20px; } body * * { padding: 0; } body { font: small sans-serif; background-color: #fff; color: #000; } body>div { border-bottom: 1px solid #ddd; } h1 { font-weight: normal; } h2 { margin-bottom: .8em; } h3 …