Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can someone explain me this line? I got this from Telesko Django playlist video number 20
This urls.py of base project urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) This is the settings.py STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT=os.path.join(BASE_DIR,'assets') MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') This code is to add items to the database dynamically and i am not able to understand why is he adding the urlpatterns. -
improperly configured app in settings.py of django
Tying to register my djano app in the settings section of my django project. but when i run the server i am getting an error in the terminal. django.core.exceptions.ImproperlyConfigured: 'site1app.apps' does not contain a class 'Site1appConfig'. Choices are: 'Site1AppConfig'. I dont know what's going wrong as i just added it to the list of installed apps in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'site1app.apps.Site1appConfig', ] -
Django - Multi Tenancy vs Sites Framework, When to use each?
I'm designing an API that handles multiple domains by country (e.g peru.website.com, chile.website.com, etc.). I read about two aproaches: using django sites framework or django multi tenancy, but I am not sure about the advantages of each one. When should I use one over the other? -
Django Static Files - No error but still doesnt load or change css
It seems like this is an incredibly common issue and I've read the docs and tried all solutions and multiple youtube videos, but can't find a solution. When I run the development server, my static files don't load but my terminal doesn't raise any errors either. File layout: File Structure SETTINGS.PY STATIC_URL = '/staticfiles/' MEDIA_URL = '/images/' STATICFILES = [ os.path.join(BASE_DIR, 'staticfiles'), ] TERMINAL OUTPUT: July 15, 2020 - 21:02:47 Django version 3.0.8, using settings 'mywebsite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [15/Jul/2020 21:02:51] "GET / HTTP/1.1" 200 148 [15/Jul/2020 21:02:51] "GET /staticfiles/css/main.css HTTP/1.1" 404 1672 [15/Jul/2020 21:02:51] "GET /staticfiles/images/headshot.JPG HTTP/1.1" 404 1693 -
Get All Users in django
I want to display all the users, in my template but I i received this error. TypeError at /list/ init() takes 1 positional argument but 2 were given views.py class UsersView(TemplateView): template_name = 'list.html' context = super(UsersView, self).get_context_data(**kwargs) context['object_list'] = User.objects.values() list.html <tbody> <tr> <th scope="col">Id</th> <th scope="col">username</th> <th scope="col">email Adress</th> <th scope="col">First Name </th> <th scope="col">Last Name</th> </tr> </thead> <tbody> {% for user in users %} <tr> <td>{{ user.id }} </td> <td>{{ user.username}}</td> <td>{{ user.email }}</td> <td>{{ user.first_name}}</td> <td>{{ user.last_name }}</td> How could you pull all users? -
how to group index db in django
I have a problem when I create an index in models file, I need grouping index like this (dt_cot, dt_cri) and another group index (id_inv) in a table, my code is below: class ModelTable(models.Model): name = models.CharField(max_length=30) class Meta: indexes01 = [models.Index(fields=['dt_cot', 'dt_cri'])] indexes02 = [models.Index(fields=['id_inv'])] the problem is when I do 'makemigrations', the error display: "TypeError: 'class Meta' got invalid attribute(s): indexes01, indexes02". please how to grouping indexes. regards. -
Django form is not valid. Problem with ChoiceField and first list of tuples (PK)
I generate a list to prepopulate a ChoiceField in my Form. This list consists of 2x tuples. The first tuple is primary key, the second tuple is text. views.py from django.http import HttpResponse, HttpRequest, HttpResponseRedirect from .models import * def n01_size_kss(request): if request.method == 'POST': form = KSS_Form(request.POST) context = {'form':form} if form.is_valid(): filtertype, context = n01_context_cleaned_data(form.cleaned_data) if filtertype != "none": geh_innen_choice = prepare_dictionary_form2(context) form1.fields['geh_innen'].choices = geh_innen_choice context = {'form':form1, **context} return render(request, 'af/size/01_kss_size2.html', context) else: context = {'form':KSS_Form()} return render(request, 'af/size/01_kss_size1.html', context) def prepare_dict_form_n01_01(context): baureihe_record1 = context['baureihe_record1'] filter_label = baureihe_record1.series.valuefg x_choice = afc_select_housing_innenteile.objects.filter(Q(series__valuefg__exact=filter_label)).order_by('price') geh_innen_choice = [] for i in x_choice: x = "Housing: " + i.mat_housing.descr x1 = (i.id, x) geh_innen_choice.append(x1) return geh_innen_choice forms.py from django import forms from django.conf.urls.i18n import i18n_patterns class KSS_Form1(forms.Form): geh_innen = forms.ChoiceField(\ required=True, \ label=_("Specify material of the housing:"), \ disabled=False, \ ) As a result I get form.is_valid=FALSE and the following error message by printing form.errors: Select a valid choice. 119 is not one of the available choices 119 - is the record number (primary key) If I will generate the first list of tuples as 1, 2, 3..., how can I trace then, which menu item was chosen? What is the correct … -
Django admin ignores dynamically generated form fields
I'm trying to have the django admin display a model form with dynamically generated fields. I setup my form like this: class EulogyTextForm(f.ModelForm): class Meta: model = EulogyText fields = '__all__' def __init__(self, *args, **kwargs): super(EulogyTextForm, self).__init__(*args, **kwargs) for i in range(len(settings.MULTITEXT_LANGUAGES)): field_name = 'language%s' % (i, ) self.base_fields[field_name] = f.CharField(disabled=True, initial=settings.MULTITEXT_CHOICES[i][0]) field_name += '_text' self.base_fields[field_name] = f.CharField() I have setup my admin like this: class EulogyTextAdmin(admin.ModelAdmin): model = EulogyText exclude = [] form = EulogyTextForm However, Django admin will not display my added fields. I have created a TestView to display the form. In the test view, the form is correctly displayed with the added fields. Why does Djang admin ignore the additional fields? -
Deploy Heroku: when manage.py and settings.py file is in outside of app folder
I have folder map looks like this: `` C:\Users\OS\oTree - oTree | |-- nar2020 (this is the name of my app) | | | |-- templates. | | | |-- _init_.py | | | |-- models.py | | | |-- pages.py | | | |-- Procfile | | | |-- requirements.txt | | | |-- runtime.txt | |-- init_.py | |-- manage.py | |-- settings.py | |-- requirements_base.txt (This is the standard format of Otree, if I move manage.py or settings.py into <nar2020> folder. the app cannot run in local host. And if I move Procfile, requirements.txt or runtime.txt to the outer folder (otree). I cannot push it in Heroku.So I cannot change the directoy of these files although I know that manage.py should be in the same folder with Procfile. My manage.py file import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from otree.management.cli import execute_from_command_line execute_from_command_line(sys.argv, script_file=__file__) django.setup() My Procfile web: gunicorn oTree.manage:app --log-file – My settings.py from os import environ SESSION_CONFIG_DEFAULTS = { 'real_world_currency_per_point': 1.00, 'participation_fee': 0.00, 'doc': "", } SESSION_CONFIGS = [ { 'name': 'nar2020', 'display_name': "nar2020", 'num_demo_participants': 1, 'app_sequence': ['nar2020'], } ] LANGUAGE_CODE = 'en' REAL_WORLD_CURRENCY_CODE = 'EUR' USE_POINTS = False ROOMS = [ … -
Heroku 404 error for Django implementation
I have developed a website using Django and it worked well on my local sever. However when I deployed it on Heroku, only the index.html is rendered. When I visit the other links it gives me this error https://recptool.herokuapp.com/login/ Page not found (404) Request Method: GET Request URL: https://recptool.herokuapp.com/login/ Using the URLconf defined in prcl_tool.urls, Django tried these URL patterns, in this order: admin/ [name='index'] favicon.ico signup [name='signup'] login [name='login'] logout [name='logout'] upload [name='upload'] tag/<int:group> [name='tag'] classify/<int:group> [name='classify'] The current path, login/, didn't match any of these. urls.py has the following: urlpatterns = [ path('admin/', admin.site.urls), path('', include('reviewtool.urls')), ] and settings.py has the following: ALLOWED_HOSTS = ['recptool.herokuapp.com'] INSTALLED_APPS = [ 'reviewtool.apps.ReviewtoolConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'prcl_tool.urls' Can provide additional information to debug this issue -
Reverse for 'detail_account' with arguments '('',)' not found. 1 pattern(s) tried: ['account/account/(?P<slug>[^/]+)$']
I'm making a Django application and been trying to add a detail_profile_view, i want a button underneath the posts (its a blog app) to direct you to a users account, the following isn't the entirety of my code its only what i think is relevant in the error, if you need more i can always update this post. i keep getting the following error: Internal Server Error: / Traceback (most recent call last): File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dylan\myblogsite\blog\views.py", line 34, in home_view return render(request, 'home.html', context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) … -
Instagram like infinite scroll image gallery
I'm looking for a very simple method to gradually load images as the user scrolls. I don't need and buttons I just want it to load like when you scroll through instagram or facebook. I've tried making some examples I've seen work without success. They all seem to be class-based views or not what I'm looking for. Here's my code: views.py def image_view(request): context = { "images": Image.objects.all(), } return render(request=request, template_name="products/images.html", context=context) images.html <div class="col-12"> <div class="card"> <div class="card-header card-header-success"> All Images </div> <div class="card-body"> <table class="table-striped"> <thead> <th>Image</th> <th>Filename</th> <th>Upload Date</th> </thead> <tbody> {% for image in images %} <tr> <td><img src="{{image.image.url}}" class='model-image-preview' alt=""></td> <td>{{image.image.url}}</td> <td>{{image.timestamp}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> -
Find properties from database within 5 kms
I have latitude and longitude which will be considered as centre and I want to find out properties in my database which are within 5kms from given latitude and longitude in Python. Please help me out as I'm a newbie! Thanks in advance! -
Django - Multi Tenancy vs Sites Framework
I'm using django and django rest framework to create a website. One of the requirements is that the website must be multi domain, by country (e.g. peru.website.com, chile.website.com, etc). I read about 2 ways to achieve this goal: The site framework: A model that stores the domain names that relates to other models via foreign keys. Django multi tenancy package: Separate domains by DB schemas. What would I need? I think would I need the site framework because certain models must be common across sites, like the user model. There should be only one superuser and the user's email must be unique for all domains. But I'm not sure whether I can do more than that with the site framework or it is its only advantage. So, the question is: what would be the advantages of using one instead the other? I would really appreciate if anyone could tell me a detailed comparison between both aproaches. Thank you in advance. -
POST fails without executing even a single line
I'm trying to POST from a website with different origin. I use JavaScript to call the API. A minimal example of what I've done is shown: JavaScript: options = {method: 'POST', // mode: 'no-cors', headers: { 'Content-Type': 'application/json' }, body: formData } fetch(url, options).then(response => { console.log(response) }).catch(err => { console.error(err) }); } Django Rest Framework based class: class ImageUpload(APIView): def post(self, request, format=None): print("data:", request.data) print("file:", request.FILES) response = Response(status=status.HTTP_201_CREATED) response['Access-Control-Allow-Origin'] = "*" response["Access-Control-Allow-Headers"] = "*" print(response) return response def options(self, request, *args, **kwargs): response = Response() response['Access-Control-Allow-Origin'] = "*" response["Access-Control-Allow-Headers"] = "*" print(response) return response With this example, I get CORS error that Cross-Origin Request is Blocked. This is due to the missing header. Interestingly, upon calling the API, my django console doesn't print a single line which it was supposed to upon calling the POST request. How did DRF send a response without going into def post? Before calling POST, OPTIONS is called which behaves perfectly as it should have. I even got the response printed on console. Also, another observation is, the API works perfectly fine when i uncomment mode: 'no-cors'. Upon researching, I found that I can use django-cors-headers, but opening up CORS to all … -
how to make ajax work? what need to be installed on my pc(Linux)
forgive me, this is probably very easy question, and its stupid of me to even ask, but I am losing my mind over it so please help me, what do I need to run ajax, I copy code from w3school save it on html,it doesnt work, I did have jquery cdn in my html header so why is not working, data.txt its same folder as html file <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("data.txt"); }); }); </script> </head> <body> <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div> <button>Get External Content</button> </body> </html> PS: I am learning django, I was watching youtube tutorial, I follow as the video goes, I copy paste the code, it didn't work, so I am now watching ajax tutorial and most basic command that I follow the video, or the one I copied from w3school nothing is working,I know JavaScript and dom objects, and yes javascipt and dom object work, but Jquery and ajax is not working at all -
How come page isn’t accessible?
**So what I’m trying to do is** make my contact page accessible when clicked on but I keep on getting an error I don’t know why if everything seems in place also everything seems to imported properly as well. import React from ‘react’; import logo from ‘./logo.svg’; import ‘./App.css’; import Header from ‘./components/header’; import Footer from './components/footer'; import Home from './components/home'; import About from './components/about'; import Car from './components/car'; import Contact from './components/contact'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; import './image-gallery.css'; function App() { return ( <Router> <Switch> <Route exact path="/"> {create_page(<Home />)} </Route> <Route path="/home"> {create_page(<Home />)} </Route> <Route path="/about"> {create_page(<About />)} </Route> <Route path="/home"> {create_page(<Home />)} </Route> <Route path="/car"> {create_page(<Car />)} <Route path="/home"> {create_page(<Home />)} </Route> <Route path="/contact"> {create_page(<Contact />)} </Route> </Switch> </Router> Here is the error that shows up don’t know why if everything seems to be properly put in place and everything imported correctly > ./src/App.js Line 43:8: Parsing error: Expected corresponding JSX > closing tag for <Route> > > 41 | {create_page(<Contact />)} 42 | > </Route> > > 43 | </Switch> > | ^ 44 | </Router> -
Django: the best way make queries optimize
i have a problem with queries in webpages the index page show 5 row with 5 differents categories my table look like this models.py class Post(models.Models): .... categories = M2M(Category, ...) author = FK(author, ...) status = CharField(Choices=STATUS) views.py here I put the way I extract the data to send them to the template queryset_global = Post.objects.filter(status__contains='publish').prefetch_related('categories').select_related('author') According to me, I cached the query, to later filter my categories and not hit the database news_cat1 = queryset_global.filter(categories__slug__contains="cat1_name").order_by('-date')[:5] news_cat2 = queryset_global.filter(categories__slug__contains="cat2_name").order_by('-date')[:5] news_cat3 = queryset_global.filter(categories__slug__contains="cat3_name").order_by('-date')[:5] news_cat4 = queryset_global.filter(categories__slug__contains="cat4_name").order_by('-date')[:5] news_cat5 = queryset_global.filter(categories__slug__contains="cat5_name").order_by('-date')[:5] i retrieve 25 post for show in index page according debug toolbar this produce SQL 2599.59 ms (44 queries including 34 duplicates ) but when I go loop them in the template this increases considerably index.html 5 time loop in template {% for news1 in news_cat1 %} {{news.title}} {{newa.date|date:'Y-m-d'}} {{news.body|safe|truncatewords:20}} {{news.category.all.0}} <a href="{{news.get_absolute_url}}">Read More</a> {% endfor %} ... {% for news5 in news_cat5 %} .... {% endfor %} according debug toolbar this produce SQL 3463.65 ms (86 queries including 77 duplicates ) why debug toolbar say N duplicates and show more queries, and if i show more category it increases more queries. How can I improve or optimize these queries, they … -
How to prevent javascript element from rendering over collapsible Navbar Menu
I'm trying to add a Full-Calendar to my website but the calendar div keeps rendering over the expanded Navbar. Is there a way to make the navbar stay on top of the full-calendar ? On top meaning that the menu once expanded hides the calendar. For information I'm using bootstrap 4 for the styling and django as framework. This is my body section from my base template: <body> <!-- Header --> <header id="header"> <!--Loading Navbar--> {% include 'navbar.html' %} <div id="branding"> {% block branding %}{% endblock %} </div> </header> <!-- END Header --> <!-- Container --> <div id="container"> <!-- Content --> <div id="content" class="{% block content_container_class %}colM{% endblock %}"> {% block pretitle %}{% endblock %} {% block content %}{% endblock %} </div> <!-- END Content --> </div> <!-- END Container --> {% include 'footer.html' %} <!-- Load Javascript--> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> {% block script %}{% endblock %} <!-- End Javascript--> </body> My navbar : {% load static %} <nav class="navbar navbar-expand-md bg-light navbar-light shadow-sm"> <div class="navbar-header justify-content-between d-flex flex-row"> <!-- Toggler/collapsibe Button --> <button class="navbar-toggler border-0" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <img src="{% static 'img/navbar-menu.svg' %}" alt="menu" class="nav-menu"> </button> <!-- Brand --> <a … -
'QuerySet' object is not callable while updating pandas to database table in django
I have a .csv file in a database table. Pandas open this .csv file and crunches some numbers in it. I am then trying to update a different database table with these crunched number values, but am running into a'QuerySet' object is not callable error in the terminal. I can't see what i am doing wrong here. The pandas column is counting how many "OK" values and "Fail" values there are in the status column. i then assign these output values as whatsgood and whatsbad. Then i try to update my pass_number and fail_number that lie in a database table called PF. if UploadedFile.objects.filter(the_file='test.csv').exists(): df = pd.read_csv(UploadedFile.objects.get(the_file='test.csv').the_file, parse_dates=True) totals = df["status"].value_counts() whatsgood = float(totals.OK) whatsbad = float(totals.Fail) crunched_numbers_for_upload = PF.objects.all() crunched_numbers_for_upload(pass_number = whatsgood, fail_number = whatsbad) -
Heroku H10 Error and Syntax Error when running app
Hey so my friend and I are trying to host a website for a hackathon. The website was made with django and we are trying to host on heroku. I managed to get it working for the most part, but when I try to open the website it wont work. When I check my logs it gives me some h10 error and some syntax error? I'm pretty confused: PROCFILE: web: waitress-serve --listen=*:$PORT Melanoma.wsgi:application WSGI.py """ WSGI config for Melanoma project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Melanoma.settings') application = get_wsgi_application() HEROKU LOGS: 2020-07-15T19:59:54.064271+00:00 heroku[web.1]: State changed from crashed to starting 2020-07-15T20:00:14.548453+00:00 heroku[web.1]: Starting process with command `waitress-serve --listen=*:50383 Melanoma.wsgi:application` 2020-07-15T20:00:16.032919+00:00 app[web.1]: Traceback (most recent call last): 2020-07-15T20:00:16.032946+00:00 app[web.1]: File "/app/.heroku/python/bin/waitress-serve", line 8, in <module> 2020-07-15T20:00:16.033071+00:00 app[web.1]: sys.exit(run()) 2020-07-15T20:00:16.033071+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/runner.py", line 270, in run 2020-07-15T20:00:16.033278+00:00 app[web.1]: app = resolve(module, obj_name) 2020-07-15T20:00:16.033279+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/waitress/runner.py", line 211, in resolve 2020-07-15T20:00:16.033450+00:00 app[web.1]: obj = __import__(module_name, fromlist=segments[:1]) 2020-07-15T20:00:16.033454+00:00 app[web.1]: File "/app/Melanoma/wsgi.py", line 1 2020-07-15T20:00:16.033471+00:00 app[web.1]: version https://git-lfs.github.com/spec/v1 2020-07-15T20:00:16.033487+00:00 app[web.1]: ^ 2020-07-15T20:00:16.033515+00:00 app[web.1]: SyntaxError: invalid syntax 2020-07-15T20:00:16.072701+00:00 heroku[web.1]: Process exited with status … -
Filter Objects by Choice Django
I have a model Book that has a choice field in it with the following choices: NVL - Novel SHT - Short story AB - Autobiography I have a list of all my books in HTML and want to be able to search by the choices above. For example, if I type in "N" then Novels would come up. If I type in "O", then all Novels, Short stories, and autobiographies would come up since they all have "O" in them. How can I achieve this? I thought of icontains with Q filters, but couldn't get it to work ;(. -
How can i update with modelformset_factory on Django
I used the modelformset_factory method for multiple photo uploads. But when I want to update the post, I don't know how to do this, I tried something, but this only serves to re-upload photos and upload the uploaded photos again. How can I update or delete a previously uploaded photo? Also, I cannot access the photos in formset as {{formset.image}}. How can I access this? Views.py def post_update(request, slug): post = get_object_or_404(Post, slug=slug) if not request.user.is_authenticated and not request.user == post.seller or not request.user.is_admin: raise Http404 ImageFormSet = modelformset_factory(PostImage, form=PostImageForm, extra=5, can_delete = True) form = PostForm(data=request.POST or None, instance = post, files = request.FILES or None) formset = ImageFormSet(data=request.POST or None, files= request.FILES or None, queryset=PostImage.objects.filter(post__slug=slug)) if form.is_valid(): if formset.is_valid(): for forms in formset.cleaned_data: if forms: image = forms['image'] print(forms['image']) photo = PostImage(post=post, image=image) photo.save() form.save(commit=True) messages.success(request,"Success") return HttpResponseRedirect(reverse('gayrimenkul:detail',kwargs={'slug':form.instance.slug})) return render(request,'post_update.html',{'form':form,'formset':formset,'slug':slug}) post_update.html {% extends "main_page.html" %} {% load static %} {% block icerik %} {% load crispy_forms_tags %} <div class="row"> <div class="container"> <h2 class="page_header">İlan Ver</h2> <hr> {% if form.errors %} {{form.errors}} {% endif %} <div class="col-md-12"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form.media}} {{form|crispy}} <div class="row"> <div class="col-md-6"> {{formset}} </div> <div class="col-md-6"> <button type="submit" id="inp" class="btn btn-outline-primary" style="float:right;">Kaydet</button> </div> … -
forms.CharField(initial = "")
My task to make pre-populated content of the page, like this: content content = "Sample text" content = forms.CharField(widget=forms.Textarea, initial = content) I need something like above, can you help me with realising that in code class EditPageForm(forms.Form): content = forms.CharField(widget=forms.Textarea) def editPage(request, title): content = util.get_entry(title) if request.method == "POST": form = EditPageForm(request.POST) if form.is_valid(): new_content = form.cleaned_data["content"] util.save_entry(title, new_content) return HttpResponseRedirect(reverse("encyclopedia:entry", kwargs={'title': title})) EditPageForm.initial = content return render(request, "encyclopedia/editpage.html", { "form": NewSearchForm, "editPageForm": EditPageForm, "title": title }) Html code: <form action="{% url 'encyclopedia:editpage' title=title%}" method="post"> <div> <h3>Content:</h3> {% csrf_token %} {{ editPageForm }} </div> <input type="Submit"> </form> -
Python Django Form submit button not working as desired
I have been trying to learn Django. I am stuck on this form part. A form has been created that allows the user to create an Album object where they can fill in the Artist, Album Name, Genre and upload an Album Logo. When I fill in the fields and then click submit, it should then redirect me to the details page for that particular Album that just got created. But nothing appears to happen when clicking the submit button and the object does not get created. Here is the models.py code that contains an Album class with 4 fields; artist, album_name, genre and album_logo. from django.db import models from django.urls import reverse # Create your models here. class Album(models.Model): artist = models.CharField(max_length=250) album_name = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.ImageField() def get_absolute_url(self): return reverse('music:detail', kwargs={'pk':self.pk}) def __str__(self): return self.album_name + " - " + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=100) song_title = models.CharField(max_length=250) is_favourite = models.BooleanField(default=False) def __str__(self): return self.song_title Here is the album_form.html code which contains the actual form. I have not used crispy_forms as I am not familiar with Bootstrap though I know CSS. {% extends 'music/base.html' %} {% block title %}Add …