Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache Server returning html file in var/www/html but not returning my website
I have a linux server (ubuntu) and am trying to set up apache, but the server is not running my actual django server, but instead running a html file in var/www/html. Running sudo systemctl reload apache2 works fine, so I think the problem involves the .conf file in /etc/apache2/sites-available/ called infosum.conf somehow. This is for a new linux server (ubuntu). The project is running django 2.2 and apache 2.4. When running python manage.py runserver 0.0.0.0:8000, the server works fine, but when on the apache server it just returns that html file. /etc/apache2/sites-available/infosum.conf (infosum is project name) Alias /static/ /home/username/infosum/staticfiles <Directory /home/username/infosum/staticfiles> Require all granted </Directory> Alias /media/ /home/username/infosum/media/ <Directory /home/username/infosum/media> Require all granted </Directory> <Directory /home/username/infosum/infosum> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/username/infosum/infosum/wsgi.py WSGIDaemonProcess django_app python-path=/home/username/infosum python-home=/home/username/infosum/venv WSGIProcessGroup django_app /home/username/infosum/infosum/wsgi.py import os import sys sys.path.append('/home/username/infosum/infosum') # add the virtualenv site-packages path to the sys.path sys.path.append('/home/username/infosum/venv/Lib/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'infosum.settings') application = get_wsgi_application() -
Django - User Search
I'm trying to filter ListView based on post method from search bar in my basetemplate. So making it works like: Insert name --> SearchBar-->GET Method-->SearchView class(in views.py)--> render html with usernames. I have done this, but it wont work. Could you please tell me what I'm doing wrong? views.py in my user app class SearchView(ListView): model = User template_name = 'blog/list_of_users.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(SearchView, self).get_queryset() query = self.request.GET.get('search') if query: postresult = User.objects.filter(username__contains=query) result = postresult else: result = None return result urls.py in my blog app path('users_search/?search=<str:username>', user_view.SearchView.as_view(), name='user_search'), search form in html <form class="example" method="GET"> <input type="search" placeholder="ユーザー検索..." name="user_name"> <button type="submit"> 検索 </button> rendered html with user names {% for result in all_search_results %} {{ result.username }} {% empty %} add something to show no results {% endfor %} -
Django Duration Field convert to MM:SS:CC format?
I have the following model called Competition. I am trying to store the records for each swimmer as freestyle_50 as mm:ss:cc where cc refers to centisecond i.e 1/100 of second. Is there anyway i can solve this problem using duration field? Also in Forms class Competition(models.Model): swimmer = models.ForeignKey( Swimmer, blank=True, on_delete=models.CASCADE, related_name='swimmer_competition' ) freestyle_50 = models.DurationField( blank=True, null=True, ) freestyle_100 = models.DurationField( blank=True, null=True, ) -
How to Create Django Project without default Django Database table
I'm trying to make Django project but when creating that Django Project There are serval table created in Database which I dont Want. I need Django Project Without any Default Database Table Database tables are: auth_group auth_group_permission auth_user django_migration django_admin_log django_content_type I tried Disabling django.contrib.admin In Installed Apps # 'django.contrib.admin', # 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'data.apps.DataConfig', ]``` The Expected result should be Django shouldn't create Default table in database -
Overwrite fields in Django Serializer
I am new in Django and I would like to overwrite the field value in create and update method of serializer. Here is my model=> class Holiday(models.Model): HolidayDay = models.DateField() Created_DT = models.DateTimeField() Created_Usr = models.CharField(max_length=20) LastModified_Usr = models.CharField(max_length=20,blank=True) LastModified_DT = models.DateTimeField(blank=True,null=True) def __str__(self): return str(self.HolidayDay) Here is my serializer=> class HolidaySerializer(serializers.ModelSerializer): class Meta: model=Holiday fields = [ 'id', 'HolidayDay', 'Created_DT', 'Created_Usr', 'LastModified_Usr', 'LastModified_DT' ] def create(self,validated_data): validated_data['Created_Usr'] ="Testing" return Holiday.objects.create(**validated_data) I would like to update Create_usr field value in create method and LastModified_usr field in update method. But why I can't overwrite the create_usr field as "Testing"? Here is my views=> def post(self,request): holiday = request.data.get('holiday') serializer = HolidaySerializer(data=holiday) serializer.is_valid() print(serializer.errors) if serializer.is_valid(): holiday_saved=serializer.save() return Response({"success":"Holiday '{}' created successfully".format(holiday_saved.HolidayDay)}) def put(self,request,pk): save_holiday = get_object_or_404(Holiday.objects.all(),pk=pk) data = request.data.get('holiday') serializer = HolidaySerializer(instance=save_holiday,data=data,partial=True) if serializer.is_valid(raise_exception = True): holiday_saved=serializer.save() return Response({"sucess": "Holiday '{}' updated successfully".format(holiday_saved.HolidayDay)}) -
How to show more objects in my html with django (queries)
I want to show more queries within my html page but it only shows a single object. I do not know how to add more This is in mysql, html, django1.11 and python 2.7.15 views.py def administrador(request): alumno = Alumnos.objects.get(pk=1) context = { 'alumno': alumno } mapa = mapas.objects.get(pk=4) context2 = { 'mapa' : mapa} competencias = Competencias.objects.get(pk=1) context3 = { 'competencias' : competencias} return render(request, 'competencias_app/competencias.html',context) <form action="/competencia" method="POST"> {% csrf_token %} <div class="container-alumnos"> <div> <select id="carrera" name="Carrera"> <option value="1">TICS</option> <option value="2">Carrera</option> <option value="3">Carrera</option> <option value="4">Carrera</option> <option value="5">Carrera</option> </select> </div> <div> <select id="Alumno" name="Nombre"> <option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option> </select> </div> <form action=""> <label for="ID">ID</label> <input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br> <label for="apellidos">Apellidos</label> <input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br> <label for="Correo">Correo</label> <input type="input" name="Correo" disabled value="{{alumno.correo}}"><br> </form> </div> <select id="opciones" name="Semana"> <option value="1">Semana 1</option> <option value="2">Semana 2</option> <option value="3">Semana 3</option> <option value="4">Semana 4</option> <option value="5">Semana 5</option> </select> <div class="container-listas"> <select name="OS" size=9> <option selected value="0"> Elige una opción </option> <optgroup label="{{mapa.nombre}}"> <option value="1">{{competencias.nombre}}</option> <option value="2">Nombre Competencia</option> <option value="3">Nombre Competencia</option> </optgroup> <optgroup label="Mapa - Nombre"> <option value="10">Nombre Competencia</option> <option value="11">Nombre Competencia</option> <option value="12">Nombre Competencia</option> </optgroup> </select> i need add object mapa and competencias. The object alumno i dont have problem -
Django Elastic Search Help: Trouble with settings.py configuration
I new in django elastic search... When i am not getting what to put in host section: ELASTICSEARCH_DSL={ 'default': { 'hosts': '127.0.0.1:9200' }, } I didnt configure django default localhost, my django localhost server is defult http://127.0.0.1:8000/ , Whenever i put the host id in elastic_dsl, it fires me error that raise ConnectionError("N/A", str(e), e) elasticsearch.exceptions.ConnectionError: ConnectionError((<urllib3.connection.HTTPConnection object at 0x7f486a65c550>, 'Connection to 192.168.1.10 timed out. (connect timeout=10)')) caused by: ConnectTimeoutError((<urllib3.connection.HTTPConnection object at 0x7f486a65c550>, 'Connection to 192.168.1.10 timed out. (connect timeout=10)')) in my current situation, Can anyone help me to put what in ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } I am in trouble doing it.... Thank You so much -
Django - redirect after pressing comment delete
I have a code that deletes comments to from posts. def comment_remove(request, pk): comment = get_object_or_404(Comment, pk=pk) comment.delete() return redirect('Post-detail', pk=post.pk) It deletes comments, but it throws error that name 'post' is not defined I have a same function above in my views.py with the same post.pk that works fine... @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user #comment.author.photo = object.author.profile.image.url comment.save() return redirect('Post-detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) Can someone please explain me, where is the problem? Is it taking no post.pk but comment.pk? -
How do I order my objects in a random way?
I'm using Django with Python 3.7 and PostGres 9.5. I use the following to get all my objects and iterate over them ... article_set = Article.objects.all() for article in article_set: Is there a way to modify my existing query or possibly the loop so that the objects are returned in a random order each time? I would prefer not to make a second query if at all possible. -
How to add fields in django admin change page?
I want to some directions for this question. For example, I have three models: Country, State, City. In the admin:myapp_city_change url, I can change the city in a drop down list. However, the question is that there are too many choice in the list, which makes me hard to find. So I want to have three fields which are Country, State and City. These fields will be dependent drop down list so I can easily filter to the city I want. How can I achieve this? class Country(models.Model): name = models.CharField(...) class State(models.Model): name = models.CharField(...) country = models.ForeignKey(Country) class City(models.Model): name = models.CharField(...) state = models.ForeignKey(State) -
Problem uploading django project to heroku "App not compatible with buildpack:"
Im trying to deploy a django application to heroku, but the heroku-cli returns the message: remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to lisa-api. remote: To https://git.heroku.com/lisa-api.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/lisa-api.git' I have seted the buildpack to heroku/python, it not worked so i have also added the following: heroku create --buildpack https://github.com/heroku/heroku-buildpack-python.git But still not working :s Searching for the error on the internet, people say that this may be because theres not a requirements.txt file on the project root, but, actually i have the file. My runtime file: python-3.6.5 My Procfile: web: gunicorn lisa.wsgi --log-file - The code is on my github repo: https://github.com/brunolcarli/Lisa/tree/master What am i missing? -
How to Create a Unique One Time Reset Password Link in Django?
I have Django website which users can register and login with their phone number. Recently I decide to add a recover password with phone number part to my site,I read Authentication Views in Django which users can reset their password by sending them an email but first of all it use email to reset password and second it use django built-in views, but I want a function in my view which generate a unique one time reset password link then I send this link to them with my sms api so they can reset their password using this link. So how can I generate reset password link in a secure way? -
Django - trying to upload a file which has a validator throws strange error
So I'm trying to make a form with a filefield. That filefield has a validator which checks for the file size. Unfortunately, when running the validators with full_clean, I get this error: {'CV': ['This field cannot be blank.']} C:\Users\PC\Desktop\bestVENV\myvenv\bestWEB\oferte\views.py in incarcarecv cv_upload.full_clean() The strange thing is that the file size does not exceed the limit so it should be working, but I just can't get why it does not. views.py from django.shortcuts import render, get_object_or_404 from .models import Oferta, CV from django.contrib import messages from django.core.paginator import Paginator # Create your views here. def incarcarecv(req): context = { 'title': "Incarcare CV | Best DAVNIC73" } if req.method == 'POST': nume = req.POST['nume'] prenume = req.POST['prenume'] telefon = req.POST['telefon'] email = req.POST['email'] cv = req.FILES['CV'] if(req.user.is_authenticated): cv_upload = CV( solicitant=req.user, nume=nume, prenume=prenume, telefon=telefon, emailContact=email ) cv_upload.full_clean() cv_upload.CV.save(cv.name, cv) cv_upload.save() req.user.profile.cvuri.append(cv_upload.id) req.user.profile.save() messages.success(req, 'CV depus cu succes!') else: messages.error(req, 'Trebuie sa fii logat pentru a depune CV-ul!') return render(req, "../templates/pagini/incarcare-cv.html", context) validators.py from django.core.exceptions import ValidationError def validate_file_size(value): filesize=value.size if filesize > 99999999999: raise ValidationError("Fisierul poate avea maxim 5MB!") else: return value models.py from django.db import models from django.contrib.auth.models import User from .validators import validate_file_size # Create your models here. class CV(models.Model): … -
Form Validation in Django on formset - multiple image upload
I am getting the request data from my view, but can´t validate my data from my form, I tried so many different things, I want to multiple upload image with formset. Any help is appreciated! I only have an imagefield and reference to my Post model in my model. My form is only consisting of my image field. images <MultiValueDict: {'files[]': [<TemporaryUploadedFile: Screenshot 2019-06-18 at 18.11.47.png (image/png)>, <TemporaryUploadedFile: touch.of.boho-white-home-about_seeking_and_finding.jpg (image/jpeg)>, <TemporaryUploadedFile: Screenshot 2019-06-18 at 19.38.40.png (image/png)>, <TemporaryUploadedFile: touch.of.boho-white-home-about_seeking_and_finding -boheme-lifestyle.jpg (image/jpeg)>]}> Model.py from django.db import models from blog.models import Post class Catalog_images(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to='catalog/', blank=True,null=True) #title = models.TextField(max_length=255, null=True, blank=True) def __str__(self): return self.post.title + " Image" Forms.py class ImageUploadForm(forms.ModelForm): image = forms.ImageField(label='image') class Meta: model = Catalog_images fields = ('image',) Views.py def catalog_upload_view(request): template_name = 'utils/catalog-upload.html' ImageFormset = modelformset_factory(Catalog_images, fields=('image',), extra=4) #ImageFormset = modelformset_factory(Catalog_images, form=ImageUploadForm, extra=4) if request.method == 'POST': print(request.POST) image_form = ImageUploadForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None, queryset=Catalog_images.objects.none()) print('images', request.FILES) if image_form.is_valid() and formset.is_valid(): print('form is valid') post = image_form.save(commit=False) post.user = request.user post.save() for f in formset: print(f) try: photo = Catalog_images(post=post, image=f.cleaned_data['image']) print(photo) photo.save() messages.success(request, 'You Successfully uploaded to MYNORDICROOM') except Exception as e: break else: print('form not … -
Django manage.py migrate ValidationError
While running django when I use python manage.py migrate I am encountering the following error after running python manage.py makemigrations File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 433, in add_field definition, params = self.column_sql(model, field, include_default=True) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 161, in column_sql default_value = self.effective_default(field) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 233, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 789, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1429, in get_db_prep_value value = self.get_prep_value(value) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1408, in get_prep_value value = super().get_prep_value(value) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1268, in get_prep_value return self.to_python(value) File "/Users/rasikraj/Desktop/eb-virt/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1393, in to_python … -
How to access submitted data (field value) in django form __init__ method if this form is a part of inline formset?
I have form class OrderItemsImportForm( forms.ModelForm ): oem = forms.CharField(max_length=128, required=True) field_order = ['oem', ....] class Meta: model = Orderitem fields = (.....,) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.is_bound: oem = self.data.get('oem') else: oem = kwargs['initial']['oem'] self.fields['part'].queryset = Part.objects.filter(oem=oem) But the code oem = self.data.get('oem') returns None, because if I print self.data it contains something like: data = <QueryDict: {'csrfmiddlewaretoken': ['HOCNE7mZmuIXz0RvabrEBFlGQU1qwvThtdj2xtMw8n6tsYGbhq2jNze1JFHSVcIL'], 'ordercomposingitem_set-TOTAL_FORMS': ['2'], 'ordercomposingitem_set-INITIAL_FORMS': ['0'], 'ordercomposingitem_set-MIN_NUM_FORMS': ['0'], 'ordercomposingitem_set-MAX_NUM_FORMS': ['1000'], 'ordercomposingitem_set-0-id': [''], 'ordercomposingitem_set-0-order': [''], 'ordercomposingitem_set-0-oem': ['8844026100'], 'ordercomposingitem_set-0-count': ['100'], 'ordercomposingitem_set-0-price_prefered': ['0'], 'ordercomposingitem_set-0-part': ['88'], 'ordercomposingitem_set-0-user_reference': ['12345'], 'ordercomposingitem_set-0-user_partnumber': ['MY-12345'], 'ordercomposingitem_set-0-user_partbrand': ['My-Supa-Brand'], 'ordercomposingitem_set-0-user_partname': ['My Partname'], 'ordercomposingitem_set-0-user_price': ['100'], 'ordercomposingitem_set-0-user_comment': ['Please make it better!'], 'ordercomposingitem_set-1-id': [''], 'ordercomposingitem_set-1-order': [''], 'ordercomposingitem_set-1-oem': ['31170RNAA02'], 'ordercomposingitem_set-1-count': ['150'], 'ordercomposingitem_set-1-price_prefered': ['0'], 'ordercomposingitem_set-1-part': [''], 'ordercomposingitem_set-1-user_reference': ['789456'], 'ordercomposingitem_set-1-user_partnumber': [''], 'ordercomposingitem_set-1-user_partbrand': ['My-Supa-Brand'], 'ordercomposingitem_set-1-user_partname': [''], 'ordercomposingitem_set-1-user_price': [''], 'ordercomposingitem_set-1-user_comment': ['Hello!'], 'action': ['save']}> where there are no clean "oem" field, only "ordercomposingitem_set-0-oem" and like that. How can I access oem field value? -
having trouble setting up python social auth to log in to facebook, facebook giving error that test user is not registered
I am running my django app on a remote server. When I try to log in to facebook using python-social-auth, I get the following error App Not Setup: This app is still in development mode, and you don't have access to it. Switch to a registered test user or ask an app admin for permissions. I'm using a tutorial from simpleisbetterthancomplex.com I've named the app that demonstrates the login "test_social" with a prefix "tsoc" as in /tsoc/login/facebook, etc. I've managed to get it working on my localhost, I got it ssl certification using letsencrypt.org it's just getting it to work remotely is very hard, I'm sure there is something I'm missing here. I can't even use the test users I made to log in. If I am already logged in as a nomral user I get the following error: App Not Setup: This app is still in development mode, and you don't have access to it. Switch to a registered test user or ask an app admin for permissions. screenshot of attempted sign-in while already logged in This happens if I'm signed in as the app administrator or if I'm signed in as an an accepted app developer. If I'm … -
Django CharField option to ensure only one value is stored
I am working with the following code: class UserDescription(models.Model): fullname = models.CharField(max_length = 100) # profilePic = models.CharField(max_length=100, default="avatar.png") city=models.CharField(max_length=100,null=True, blank=True) state=models.CharField(max_length=100,null=True, blank=True) country=models.CharField(max_length=100,null=True, blank=True) occupation=models.CharField(max_length=100,null=True, blank=True) shortdescription=models.CharField(max_length=300,null=True, blank=True) Is there an option using CharField such that every time the update in the model happens only the last value stays. i.e. previous values get overwritten. -
TypeError: view must be a callable or a list/tuple in the case of include().django2.2.2
TRYING TO MAKE MY FIRST APP in urls.py I have this code from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', 'blogs.views.home', name='home'), path('admin/', include(admin.site.urls)), ] ` I get this error TypeError: view must be a callable or a list/tuple in the case of include(). WHEN I CHANGE IT WITHOUT QUOTATION TO from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', blogs.views.home, name='home'), path('admin/', include(admin.site.urls)), ] i GET THIS ERROR NameError: name 'blogs' is not defined -
ElasticSearch: Django ConnectionError after adding documents.py
I run python3 manage.py test and it shows me everything is ok i try to add post in django admin templates, i can add post nicely... But the problem is, whenever, i add documents.py in my django app, my test doesn't pass, even i cant post from admin template too... Whats wrong with my documents.py? from django_elasticsearch_dsl import DocType from django_elasticsearch_dsl.registries import registry from blog2.models import Article @registry.register_document class ArticleDocument(DocType): class Index: name = 'cars' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Article fields = [ 'title', 'body', ] After i add above file, it fires me this error in console whenever i try to add post from admin template or i run my test... File "/home/pyking/.local/lib/python3.6/site-packages/elasticsearch/connection/http_urllib3.py", line 244, in perform_request raise ConnectionError("N/A", str(e), e) elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f6c81b59d68>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f6c81b59d68>: Failed to establish a new connection: [Errno 111] Connection refused) this is my models.py below from django.db import models import uuid class Organization(models.Model): organization_name = models.CharField(max_length=50) contact = models.CharField(max_length=12, unique=True) def __str__(self): return self.organization_name class Author(models.Model): name = models.CharField(max_length=40) detail = models.TextField() organization = models.ForeignKey(Organization, on_delete=models.DO_NOTHING) def __str__(self): return self.name class … -
[Django]How to return value to view after select item from dropdown list
Though I read django document but I am still confused how to use request.POST to get value from dropdown list to make query to databse.. And how to return the details of selected value back to frontend in order to show the result? Suppose I can select "region" in dropdown box and it would return the detail of that restaurant under that region category Class Restaurant class Restaurant(models.Model): restId = models.AutoField(db_column='restId', primary_key=True) restName = models.TextField(db_column='restName') phone = models.IntegerField() address = models.TextField() ratings = models.DecimalField(max_digits=2, decimal_places=1) cuisine = models.TextField() region = models.TextField() last_modify_date = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = "restaurant" views.py def index_view(request): rest_list = Restaurant.objects.all() context = { 'rest_list': rest_list } return render(request, 'index.html', context) index.html <h1>Index</h1> <form action="selectRegion" method="post"> <select name = "dropdown"> {% for rest in rest_list %} <option value = "{{ rest.region }}">{{ rest.region }}</option> {% endfor %} </select> <input type="submit" value="Select"> </form> -
Dynamic field on Django model
I have my models.py class Restaurant(models.Model): name = models.CharField(max_length=100, blank=False) opening_time = models.TimeField(blank=False) closing_time = models.TimeField(blank=False) def __str__(self): return self.name @property def is_open(self): return True if self.opening_time <= datetime.now().time() < self.closing_time else False And, my serializer.py: class RestaurantSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Restaurant fields = ('pk', 'name', 'opening_time', 'closing_time') I have this property in the model that checks if the restaurant is open. How can I have the is_open property check if it's open every time the person gets the object from this model. I was thinking about using Celery to check if it's open, but it sounds like an overkill solution. Of course, I would like this change to affect the serializer, so it should be something done on the model, I would think. -
CreateAPIView returns TypeError with st() function, when accessing endpoint via browser
I am writing API based on Django (2.2.2) and Django Rest Framework (3.9.4). Goal is to create simple message system. After creating endpoint for creating message, I get TypeError: TypeError at /api/v1/message/create/ str returned non-string (type Message) The 'message_body' in the DB contains PL characteristic characters. " I tried both serializer.Serializer and serializer.ModelSerializer for my serializer, CreateAPIView and ListCreateAPIView for the view. What is really interesting, endpoint for listing out the messages is working just fine. This is nearly copy-paste code from my other endpoint (also CreateAPIView), which is working just as expected. I also tried some encoding stuff on str(self), but guess not properly. sample.json: (fixtures to test API in the browser) { "model": "core.message", "pk": 1, "fields": { "chat": 1, "message_body": "Wiadomość testowa 1", "sender": "user", "sent": "2019-05-05T10:20:37+01:00", "is_viewed": true } } models.py: class Message(models.Model): """ Model representing single message in DB """ chat = models.ForeignKey( 'Chat', on_delete=models.CASCADE, unique=False ) message_body = models.TextField(blank=False, null=False) sender = models.CharField(max_length=4) sent = models.DateTimeField(auto_now_add=True) is_viewed = models.BooleanField(default=False) def __unicode__(self): return self.message_body def __str__(self): return self.message_body.decode('utf8') views.py: from rest_framework import generics, status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from message.serializers import ( ListMessageSerializer, CreateMessageSerializer ) from core.models … -
Django can't display the image saved in the database
I wrote two templates in Django "index.html" and "detail.html". In both templates, I display png, in the template "index" the graphics are displayed correctly, and in the template "detail" has the status "src (unknown)". detail.html (details.html should display only one graphic) <section class="jumbotron text-center"> <div class="container"> <h1 class="jumbotron-heading">Course Detail</h1> <p class="lead text-muted"> {{ films.summary}}.</p> <img class = "card-img" src="{{film.image.url}}" > </img> <p> <a href="{% url 'index' %}" class="btn btn-primary my-2">Back</a> </p> </div> </section> index.html <div class="row"> {% for film in films.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <a href="{% url 'detail' film.id %}"> <img class = "card-img" src="{{film.image.url}}" > </img> </a> <div class="card-body"> <p class="card-text"> {{film.summary}} </p> </div> </div> </div> {% endfor %} </div> </div> views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Films # Create your views here. def index(request): films = Films.objects.all() return render(request, 'films/index.html',{'films':films}) def detail(request, films_id): films_detail = get_object_or_404(Films,pk=films_id) return render(request, 'films/detail.html',{'films':films_detail}) urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name="index"), path('<int:films_id>', views.detail, name="detail"), ] -
Django- admin: compare unique values before save
I have two models user and telephone, where telephone is displayed under user-admin. User can have only one main telephone number (so only one number can be set as main). I tried to use unique_together but that didnt work as i wanted. My models: class User(models.Model): name = models.CharField(...) class Telephone(models.Model): number = models.CharField(...) main = models.NullBooleanField(choices=((None, "Normal"),(True, "Main")) user = models.ForeignKey(User, on_delete=models.SET_NULL) my problem is: i want to change first telephone number from main to normal and set second number from normal to main at same time in django-admin. After i press save.. i get ValueError that said unique error. i tried to rewrite save and clean method in model, but there i get only one telephone number at time.. so i cant compare with other numbers that belongs under user So my question is: Is there a way how to get a list of changes made in admin to compare fields before saving to database?