Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect() doesn't redirect but rather refreshes the same page
view.py @login_required(login_url='index', redirect_field_name=None) def new_character(request): if request.method == 'POST': character_form = CharacterForm(request.POST) if character_form.is_valid(): new_character = character_form.save(commit=False) new_character.creator = request.user new_character.save() # If new_character has a primary key (pk) then it # means it was saved to the database. if new_character.pk: # TODO: For some reason this doesn't work. redirect('list_characters') else: character_form = CharacterForm() return render(request, 'characters/new-character.html', {'character_form': character_form}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.list_characters, name='list_characters'), path('new/', views.new_character, name='new_character'), ] I checked and new_character.pk is coerced to True. However, the redirect doesn't happen and instead the same page is simply refreshed. -
how to change merging two queries to josnResponse - django
i'm trying to merge two queries , i did this models.py class MyDateTimes(models.Model): deadline = models.DateTimeField() class ModelA(models.Model): title = models.CharField(max_length=30) deadline = models.OneToOneField(MyDateTimes,blank=True,null=True) class ModelB(models.Model): post = models.ForeignKey(MyPosts,on_delete=models.PROTECT) deadline = models.OneToOneField(MyDateTimes,blank=True,null=True) class MyPosts(models.Model): article = models.CharField(max_length=30) i've to merge ModelA with ModelB , here is what i did from itertools import chain modelA = ModelA.object.filter(deadline__isnul=False,deadline__deadline__lte=timezone.now()) modelB = ModelB.object.filter(deadline__isnul=False,deadline__deadline__lte=timezone.now()) my_query = list(chain(modelA, modelB)) my_listA = [] my_listB = [] i have to return json response of my_query for i in modelA: item={ 'title':i.title, 'dead_line':i.deadline.deadline, } my_listA.append(item) for i in modelB: item={ 'title':i.post.article, 'dead_line':i.deadline.deadline, } my_listB.append(item) note : because i need to use ForeignKey and OneToOne data thats i couldn't use serialiser function i want to do it into one list to return JsonResponse , in order to callable into ajax call ! thank you in advance , please let me know the most efficient way to achieve that -
How to add custom page for 403 error django
Question as in title. How to set custom page for an error in django. I tried using just in templates new file like '403.html' but it did not work. I tried also this: def handler404(request, exception, template_name="404.html"): response = render_to_response(template_name) response.status_code = 404 return response but I can not import render_to_response -
How to disable "?next=" parameter for Django Admin to avoid Page Enumeration Attacks?
I'd like to disable the ?next=... parameter that Django Admin automatically sets if you try to access a page that's protected by the admin panel. I haven't been able to find a solution to do this so far. Does anyone know how to achieve this? The reason why I want to do this is to avoid page enumeration attacks. -
Django How to refactor duplicate method
I'm using django 2.2 and in my view I have two functions that do the same thing but only one element changes. I would like to try to improve my code so that I don't repeat the same thing more times, basically do what the vm_schedule_power_on_vm function does and vm_schedule_power_off_vm into one function. The only thing that will change is the call of vmware_poweron in the vm_schedule_power_on_vm function and vmware_poweroff in the vm_schedule_power_off_vm function. path('vm/schedule/<int:pk>/powered_on/', vm.vm_schedule_power_on_vm, name='vm_schedule_power_on_vm'), path('vm/schedule/<int:pk>/powered_off/', vm.vm_schedule_power_off_vm, name='vm_schedule_power_off_vm') def vm_schedule_power_on_vm(request, pk): sch = VmSchedule.objects.get(pk=pk) mylistvm, mylist = list(), list() mydate = time.strftime("%d/%m/%Y") for i in sch.vms.all(): if i.lock: return 'locked' # here the order has importance because # I try to have the start time and at the end the end time. mylist.append(mydate) mylist.append(time.strftime("%H:%M:%S")) mylist.append(i.name) mylist.append(i.vmware.hostname) # only this line changes each time mylist.append(vmware_poweron(i)) mylist.append(time.strftime("%H:%M:%S")) mylist.append(sch.schedule) mylistvm.append(mylist) mylist = list() vm_logs_export(mylistvm) return HttpResponse(json.dumps(mylistvm)) def vm_schedule_power_off_vm(request, pk): sch = VmSchedule.objects.get(pk=pk) mylistvm, mylist = list(), list() mydate = time.strftime("%d/%m/%Y") for i in sch.vms.all(): if i.lock: return 'locked' mylist.append(mydate) mylist.append(time.strftime("%H:%M:%S")) mylist.append(i.name) mylist.append(i.vmware.hostname) # only this line changes each time mylist.append(vmware_poweroff(i)) mylist.append(time.strftime("%H:%M:%S")) mylist.append(sch.schedule) mylistvm.append(mylist) mylist = list() vm_logs_export(mylistvm) return HttpResponse(json.dumps(mylistvm)) # Example result of vm_schedule_power_on_vm or vm_schedule_power_off_vm ['09/12/2021', '13:54:33', 'API1VTEST11', 'ste1vvcsa', '13:54:33', … -
WEASYPRINT M1 MAC MINI
I am running weasyprint but system cannot find the package: (env) andrestemmett@Andres-Mac-mini MicrocareERP % weasyprint --info Traceback (most recent call last): File "/Users/andrestemmett/Desktop/MicrocareERP/env/bin/weasyprint", line 5, in from weasyprint.__main__ import main File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/__init__.py", line 322, in from .css import preprocess_stylesheet # noqa isort:skip File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/css/__init__.py", line 27, in from . import computed_values, counters, media_queries File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/css/computed_values.py", line 16, in from ..text.ffi import ffi, pango, units_to_double File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/text/ffi.py", line 380, in gobject = _dlopen( File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/weasyprint/text/ffi.py", line 377, in _dlopen return ffi.dlopen(names[0]) # pragma: no cover File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/cffi/api.py", line 150, in dlopen lib, function_cache = _make_ffi_library(self, name, flags) File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/cffi/api.py", line 832, in _make_ffi_library backendlib = _load_backend_lib(backend, libname, flags) File "/Users/andrestemmett/Desktop/MicrocareERP/env/lib/python3.9/site-packages/cffi/api.py", line 827, in _load_backend_lib raise OSError(msg) OSError: cannot load library 'gobject-2.0-0': dlopen(gobject-2.0-0, 2): image not found. Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0' I have tried to change my symlinks to link to hombrew because i read that weasy print relies on dependencies pango libffi. However when I try that: sudo ln -s /opt/homebrew/opt/glib/lib/libgobject-2.0.0.dylib /usr/local/lib/gobject-2.0 sudo ln -s /opt/homebrew/opt/pango/lib/libpango-1.0.dylib /usr/local/lib/pango-1.0 sudo ln -s /opt/homebrew/opt/harfbuzz/lib/libharfbuzz.dylib /usr/local/lib/harfbuzz sudo ln -s /opt/homebrew/opt/fontconfig/lib/libfontconfig.1.dylib /usr/local/lib/fontconfig-1 sudo ln -s /opt/homebrew/opt/pango/lib/libpangoft2-1.0.dylib /usr/local/lib/pangoft2-1.0 Then i get this error: ln: /usr/local/lib/gobject-2.0: No such file or directory … -
How to get select value in flask?
I'm trying to get the value of select tag but it returns none, how can I get the value of it using flask? I tried request.form.get but still not working, It says the value is none. Here's the HTML of my select tag <select name="channels" id="channels" method="POST"> <option value="1">Channel 1</option> <option value="2">Channel 2</option> <option value="3">Channel 3</option> <option value="4">Channel 4</option> <option value="5">Channel 5</option> <option value="6">Channel 6</option> <option value="7">Channel 7</option> <option value="8">Channel 8</option> </select> Here's my flask code: def updatedecimal(): con = sqlite3.connect('/home/tim-rtc/Randomizer/tmonitor.db') con.row_factory = sqlite3.Row channel = request.form.get('channels') cur = con.cursor() cur.execute("""SELECT * FROM monitors where CHANNEL = ? ORDER BY id DESC limit 1""", (channel, )) rows = cur.fetchall() row1 = [row[1] for row in rows] row2 = [row[2] for row in rows] row3 = [row[3] for row in rows] return jsonify( row1 = row1, row2 = row2, row3 = row3) Newbie in flask here. Thank you! -
Why is a security issue Entry.objects.all ? Django
I'm using Checkmarx tool to scan my code for security issues. For getting all objects from database I used the following code entries = Entry.objects.all() But checkmarx raises an error for this and it consider this code as secord order sql injection. Can someone explain? -
Django import-export, only export one object with related objects
I have a form which enables a user to register on our website. Now I need to export all the data to excel, so I turned towards the import-export package. I have 3 models, Customer, Reference and Contact. The latter two both have a m2m with Customer. I also created Resources for these models. When I use Resource().export() at the end of my done() method in my form view, it exports all existing objects in the database, which is not what I want. I tried googling this and only got one result, which basically says I need to use before_export(), but I can't find anywhere in the docs how it actually works. I tried querying my customer manually like: customer = Customer.objects.filter(pk=customer.id) customer_data = CustomerResource().export(customer) which works fine but then I'm stuck with the related references and contacts: reference_data = ReferenceResource().export(customer.references) gives me an TypeError saying 'ManyRelatedManager' object is not iterable. Which makes sense because export() expects an queryset, but I'm not sure if it's possible getting it that way. Any help very appreciated! -
Angular-Django-MongoDB simple connection failure
I have set up an Angular-Django-MongoDB application, with a real MongoDB database with a cluster called consumers. I am just trying to establish a simple connection between the app and the database. I know my connection string is mongodb+srv://MyUser2021:TestMe@cluster0.j9jz1.mongodb.net/test Just to see if I can get it all to communicate, I have written the following in views.py: @csrf_exempt def consumers(): print("consumers") with its correspondence in urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), # http://localhost:8000/admin/ url(r'^consumers/', consumers), url(r'^.*', TemplateView.as_view(template_name="home.html"), name="home") ] In my Angular app, I have written a simple service script for it: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Post } from '../models/post.model'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable() export class DbService { consumersMongodbApiUrl = "http://localhost:8000/consumers"; constructor(private httpClient: HttpClient) { } addConsumerMongodb(post: Post): Observable<Post> { return this.httpClient.post<Post>(this.consumersMongodbApiUrl, post, httpOptions); } } When I call some function somewhere else that invokes the addConsumerMongodb method in this service class, I get POST http://localhost:8000/consumers 403 (Forbidden) in my webpage dev console. I have looked at lots and lots of posts on this particular error message, but nothing has helped me so far... Could … -
Questions with multiple choices database schema design
Let's say we want to create a quiz application, where a user can create a quiz with the following characteristics: Users can select questions for their quiz from a set of predefined questions. Each question can have multiple options (choices); 2, 3, 5, 6, 9, it doesn't matter. The questions and it's choices are added by the admins (through Django Admin API) I have come up with a fairly simple schema design: This is what's happening in the schema design above: Each Question can have multiple choices The QA maps the question to the answer selected by the user who did/took the quiz Each submitted quiz can have multiple questions together with their answers I am using Django for this particular project. -
DJANGO migrate big database from SQLite3 to PostgreSQL
I have a relatively bid database with around 50 model classes in DJANGO and I would like to migrate it from SQLite3 to PostgreSQL. I set up a dummy local PSQL for testing. I read on multiple other posts to do the following: dump the db Change SQL credentials in setup.py migrate load the db I was able to dump the DB into a json file. After I changed my settings to look like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test_db_name', 'USER': 'test', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '', } } I created the DB by hand, because I was getting errors that it does not exists. After this if I run python3 manage.py migrate I got a bunch of errors, that tables dont exists, so it is not doing what I wanted. End of the long error: django.db.utils.ProgrammingError: relation "gympro_gymclasstype" does not exist LINE 1: ...."type", "gympro_gymclasstype"."description" FROM "gympro_gy... I also saw on other posts that I should reset the migratons, so I tried python3 manage.py --fake appname zero. This also failed, so what I tried is I put the old SQLite3 cretendials back, made the fake reset, I check with showmigrations that the current status … -
ModuleNotFoundError: No module named 'users' from dj-rest-auth
I am trying to run celery on a Django application that has dj-rest-auth already configured but, I get the following error when I run - "celery -A config worker -l info" but, it works perfectly fine without errors when I do "python manage.py runserver". The application has several apps under the folder /apps and within the settings.py, it is imported as "apps.<app_name>". It does have an app called "users" so, it's imported as "apps.users". Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.10/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/usr/local/lib/python3.10/site-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.10/site-packages/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/celery/bin/worker.py", line 343, in worker worker = app.Worker( File "/usr/local/lib/python3.10/site-packages/celery/worker/worker.py", line 94, in __init__ self.app.loader.init_worker() File "/usr/local/lib/python3.10/site-packages/celery/loaders/base.py", line 111, in init_worker self.import_default_modules() File "/usr/local/lib/python3.10/site-packages/celery/loaders/base.py", line 105, in import_default_modules raise response File "/usr/local/lib/python3.10/site-packages/celery/utils/dispatch/signal.py", line 276, … -
"message": "Error: You do not have permission to perform this action. 'Traceback (most recent call last):\\n File \"/opt/dev-application/django-app
I am getting this msg error almost every second on my AWS cloudwatch log "message": "Error: You do not have permission to perform this action. 'Traceback (most recent call last):\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 483, in dispatch\\n self.initial(request, *args, **kwargs)\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 401, in initial\\n self.check_permissions(request)\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 336, in check_permissions\\n request, message=getattr(permission, \\'message\\', None)\\n File \"/opt/dev-application/django-app-20211208092104/.venv/3.7/lib/python3.7/site-packages/rest_framework/views.py\", line 177, in permission_denied\\n raise exceptions.PermissionDenied(detail=message)\\nrest_framework.exceptions.PermissionDenied: You do not have permission to perform this action.\\n'", "customer": { "userId": null, "accountId": null }, "requestId": "65ecb0b6-a114-4dd3-9153-ad43c045a378", "data": {}, "dateCreated": "2021-12-09T11:36:33.998168", "level": "WARNING", "app": { "name": "frontend_api", "threadName": "DummyThread-781" } } ``` -
How to override list function of ModeViewSet to filter multiple value of same parameters in Django?
Currently this how my code looks - class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer def list(self, request): query_dict = QueryDict(request.META['QUERY_STRING']) query_dict = query_dict.dict() self.queryset = MyModel.objects.filter(**query_dict) return super().list(reuqest) Now if I invoke the endpoint with the api like /api/url/?param1=79&param2=34 it works fine. Assuming param1 and param2 are two fields present in MyModel. But if try to do this - /api/url/?param1=79&param2=34&param1=45&param2=576 it returns the result of param1=45 AND param2=576. Which is understandable since I am using dict to parse query params. But I want the results of param1=79&param2=34&param1=45&param2=576 combination. How to achieve that? -
whitenoise.storage.MissingFileError: The JS file 'drf-yasg\redoc\redoc.min.js' references a file which could not be found
I tried collecting static files on an API project I am working with Django/Django REST Framework and I got this error on my console. What could be the cause of the error? raise processed whitenoise.storage.MissingFileError: The file 'drf-yasg/redoc/redoc.standalone.js.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x000002DEED19E050>. The JS file 'drf-yasg\redoc\redoc.min.js' references a file which could not be found: drf-yasg/redoc/redoc.standalone.js.map Please check the URL references in this JS file, particularly any relative paths which might be pointing to the wrong location. enter image description here -
Python/Django ORM: Return result only if there is no more recent date out of range filter
I need to do a query where I have a table in the following format: fk_customer overdue_date Basically I have a query that filters a monthly range of overdue_date. However, I only need to show some date if there isn't a newer date outside of this customer's range. IE. Customer1 - 2021-10-01 Customer1 - 2022-01-02 If I use the range for the month of October, it shouldn't show because there is a more recent date. How can I do this? In raw sql I use IN with a subquery looking for MAX DATE. -
when i run migrate the uuid is field is updating always will it give me some perfomance issue is anyone can explain me the reason and solution
class Customer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True) activate_token = models.CharField(max_length=200,default=str(uuid.uuid4())) forget_password_token = models.CharField(max_length=200,default=str(uuid.uuid4())) first_name = models.CharField(max_length=100,blank=True,null=True) last_name = models.CharField(max_length=100,blank=True,null=True) status = models.CharField(max_length=100,blank=True,null=True) email = models.CharField(max_length=100,blank=True,null=True) gender = models.CharField(max_length=50,blank=True,null=True) city = models.CharField(max_length=100,blank=True,null=True) country = models.CharField(max_length=100,blank=True,null=True) Accounts\migrations\0010_alter_customer_activate_token_and_more.py - Alter field activate_token on customer - Alter field forget_password_token on customer Migrations for 'Store': Store\migrations\0004_product_shipping_charges_alter_product_price.py - Add field shipping_charges to product - Alter field price on product I have a model of customer i am storeing two things there one is user activation token and the other is forgot password token i want it random so i used uuid but when ever i am running migrate this migration always happening by the way i am not facing any functional error everything working fine but i have a feeling it might give me a error -
Running nginx and gunicorn in the same docker file
I have a Dockerfile which at the end runs run.sh. I want to run gunicorn on port 8000 and proxy requests on 80 to 8000 with nginx. The problem is running server is a blocking command and it never executes nginx -g 'daemon off;'. What can I do to handle this situation? Here is the run.sh file: python manage.py migrate --noinput gunicorn --bind=0.0.0.0:8000 bonit.wsgi:application & nginx -g 'daemon off;' And this the Dockerfile: FROM python:3.8 # set work directory WORKDIR /usr/src/app # set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y nginx supervisor build-essential gcc libc-dev libffi-dev default-libmysqlclient-dev libpq-dev RUN apt update && apt install -y python3-pip python3-cffi python3-brotli libpango-1.0-0 libpangoft2-1.0-0 RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY nginx.conf /etc/nginx/nginx.conf RUN python manage.py collectstatic --noinput ENTRYPOINT ["sh", "/usr/src/app/run.sh"] -
Django Elastic Search - How to improve Big Data Indexing speed in ES
I've Epsiode Index where I've only 1 field which I used for searching. I've 53 Millions of records in PostgreSQL. I used django-elasticsearch-dsl lib. for elastic search engine. The problem is When I run the cmd to dump the PostgreSQL episodes table into Episode Index it almost takes 5-6 hours. How can I overcome this problem. Its a bottleneck for me to deploy on prod. documents.py search_analyzer = analyzer('search_analyzer', filter=["lowercase"], tokenizer=tokenizer('autocomplete', 'edge_ngram', min_gram=1, max_gram=15)) @registry.register_document class EpisodeDocument(Document): title = fields.TextField(analyzer=search_analyzer) class Index: name = 'episode' settings = { 'number_of_shards': 4, 'number_of_replicas': 2, 'max_ngram_diff': 10 } class Django: model = Episode queryset_pagination = 5000 cmd for Data dump into ES python manage.py search_index --rebuild ES machine: t3.2xlarge -
LDAP bind failed: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C090A5C,
I am using "django-python3-ldap". I have set up all and while syncing user by command "./manage.py ldap_sync_users" This shows the following binding error LDAP connect succeeded LDAP bind failed: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C090A5C, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v4563 - searchResDone - None Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django_python3_ldap/ldap.py", line 182, in connection yield Connection(c) File "/usr/local/lib/python3.5/dist-packages/django_python3_ldap/management/commands/ldap_sync_users.py", line 24, in handle for user in connection.iter_users(): File "/usr/local/lib/python3.5/dist-packages/django_python3_ldap/ldap.py", line 93, in <genexpr> self._get_or_create_user(entry) File "/usr/local/lib/python3.5/dist-packages/ldap3/extend/standard/PagedSearch.py", line 68, in paged_search_generator None if cookie is True else cookie) File "/usr/local/lib/python3.5/dist-packages/ldap3/core/connection.py", line 853, in search response = self.post_send_search(self.send('searchRequest', request, controls)) File "/usr/local/lib/python3.5/dist-packages/ldap3/strategy/sync.py", line 178, in post_send_search responses, result = self.get_response(message_id) File "/usr/local/lib/python3.5/dist-packages/ldap3/strategy/base.py", line 403, in get_response raise LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'], response_type=result['type']) ldap3.core.exceptions.LDAPOperationsErrorResult: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C090A5C, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v4563 - searchResDone - None here are my settings file ` # The URL of the LDAP server. LDAP_AUTH_URL = "ldaps://example.com:636" # Initiate TLS on connection. LDAP_AUTH_USE_TLS = True # The … -
django query with filtered annotations from related table
Take books and authors models for example with books having one or more authors. Books having cover_type and authors having country as origin. How can I list all the books with hard cover, and authors only if they're from from france? Books.objects.filter(cover_type='hard', authors__origin='france') This query doesnt retrieve books with hard cover but no french author. I want all the books with hard cover, this is predicate #1. And if their authors are from France, I want them annotated, otherwise authors field may be empty or 'None'. Tried many options, annotate, Q, value, subquery, when, case, exists but could come up with a solution. -
Making a custom template for CreateView and UpdateView with placeholders and error validation
I'm making a generic blog while learning Django. I have an ArticleCreateView and ArticleUpdateView, and I am trying to make a custom template that both views would share. From what I understand, CreateView and UpdateView use the same template by default (article_form.html), which is the template I'm trying to modify. I have the following in my models.py: class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() # def __str__ ... # def get_absolute_url ... In my views.py: class ArticleCreateView(CreateView): model = Article fields = ['title', 'body'] template_name = 'article_form.html' class ArticleCreateView(CreateView): model = Article fields = ['title', 'body'] template_name = 'article_form.html' Having the following in my template article_form.html works: <form method='post'> {{ form.as_p }} <button> Publish </button> </form> I want to make it more fancy though, with loads of CSS, and a simplified version is: <form method='post'> {% csrf_token %} <fieldset class="fieldset-class"> {{ form.title.errors }} <input class="form-class" type="text" placeholder="Article Title" name="{{ form.title.name }}" value="{{ form.title.value }}" /> </fieldset> <fieldset class="form-group"> {{ form.body.errors }} <textarea class="form-control" rows="8" placeholder="Article Body" name="{{ form.body.name }}" >{{ form.body.value }}</textarea> </fieldset> </form> What I want is a form that: has placeholders in empty fields (instead of labels) has model-based error validation (max_length is respected and both fields … -
Django Validation is working on django admin but not working on html template
I'm creating a form where if we register it should save data to the database if the form is valid. otherwise, it should raise an error but it doesn't save data to the database, and also some fields are required but if I submit the form it doesn't even raise the error field is required. but if I register it manually on Django admin pannel it works perfectly fine. here is my model: class foodlancer(models.Model): Your_Name = models.CharField(max_length=50) Kitchen_Name = models.CharField(max_length=50) Email_Address = models.EmailField(max_length=50) Street_Address = models.CharField(max_length=50) City = models.CharField(max_length=5) phone = PhoneNumberField(null=False, blank=False, unique=True) def __str__(self): return f'{self.Your_Name}' also, I disabled html5 validation forms.py class FoodlancerRegistration(forms.ModelForm): phone = forms.CharField(widget=PhoneNumberPrefixWidget(initial="US")) class Meta: model = foodlancer fields = "__all__" views.py: def apply_foodlancer(request): form = FoodlancerRegistration() return render(request, 'appy_foodlancer.html', {"form": form}) and finally Django template <form method="POST" novalidate> {% csrf_token %} {{ form.as_p }} <button type="submit" class="cta-btn cta-btn-primary">Submit</button> </form> Thank you for your time/help -
how to change where summernote looks for images
Everything works for me on summernote but when i add image in the text it dosent show up in frontend i know the reason is that it looks for image on localhost:3000/media/django-summernote/2021-12-06/default.png but istead of 3000 it should be going to localhost:8000 urls.py from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('summernote/', include('django_summernote.urls')), path('api/', include('api.urls')), path('admin/', admin.site.urls), ] + static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns +=[re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]