Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I modify a widget/field so that it is filtered further in Django/Python?
I have a form with a field in my models called employee_number, which is tied to another model, called Salesman, which holds all the data with all the employee names, numbers, dept, etc. Currently it works by only allowing submission of the form if the employee number entered is is salesman. What I'm trying to do is also filter it so that only employees that are part of team "MM" and "OM" and whose employee_status is "A" are the only ones able to submit. forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_name = models.CharField(max_length=25) employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True) def __str__(self): return self.employee_number alldata/models.py class Salesman(models.Model): id = models.IntegerField(db_column='number', primary_key=True) team = models.CharField(max_length=2) employee_status = models.CharField(max_length=1, blank=True) -
Create Subdomain for each user
I want to know, what is the best efficient way to give each user a subdomain? I've seen these topics: Link1 and Link2 but these are too old (10 years ago). Is there any better way? -
Writing Form Data To SQLLite Database
I am trying to write my data from my forms data and I'm getting the following error. FYI: Total noob on python and django. AttributeError at /forms/ 'NewStudentForm' object has no attribute 'save' From reading online its because I'm doing in my forms.py is (forms.Forms) and it doesn't use the .save() attribute. What is the easiest way to fix this ? Thank you! #forms.py from django import forms from .models import StudentCheck class NewStudentForm(forms.Form): startdate = forms.DateField(label = "Start Date", required= True) esy = forms.BooleanField(label = "ESY", required= False) ten_month_school_year = forms.BooleanField(label= "Ten Month School Year", required= False) other = forms.BooleanField(required= False) intakedate = forms.DateField(label = "Intake Date", required= True) grade = forms.CharField(label= "Grade",max_length=2) firstname = forms.CharField(label = "First Name", max_length=50) lastname = forms.CharField(label = "Last Name", max_length=60) address = forms.CharField(label = "Address", max_length=100) city = forms.CharField(label = "City", max_length=100) state = forms.CharField(label = "State", max_length=30) zipcode = forms.CharField(label = "Zip Code",max_length=5) parent_one_name = forms.CharField(label = "Parent 1",max_length=100) parent_one_phone = forms.CharField(label = "Phone",max_length=12) parent_one_email = forms.CharField(label = "Email",max_length=100) parent_two_name = forms.CharField(label= "Parent 2",max_length=100) parent_two_phone = forms.CharField(label= "Phone",max_length=12) parent_two_email = forms.CharField(label = "Email", max_length=100) #models.py from django.db import models from django.utils import timezone # Create your models here. class StudentCheck (models.Model): … -
django 404 error http://*********:8080/ciopsmenu/searchlit/
I am trying to navigate to an app from a link on a page(the ciopsmenu) which is a view located in the homepage app but I am getting a 404 error. I tried to adding the path(searchLit/urls.py) using the include module to my project level urls.py file and I also tried adding the same line to my homepage/urls.py file #ciopsdb/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('homepage.urls')), path('ciopsmenu/searchlit/', include('searchLit.urls')), ] #homepage/urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('accounts/', include('django.contrib.auth.urls')), path('ciopsmenu/', views.ciopsMainMenu, name='ciopsMainMenu'), path('ciopsmenu/searchlit/',include('searchLit.urls')), ] #installed apps from settings.py INSTALLED_APPS = [ 'searchLit', 'homepage', 'base', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mod_wsgi.server', Page not found (404) Request Method: GET Request URL: http://*******:8080/ciopsmenu/searchlit/ Using the URLconf defined in ciopsdb.urls, Django tried these URL patterns, in this order: admin/ [name='index'] accounts/ ciopsmenu/ [name='ciopsMainMenu'] ciopsmenu/searchlit/ ciopsmenu/searchlit/ [name='searchLit'] ciopsmenu/searchlit/ ciopsmenu/searchlit/ [name='searchLit'] The current path, ciopsmenu/searchlit/, didn't match any of these. -
Formset validation not working - receiving KeyError
I am trying my first formset and stuck on validation. I have combined a normal form ProgramSelector with a formset. Everything works so far in terms of saving the data but validation is giving me a real headache. I am simply not understanding how this part works. How do I get this to display errors in the forms like it normally would? Right now I am getting KeyError 'headline' and the ProgramSelector clean() doesn't seem to be doing anything. I have searched every post I can find and nothing seems to working or helping me figure this out so here I am. Thanks! model: class PropertySubmission(models.Model): BANNER_CHOICES = ( ('NB', 'No Banner'), ('FL', 'For Lease'), ('FS', 'For Sale'), ('NL', 'New Listing'), ('SD', 'Sold'), ('LD', 'Leased'), ('RD', 'Reduced'), ('NP', 'New Price'), ('SC', 'Sold Conditionally'), ('CB', 'Custom Banner'), ) image = models.ImageField(upload_to=user_directory_path, blank=True) #image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(300, 250)], format='JPEG', options={'quality':60}) mls_number = models.CharField(max_length=8, blank=True) headline = models.CharField(max_length=30) details = RichTextField() banner = models.CharField(max_length=2, choices=BANNER_CHOICES) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) program_code = models.ManyToManyField(Program) product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) production_cycle = models.ManyToManyField('ProductionCycle', null=True, blank=True) shell = models.ForeignKey('Shell', on_delete=models.SET_NULL, null=True, blank=True) card_delivery_instructions = models.CharField(max_length=1000, blank=True) card_delivery_instructions_image = models.ImageField(upload_to=card_delivery_instructions_image_path, blank=True) forms: … -
Deploying Django on AWS Beanstalk Getting Erorr 500 WSGI Error
Been on this for hours. Trying to deploy a Django APP on AWS Elastic Beanstalk, but since been having errors. Logs: [Mon Nov 04 20:29:56.672898 2019] [:error] [pid 5877] [remote 172.31.27.176:8] raise RuntimeError("populate() isn't reentrant") [Mon Nov 04 20:29:56.672912 2019] [:error] [pid 5877] [remote 172.31.27.176:8] RuntimeError: populate() isn't reentrant [Mon Nov 04 20:29:57.139970 2019] [:error] [pid 5877] [remote 172.31.27.176:8] mod_wsgi (pid=5877): Target WSGI script '/opt/python/current/app/vendease/wsgi.py' cannot be loaded as Python module. [Mon Nov 04 20:29:57.140026 2019] [:error] [pid 5877] [remote 172.31.27.176:8] mod_wsgi (pid=5877): Exception occurred processing WSGI script '/opt/python/current/app/vendease/wsgi.py'. [Mon Nov 04 20:29:57.140136 2019] [:error] [pid 5877] [remote 172.31.27.176:8] Traceback (most recent call last): [Mon Nov 04 20:29:57.140169 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/current/app/vendease/wsgi.py", line 16, in <module> [Mon Nov 04 20:29:57.140174 2019] [:error] [pid 5877] [remote 172.31.27.176:8] application = get_wsgi_application() [Mon Nov 04 20:29:57.140180 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Nov 04 20:29:57.140184 2019] [:error] [pid 5877] [remote 172.31.27.176:8] django.setup(set_prefix=False) [Mon Nov 04 20:29:57.140189 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [Mon Nov 04 20:29:57.140193 2019] [:error] [pid 5877] [remote 172.31.27.176:8] apps.populate(settings.INSTALLED_APPS) [Mon Nov 04 20:29:57.140198 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line … -
How to create a readonly field inside Django ModelForm from a value in the Model
I have the below code for a model in Django: from django.db import models from django.db.models.signals import pre_save from django.utils.text import slugify from django.conf import settings class Book(models.Model): added_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_add', on_delete=models.CASCADE) last_edited_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_edit', on_delete=models.CASCADE) title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) slug = models.SlugField() updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title def pre_save_book(sender, instance, *args, **kwargs): slug = slugify(instance.title) instance.slug = slug pre_save.connect(pre_save_book, sender=Book) My objective is to have two different kinds of forms one for changing a Book object and another one for adding a Book object. Hence i have the below code for admin.py and forms.py: admin.py: from django.contrib import admin from .models import Book from .forms import BookAddForm, BookChangeForm class BookAdmin(admin.ModelAdmin): readonly_fields = ["authorname"] def authorname(self, obj, *args, **kwargs): return obj.added_by.username def get_form(self, request, obj=None, **kwargs): if not obj: self.form = BookAddForm else: self.form = BookChangeForm return super().get_form(request, obj, **kwargs) def save_model(self, request, obj, form, change): obj.added_by = request.user super().save_model(request, obj, form, change) admin.site.register(Book, BookAdmin) forms.py: from django import forms from .models import Book class BookAddForm(forms.ModelForm): class Meta: model = Book fields = [ 'title', 'description' ] exclude = ['authorname'] class BookChangeForm(forms.ModelForm): … -
Is there a way to remove directories along with removing media files in Django?
As far as I know, it's quite simple to remove a media file when calling the delete() method. However, I'd like to ask if there's also a way to remove the path that the media file was located. (wait, is it even a good practice to remove all the empty directories?) def delete(request, post_pk): ... post = Post.objects.get(pk=post_pk) post.image.delete() # I want to delete the empty directories as well here post.delete() ... -
sys.exit() in django web application
While debugging a django application codebase I came across some pieces of code as below: try: ...some business logic... except Exception as e: logging.exception(...) sys.exit() I am not able to understand how this web API would behave in case of an exception? Our web app has more than 1 worker which I understand, are modeled as differed processes by django. Per sys.exit documentation, the process will only exit if called from the main thread. How would this behave when there are multiple workers and the workers spawn multiple threads? Does django replace the worker process with another process if the worker's main thread encountered sys.exit and the worker process was shut down? Is it even a good idea to have sys.exit in an exception block or anywhere in the app for that matter? -
Always empty aggregations django elasticsearch
I use django-elasticsearch-dsl and I have the problem that aggregations always return empty value to me. I need all the different publishers and the different authors of the search results. Document: @registry.register_document class BookDocument(Document): author = fields.ObjectField(properties={ 'name': fields.TextField(), 'name_reverse': fields.TextField(), 'pk': fields.IntegerField(), 'slug': fields.TextField(), }) editorial = fields.NestedField(properties={ 'name': fields.TextField(), 'slug': fields.TextField(), 'pk': fields.IntegerField(), }, include_in_root=True) class Index: name = 'books' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Book fields = [ 'title', 'isbn', ] related_models = [Author, Editorial] # para asegurarnos que cuando se actualice un author, se reindexa los libros def get_queryset(self): """Not mandatory but to improve performance we can select related in one sql request""" return super(BookDocument, self).get_queryset().select_related( 'author', 'editorial' ) def get_instances_from_related(self, related_instance): """If related_models is set, define how to retrieve the Book instance(s) from the related model. The related_models option should be used with caution because it can lead in the index to the updating of a lot of items. """ if isinstance(related_instance, Author): return related_instance.book_set.all() elif isinstance(related_instance, Editorial): return related_instance.book_set.all() Search: from elasticsearch import Elasticsearch from elasticsearch_dsl import Search from elasticsearch_dsl import Q from elasticsearch_dsl.query import MultiMatch, Match from elasticsearch_dsl import A s = Search(index='books') s = s.query("match", title="SECRET") s … -
Starting a django application during the unit test
I'm currently using python 2.7, django 1.6.5 and running unit tests on API files. Below is the file from which I'm trying to run all the unit test files Integration.py loader= unittest.TestLoader() start_dir='tp/pyfiles' suite=loader.discover(start_dir) runner = unittest.TextTestRunner() runner.run(suite) Below is the part of the code I've written for API testing test_file1.py class api_test(unittesting.TestCase): def setUp(self): print "SetUp Function called" command = 'gnome -terminal -e \'python manage.py runserver ' + 1585 + '\'' try: os.system(command) print "SetUp Done" except Exception as e: print e Is there is any other way to start the server rather than the above-mentioned command ?? Also, what is the correct way to run integration.py? 1.python -m unittest integration or 2.python integration.py If I'm running with the first one, I'm getting Ran 4 Tests OK Ran 0 Tests Ok else Ran 4 Tests OK Please suggest -
My view function is added to url on return render. How can I avoid this?
When a user does not fill in all information, they should be sent back to http://127.0.0.1:8000/content/readerpage/40, but instead they are sent to http://127.0.0.1:8000/content/readerpage/40/add_review How can I avoid this? def add_review(request, content_id): content = get_object_or_404(Content, pk=content_id) if request.POST['readability'] and request.POST['readability_rating'] and request.POST['actionability'] and request.POST['actionability_rating'] and request.POST['general_comments']: review = Review() review.readability = request.POST['readability'] review.readability_rating = request.POST['readability_rating'] review.actionability = request.POST['actionability'] review.actionability_rating = request.POST['actionability_rating'] review.general_comments = request.POST['general_comments'] review.save() return redirect('home') else: return render(request, 'content/readerpage.html', {'error': 'You need to fill in all information'}) urlpatterns = [ path('', views.home, name='home'), path('add/', views.add, name='add'), path('<int:content_id>', views.details, name='details'), path('link/<int:content_id>', views.link, name='link'), path('readerpage/<int:content_id>', views.readerpage, name='readerpage'), path('readerpage/<int:content_id>/add_review', views.add_review, name='add_review'), ] Thanks for reading this. -
How to filter/get second to last most recent record to update a field in Django?
I have a model that keeps track of enter/leave times. I am trying to add constraints to make the data more accurate. Currently, when someone "Enters", it creates a record, saves the time in timestamp and then redirects. If the person then tries to enter again, it creates a new record with a new timestamp. What I'm trying to add now is that, if the person has a previous entry without an exit timestamp then that record (which would be the second to last most recent entry), would be flagged by updating the time_exceptions field to 'N'. Currently, it changes all the fields to 'N', regardless of whether there's an exit or not, as shown below. class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num)).count() > 1: EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_exceptions='N') return HttpResponseRedirect(self.request.path_info) I tried the following, but I get a expected string or bytes-like object and while it still creates a new record before crashing, it does not update the time_exceptions of … -
Defined variable,says there is not 'n1',key
MultiValueDictKeyError at /home/ 'n1' Request Method: GET Request URL: http://127.0.0.1:8000/home/ Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'n1' Exception Location: /home/sanzu/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py in __getitem__, line 80 Python Executable: /home/sanzu/anaconda3/bin/python Python Version: 3.7.3 Python Path: ['/home/sanzu/PycharmProjects/django_site', '/home/sanzu/anaconda3/lib/python37.zip', '/home/sanzu/anaconda3/lib/python3.7', '/home/sanzu/anaconda3/lib/python3.7/lib-dynload', '/home/sanzu/anaconda3/lib/python3.7/site-packages'] Server time: Mon, 4 Nov 2019 18:29:40 +0000 Traceback Switch to copy-and-paste view /home/sanzu/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py in __getitem__ list_ = super().__getitem__(key) … ▼ Local vars Variable Value __class__ <class 'django.utils.datastructures.MultiValueDict'> key 'n1' self <QueryDict: {}> During handling of the above exception ('n1'), another exception occurred: /home/sanzu/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) … ▼ Local vars Variable Value exc MultiValueDictKeyError('n1') get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x7f2e177ac208>> request <WSGIRequest: GET '/home/'> /home/sanzu/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▼ Local vars Variable Value callback <function page at 0x7f2e16974048> callback_args () callback_kwargs {} middleware_method <bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at 0x7f2e1687c080>> request <WSGIRequest: GET '/home/'> resolver <URLResolver 'django_site.urls' (None:None) '^/'> resolver_match ResolverMatch(func=san.views.page, args=(), kwargs={}, url_name=None, app_names=[], namespaces=[], route=home/) response None self <django.core.handlers.wsgi.WSGIHandler object at 0x7f2e177ac208> wrapped_callback <function page at 0x7f2e16974048> /home/sanzu/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▼ Local vars Variable Value callback <function page at 0x7f2e16974048> callback_args () callback_kwargs {} middleware_method <bound method CsrfViewMiddleware.process_view of <django.middleware.csrf.CsrfViewMiddleware object at … -
How do I display the result on the current page? Django, Ajax
On the main page I have a text box. When I type text into it, after clicking the button I want to display that text below. With ajax I get the text entered and pass it to views.py. When rendering, the result I need is displayed on /localhost:8000/vk_u/ How do I display the result on the current page (localhost: 8000/)? Thanks //forms.py from django import forms from .models import * class VK_LINK_Form(forms.Form): enter_link = forms.CharField(widget = forms.TextInput(attrs={'id':'link_vk_enter'})) //urls.py from django.urls import path, include from . import views from django.http import HttpResponse urlpatterns = [ path('', views.index, name = 'index'), path('vk_u/', views.vk_u, name = 'vk_u'), ] //js $(document).on('submit','#vkht_form', function(e){ e.preventDefault(); var link_post_input = $(document.getElementById("link_vk_enter")).val() $.ajax({ type: 'POST', url: '/vk_u/', data:{ link_post_input: link_post_input, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, }); }); ] //views.py def vk_u(request): link_post_input = request.POST.get('link_post_input') return render(request, "mainApp/homePage.html", {"link_post_input": link_post_input,}) <!-- html --> <body> <div> <form action="" method="GET" id="vkht_form"> {% csrf_token %} {{ form }} text: {{ text_post_input }} <input type="submit" value="CLICK"> </form> </div> </body> -
Django giving 500 instead of 404 for unknown URLs when debug is false
Django = 2.1.x Python = 3.7.x If Debug is True - it returns a 404. If Debug is False - it gives a 500 error. My project.urls file looks like this: urlpatterns = [ path("admin/", admin.site.urls), path("", app1.views.log_in, name="log_in"), path("log_in/", app1.views.log_in, name="log_in"), path("logout/", app1.views.log_out, name="logout"), path("launcher/", app1.views.launcher, name="launcher"), path("app2/", include("app2.urls")), path("app3/", include("app3.urls")), ] My directory structure looks like this: Project_directory static_directory ...js files and css files and such... templates_directory 400.html 403.html 404.html 500.html base.html (all apps extend this page, which works great) project_directory urls.py settings.py ...other files... app1_directory views.py models.py templates_directory app1 ...template files... ...other app1 files/directories... app2_directory ...app2 directories and files... app3_directory ...app3 directories and files... When I python manage.py runserver and I hit a URL I know doesn't exist (like http://project/randomtrash.php) it gives an appropriate 404 if DEBUG = True If DEBUG = False then hitting that same URL will give a 500 and the 500.html displays. Important parts of my settings.py look like this: # These two settings are only for testing purposes and are different # In production DEBUG = False ALLOWED_HOSTS = ["*"] ROOT_URLCONF = "project.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", # DIRS lets the apps extend base.html "DIRS": [os.path.join(BASE_DIR, "templates")], "APP_DIRS": True, "OPTIONS": … -
Multiple Apps in play , something similar to multiple apps in django
In Django we can develop multiple apps(own models, view etc) grouped logically with same database and common setting files but different uri. Is there something similar in play. e.g in django we can have two apps books and author with apis like abc.com/v1/book/1, abc/com/v1/author/peter -
Import Statements Inside Functions in Python
I have been trying to solve (in my own way) the problem of making configurations sane and 12-factor compliant for a Django app I am working on. The following was my idea. As you can see, I wanted to fully isolate the specification of environment to, well, environment. Prior to this, I had to re-specify the entry-level settings file inside the manage.py for each new environment, despite already having separate settings files for each environment. settings.py (to which manage.py would point) import environ env = environ.Env() environ.Env.read_env() DJANGO_ENV = env('DJANGO_ENV') def production(): import production def development(): from .development import * def testing(): import testing def staging(): import staging options = {'production': production, 'development': development, 'testing': testing, 'staging': staging} print(options[DJANGO_ENV]()) However, I got complaints (errors) from Python 3.7 that import statements are only allowed at the module level. My question is two-fold: how sane is this approach overall and is there a way to do imports at the function level? -
Is there any advantage on using jwt vs knox on django rest framework
Planning to implement token authentication but I am not sure which one to use -
How to dynamically set value to MoneyField in djmoney?
Currently i am using djmoney to store money info in my database. Right now i need to manually set values in my form, so i use class MyForm(forms.Form): money = MoneyField() ... def view(request): form = MyForm(initial={ 'money' : Money(0.5, 'USD')}) But that's not working, because, as I later found out, MoneyField uses default_amount and default_currency kwargs to set it. But how do i set the form field dynamically? -
Why are my Django model images not being output
Here is my code views.py def search(request): if request.method == 'GET': try: q = request.GET.get('search_box', None) posts = Listing.objects.filter(title__contains=q, is_live=1) | \ Listing.objects.filter(street_address__contains=q, is_live=1) | \ Listing.objects.filter(city__contains=q, is_live=1) | \ Listing.objects.filter(state=q, is_live=1) | \ Listing.objects.filter(property_class__contains=q, is_live=1) | \ Listing.objects.filter(sale_or_lease__contains=q, is_live=1) return render_to_response('search/results.html', {'posts': posts, 'q': q}) except KeyError: return redirect('home') results.html: <div class="container" style="width:20%; float:right; text-align:center; overflow:auto;"> {% for Listing in posts %} <a href="{% url 'post_view' Listing.pk %}"><img style="width: 384px; height: 216px;" alt="Thumbnail" src="{{ MEDIA_URL }}{{ Listing.thumbnail }}"/></a> <p style="color:black;">{{ Listing.title }}</p> <p style="color:black;">Sale or Lease: {{ Listing.sale_or_lease }}</p> <p style="color:black;">Class: {{ Listing.property_class }}</p> <p style="color:black;">Square Feet: {{ Listing.square_feet }}</p> {% if Listing.price %} <p style="color:black;">Price: ${{ Listing.price|linebreaksbr }}</p> {% endif %} {% if Listing.price_per_square_foot_per_year %} <p style="color:black;">Price per SqFt/yr: ${{ Listing.price_per_square_foot_per_year|linebreaksbr }}</p> {% endif %} <p style="color:black;"> City: {{ Listing.city }}, {{ Listing.state }}</p> <hr> {% endfor %} </div> For the above code, Listing.thumbnail is not being output, only the placeholder text is. Here is an example of code I have that is working. views.py def preview(request, pk): posts = Listing.objects.all().filter(is_live=1) preview = get_object_or_404(Listing, pk=pk) attorneys = Attorneys.objects.all().filter(state=preview.state) | \ Attorneys.objects.all().filter(city=preview.city) lenders = Lenders.objects.all().filter(state=preview.state) | \ Lenders.objects.all().filter(city=preview.city) developers = Developers.objects.all().filter(state=preview.state) | \ Developers.objects.all().filter(city=preview.city) context = {'posts': posts, 'preview': … -
AttributeError: module 'socket' has no attribute 'AF_UNIX' when connecting google cloud store with django
I am connecting google cloudstore mysql with django using official documentation on app engine environment, given as: https://cloud.google.com/python/django/appengine Firstly, I got the error that mysqlclient 1.3.13 or newer is required. To resolve this issue, I used the solution given on Django - installing mysqlclient error: mysqlclient 1.3.13 or newer is required; you have 0.9.3, but when I do this it gives me the error "AttributeError: module 'socket' has no attribute 'AFX_UNIT'". -
How can i add more table fields on already developed Django User table Database
I want to add more fields in User Data table so Please Explain the right method to done this. -
Django forms : Edit image field (delete and show existing)
I am trying to have a Django Model form with an image field but I have the two problems: I don't know how to show the current name of the image in the input I don't know how to provide a way to remove the image forms: class CityLogoForm(forms.ModelForm): logo = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'}), required=False) class Meta: model = City fields = ['logo'] views: def management_form_general(request, city_slug): city = City.objects.get(slug=city_slug) if request.method == 'POST': logo_form = CityLogoForm(request.POST, request.FILES, instance=city) if logo_form.is_valid(): logo_form.save() else: logo_form = CityLogoForm(instance=city) return render(request, 'management/form/city_general.html', {'city': city, 'logo_form': logo_form}) html: <form action="" enctype="multipart/form-data" method="post"> <div class="form-group row"> <label for="id_city" class="col-sm-2 col-form-label form_title">{{ logo_form.logo.label }}</label> <div class="custom-file"> {{ logo_form.logo }} <label class="custom-file-label" for="{{ logo_form.logo.id_for_label }}" data-browse="Choisir Image">{{ logo_form.logo.label }}</label> </div> </div> </form> I have a script changing the label when the user is uploading something but I cannot find a way to get the current value for the image fields (for the normal ones it's properly prepopulated). As it seems to not prepopulate the input, it seems to be ignoring when the input is empty and therefore never deletes the current logo. -
Django template inheritance // how to use multiple css files?
I would like to find a solution to have multiple CSS files for different templates using Django template inheritance. So far I could extend my base.html template with another apps template. Now I would like to use a seperate css files for the apps html templates (one app = 1x html, 1x js, 1x css). But when I include the template into the template tag it replaces the css file from the base.html and crashes the site. How can someone implement a second css file into a extended html template that only refers to the extended part and doesn't "touch" the base.html? Thank you for your guidance in advance. extended html template which crashes site because of replacement of base.css file: {% extends 'templates/base.html' %} {% load static %} {% block head_css_site %} <link href="{% static 'Quotes_app.css' %}" rel="stylesheet" type="text/css"> {% endblock head_css_site %} {% block content %} <h1>Test</h1> {% endblock %} {% block footer_javascript_site %} <script src="{% static 'Quotes_app.js' %}"></script> {% endblock footer_javascript_site %} base.html: {# HTML5 declaration #} <!DOCTYPE html> {% load static %} <html> {# Make modifiable head elements #} <head> <title>{% block title %} {% endblock title %} DASHEX </title> {% block head_favicon %} <link rel="icon" …