Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why whene I run makemessages the locale repertoir still empty
I have some problems using the command django-admin makemessages -l es I'm running it but the locale repertory still empty and and there is not .po files generated on my locale repertory . I add this following code on my setting.py file: LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale') ] And: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have gettext installed and I have created a repertory named locale on root of the project, I don't realy get the problem -
One Django app in a separate python package
Django==3.2.5 Please, have a look at the picture: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'clients', 'general', 'images', 'themes', 'omnibus', 'staticassets', 'categories', 'tags', 'articles', ] When I run this, I get: ModuleNotFoundError: No module named 'articles' It is predictable as Django doesn't know where to find the app. Then I tried like this: INSTALLED_APPS = [ 'dependencies.articles', ] No success. Here 'articles' is just an ordinary Django app like categouries or clients. But I'd like to move it to 'depencencies' package. Why? I'd like to organize the code structure like this for as personal preferences. If it is technically possible, please, help me cope with this problem. -
Using One Model inside another model in Django
I am Developing a E-commerce Application with Django So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField. So Here is the code for this This is the model for getting the Categories from the user class ProjektCat(models.Model): id = models.AutoField(primary_key=True) Option_Name = models.CharField(max_length=50) Option_Number = models.IntegerField() Number_Visits = models.IntegerField(default=0) def __str__(self): return f'{self.Option_Name}' and here is the code to list those categories as a dropdown in the CharField class Software_And_Service(models.Model): id = models.AutoField(primary_key=True) Product_Name = models.CharField(max_length=100, default='') projectKats = ProjektCat.objects.all() choice = [] for i in projectKats: option = (i.Option_Number, i.Option_Name) choice.append(option) Cateogary = models.CharField( max_length=256, choices=choice) Price = models.IntegerField(default=0) Description = models.TextField(default='', max_length=5000) pub_date = models.DateField(auto_now_add=True, blank=True, null=True) image = models.URLField(default='') linkToDownload = models.URLField(default='') def __str__(self): return f'Projekt : {self.Product_Name}' But it's Showing me an Error that there is no such table in app_name.projektcat Is there is any solution for this?? -
Django Rest Framework CSRF protection not working
I am developing an Angular application with Django Rest Framework and I want to configure CSRF protection. However, I can not seem to trigger CSRF violations when doing any POST request to the backend (for testing purposes). I currently do not use CSRF protection. My settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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' ] I configured my CORS headers such that: CORS_ALLOW_ALL_ORIGINS = True I do not use CSRF_TRUSTED_ORIGINS anywhere. Why is the CSRF protection not invoked? -
NoReverseMatch at /vistaprevia/pedidos/4/edit Reverse for 'editr' not found. 'editr' is not a valid view function or pattern name
I have a problem with an edit view in django 3.2 and python 3.9.2, the problem is when a get into the link EDITAR in my view, it throws me the error "NoReverseMatch at /vistaprevia/pedidos/4/edit" and says to me that "Reverse for 'editr' not found. 'editr' is not a valid view function or pattern name.", I cant found what is going on with the code. Here is my code Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views import generic from django.views.generic.edit import UpdateView from vistaprevia.models import Op from vistaprevia.forms import CargarFormOp, EditarFormOp#, EditarFormRem # Create your views here. from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext, loader app_name = 'vistaprevia' #VISTA QUE MUESTRA LOS ULTIMOS 10 PEDIDOS def index(request): ultimasop = Op.objects.all().order_by('-fecha') return render(request, 'vistaprevia/index.html', context={'ultimasop':ultimasop}) #DETALLE PEDIDOS class PedidoDetailView(generic.DetailView): model = Op #CARGA DE PEDIDOS, EMPIEZ LA ACCION, WIIIIIIIIII def cargar_pedido(request): if request.method=='POST': form = CargarFormOp(request.POST) if form.is_valid(): fecha = form.cleaned_data['fecha'] cliente = form.cleaned_data['cliente'] tipoop = form.cleaned_data['tipoop'] fact = form.cleaned_data['fact'] condicion = form.cleaned_data['condicion'] despacho = form.cleaned_data['despacho'] vendedor = form.cleaned_data['vendedor'] newdoc = Op(fecha=fecha, cliente=cliente, tipoop=tipoop,fact=fact, condicion=condicion, despacho=despacho ,vendedor=vendedor) newdoc.save() return redirect("index") else: form = CargarFormOp() return render(request, 'vistaprevia/formulario.html', {'form': form}) #AGREGAMOS TODO LO REFERETE AL … -
How to fix Django admin page error related to `__str___`
Had a None type error on the admin page because of an empty field (null=True) in the db table. Followed of of the answers here with return self.author or '' + self.post_title[:40] and fixed the error. Now how do I get both the author and title of post appear in the admin page. The previous (broken) code: return self.author + ', ' + self.post_title[:40], but once I add or '', the part following + stops working. -
OneToMany relationship between abstract modules Django
So I have an app, i've created only one module which is the customer module, and there are three other tables on that app that are created by django itself. The names of the tables are auth_user, auth_user_group, auth_group. Now I need to establish a one-to-many relationship between the first two, the thing is I'm not quite sure how to do that because there are no modules. Any ideas? -
ProgrammingError: SELECT COUNT(*) AS "__count" FROM "product"
I am using multiple databases in Django and connected default SQLite and PostgreSQL db in the settings.py. setting.py : DATABASE_ROUTERS = ['routers.db_routers.AppRouter'] DATABASE_APPS_MAPPING = {'product': 'postgres',} DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'postgres': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'product', 'USER': 'postgres', 'PASSWORD':'password', 'HOST':'localhost' } } And also made the db_routers.py in the routers folder: class AppRouter: """ A router to control all database operations on models in the product application. """ def db_for_read(self, model, **hints): """ Attempts to read user models go to postgres. """ if model._meta.app_label == 'product': return 'postgres' return 'default' def db_for_write(self, model, **hints): """ Attempts to write user models go to postgres. """ if model._meta.app_label == 'product': return 'postgres' return 'default' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the user app is involved. """ if obj1._meta.app_label == 'product' or \ obj2._meta.app_label == 'product': return True elif 'product' not in [obj1._meta.app_label, obj2._meta.app_label]: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'product_db' database. """ if app_label == 'product': return db == 'postgres' return None here, it's model.py: class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) … -
how to reactjs axios send request to django database (case: the database has foreignKey)
I am learning reactjs and django by making a blog but I have a question: how to post a request to server when the database has ForeignKey field ? Example: I am making the comment section Can someone help me to solve this ? Thanks for helping ! this is my code ! models.py class Article(models.Model): title = models.CharField(max_length = 116) content = models.TextField() user_token = models.TextField(null = True) def __str__(self): return self.title class Comment(models.Model): article = models.ForeignKey(Article, on_delete = models.CASCADE) user = models.CharField(max_length = 116, null = True) comment = models.TextField() def __str__(self): return self.comment -
Unable to implement websocket with Nginix and Daphne
I am trying to setup websockets on my django application using Daphne and Ngnix. On my local setup everything works as expected but when I have uploaded to the server the websockets do not respond. This is Nginx.conf file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; client_max_body_size 10M; } and this is my sites-available file which is accessed by Nginx: server { server_name 139.59.9.118 newadmin.aysle.tech; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/AysleServer/src; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /wss/ { proxy_pass … -
Is there a way to change the blank attribute on Django form fields to False by clicking a button?
I am building a review form that will post to a single model in my database. This form will have multiple sections, each with its own set of questions. I want the user to be able to complete a section and hit a submit button that will save the progress and redirect them to the next section. In essence I want to create an in progress status for the review with the idea that as all sections are finished the user can hit a complete button that will run my validation on the entire form. However, I do not want to allow posting information to the database that has not been cleaned. I've been thinking through this trying to work out what I need to do and believe the best bet would be to have a complete button on the last page that changes blank to False for the fields of the form. I believe this would allow me to fill out each form and post it to the database as all fields would start as optional but then for that specific model instance the click of the button at the end would institute a change making all fields required, … -
Django heroku server error after deployment
I have deployed my django app to heroku. All seems to be working fine locally but not when deployed with heroku. I keep getting a Server error 500 anytime i visit the site. Here is my views.py file def home_view(request): email = send_mail("Account confirmation mail", f"Click on the link to activate your account", settings.EMAIL_HOST_USER, ["******@gmail.com"]) return render(request, "email.html", context={}) here is what comes up in my heroku logs 2021-07-16T04:32:23.908455+00:00 heroku[web.1]: State changed from starting to up 2021-07-16T04:32:28.000000+00:00 app[api]: Build succeeded 2021-07-16T04:33:04.554487+00:00 heroku[router]: at=info method=GET path="/" host=polar-temple-25791.herokuapp.com request_id=c958793a-15d9-46f7-8594-30b075db4413 fwd="102.89.1.147" dyno=web.1 connect=0ms service=794ms status=500 bytes=403 protocol=https 2021-07-16T04:33:04.554965+00:00 app[web.1]: 10.93.205.135 - - [16/Jul/2021:04:33:04 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-16T04:33:05.957497+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=polar-temple-25791.herokuapp.com request_id=c0ea8a4f-2e94-4e1d-92e1-99eaca82bd82 fwd="102.89.1.147" dyno=web.1 connect=1ms service=103ms status=404 bytes=411 protocol=https 2021-07-16T04:33:05.957866+00:00 app[web.1]: 10.93.205.135 - - [16/Jul/2021:04:33:05 +0000] "GET /favicon.ico HTTP/1.1" 404 179 "https://polar-temple-25791.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" 2021-07-16T04:34:55.263334+00:00 app[api]: Starting process with command `python manage.py migrate` by user somtochukwuuchegbu@gmail.com 2021-07-16T04:35:05.664576+00:00 heroku[run.9367]: State changed from starting to up 2021-07-16T04:35:05.984898+00:00 heroku[run.9367]: Awaiting client 2021-07-16T04:35:06.005500+00:00 heroku[run.9367]: Starting process with command `python manage.py migrate` 2021-07-16T04:35:12.861556+00:00 heroku[run.9367]: Process exited with status 0 2021-07-16T04:35:13.111213+00:00 heroku[run.9367]: … -
How to send a list of json object in PUT request for non-primary ID in Django?
I am getting a PUT request which is having array of json objects for same non-primary ID. Example: { "some_non_pk_id":101, "user_entries":[ { "name":"foo", "height":1.56 }, { "name":"bar", "height":1.76 }, . . . ] } I need to upsert the object in a table which looks something like this +----+----------------+------+--------+ | id | some_non_pk_id | name | height | +----+----------------+------+--------+ | 1 | 101 | foo | 1.56 | | 2 | 101 | bar | 1.76 | +----+----------------+------+--------+ The url of the PUT/PATCHrequest will be/api/details/?some_non_pk_id=101. I am not sure how to override the updateorpartial_updateofModelViewSet` to upsert this. I am ok if the request body can be changed to something like this. Changing the request bosy is in my control. [ { "some_non_pk_id":101, "name":"foo", "height":1.56 }, { "some_non_pk_id":101, "name":"bar", "height":1.76 } ] -
Django generate many pages with a single view
my project consists of making a library with different categories of books. for each category of book I made as many views. I would like to know if for all the existing categories I can make a single view. For example here instead of three views I want only one view to manage all categories views.py def mathematics(request): mathematics_books = Books.objects.filter(category_id=1) total_mathematics_books = mathematics_books.count() page = request.GET.get('page', 1) paginator = Paginator(mathematics_books, 5) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'total_mathematics_books': total_mathematics_books, 'page_obj': page_obj, } return render(request, 'mathematics.html',context) def biology(request): biology_books = Books.objects.filter(category_id=2) total_biology_books = biology_books.count() page = request.GET.get('page', 1) paginator = Paginator(biology_books, 5) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'total_biology_books': total_biology_books, 'page_obj': page_obj, } return render(request, 'biology.html',context) def chemistry(request): chemistry_books = Books.objects.filter(category_id=3) total_chemistry_books = chemistry_books.count() page = request.GET.get('page', 1) paginator = Paginator(chemistry_books, 5) try: page_obj = paginator.page(page) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) context = { 'total_chemistry_books': total_chemistry_books, 'page_obj': page_obj, } return render(request, 'chemistry.html',context) models.py class Categories(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) def __str__(self): return self.name class Authors(models.Model): name = models.CharField(max_length=250) biography = models.TextField(blank=True) … -
Creating HTML Modal for number of items in database
I am creating a donation application where users can view donations. If they want to learn more about a specific donation, they can click on the view button and an HTML overlay menu will come up. My problem is that I use a for loop to display every donation, and there is no specific number of donations, there can be infinite number of donations, and the view button only works for the first donation. How can I fix this so the view button can work for every donation? My code is down bellow {% extends 'suppliesbase.html' %} {% load static %} {% block content %} <div class="row"> {% for donation in donations %} <div class="col-lg-4"> <img class="thumbnail" src="{{donation.imageURL}}"> <div class="box-element product"> <h6><strong>{{donation.title}}</strong></h6> <hr> <button class="btn btn-outline-success" id="open-modal-button" href="#">View</button> <h4 style="display: inline-block; float: right"><strong>Free!</strong></h4> </div> </div> {% endfor %} </div> <!--Modal Overlay Content --> <div id="modal-overlay"> <div id="modal"> <div class="head"> <a id="close-modal-button" href="javascript:;"></a> </div> <div class="content">Modal content</div> </div> </div> <script> var openModalButton = document.getElementById("open-modal-button"); var closeModalButton = document.getElementById("close-modal-button"); var modalOverlay = document.getElementById("modal-overlay"); var modal = document.getElementById("modal"); // function that open modal and display the overlay openModalButton.addEventListener("click", event => { modalOverlay.classList.add("modal-overlay-visible"); modal.classList.add("modal-visible"); }); // function that closes the modal and remove the … -
adding multiple items to cart using a checkbox in the table
I want to include products from store page, to cart. On the shop page I have a table where there are checkboxes in the last column. when I select a checkbox in the header of the table, all checkboxes on that page are highlighted. At the end of the page there is a button that sends all selected products to the cart like this: enter image description here How can i do this? -
Django generic view redirect
I have created a blog app using Django wherein Generic views are used to Add, Update and Delete a blog post. I want to know a method by which I could redirect to the same Blog page after creating it or updating it. Thanks -
view function is not being executed
I was trying to make a basic banking system using django, in which a user can transfer money to other user. But when I tried to transfer money nothing happens, probably because transfer function in views.py is not being executed. Here are transaction.html file and transfer function from views.py.: transaction.html ''' {% extends 'bank/base.html' %} {% block content %} <div class="container"> <h2>Transfer Money</h2> <form method="post"> {% csrf_token %} <label for="s_acc">Select sender details</label> <select name="s_acc" required> <option value="select">Select</option> {% for cust in customer %} <option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option> {% endfor %} </select> <br> <label for="amt">Enter amount</label> <input type="number" name="amt" required> <br> <label for="r_acc">Select receiver details</label> <select name="r_acc" required> <option value="select">Select</option> {% for cust in customer %} <option value="{{cust.account_number}}">{{cust.name}}: {{cust.account_number}} : {{cust.balance}}</option> {% endfor %} </select> <br> <button type="submit" name="button">TRANSFER</button> </form> </div> {% endblock %} ''' transfer function from vews.py: def Transfer(request): customer = Customer.objects.all(); if request.method=="POST": s_acc = request.POST.get('s_acc') amt = request.POST.get('amt') r_acc = request.POST.get('r_acc') print(s_acc) print(amt) print(r_acc) amt = int(amt) if((s_acc=='select')or(amt=='select')or(r_acc=='select')or(s_acc==r_acc)): messages.warning(request,"Account not selected or both the accounts are same") elif(amt<=0): messages.warning(request,"Enter valid amount") else: for c in customer: if(c.account_number == s_acc): s_name = c.name; if(amt>c.balance): messages.warning(request,"Insufficient balance") break for x in customer: if(x.account_number == r_acc): r_name = x.name … -
CORS issue working with DJango Simple SSO
I'm using a fork of Django Simple SSO as an authentication mechanism on a Server. It works great while we use the "standard" way to log in on the server. This means, we just access to the /login path, log in, and then navigate across the restricted paths, etc. The problem comes when we want to connect to a 3rd server that also relays on SSO auth vía javascript/AJAX without direct access to /login path first. I've tried to use django-cors-headers but didn't get the expected result. I'm close to give up so any help is welcome. The problem When the browser is redirected to the Auth Server in order to verify that the browser is logged with a valid user, the cookie header is not transferred. (See the diagram on button for further details on how Simple SSO works) The headers set by the auth-server on the preflight request are the following: Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: accept-encoding, accept, authorization, cookie, content-type, dnt, origin, user-agent, x-csrftoken, x-grafana-org-id, x-dashboard-id, x-panel-id, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: https://client-server-domain Access-Control-Max-Age: 86400 Connection: keep-alive Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Fri, 16 Jul 2021 12:14:54 GMT Server: nginx Vary: Origin The headers … -
I got IntegrityError with delet user in django
When I delete user , I got this error. There are some problems with moving django-registration-redux(django-registration) to django-allauth. So I was trying to drop registration_registrationprofile table. But I can't find that table. I can only see those tables. It isn't look like related to this problem. How can I delete user succesfully? account_emailaddress papers_paperstatus account_emailconfirmation papers_signature addresses_address papers_verifyingexplanation auth_group profiles_alloweduser auth_group_permissions profiles_alloweduser_allowed_users auth_permission profiles_customuser authtoken_token profiles_customuser_groups django_admin_log profiles_customuser_user_permissions django_content_type profiles_expertprofile django_migrations profiles_mandate django_session profiles_profile django_site socialaccount_socialaccount papers_contractor socialaccount_socialapp papers_explanationsignature socialaccount_socialapp_sites papers_paper socialaccount_socialtoken Those are error stacks. IntegrityError at /api/user/25/ update or delete on table "profiles_customuser" violates foreign key constraint "registration_registr_user_id_5fcbf725_fk_profiles_" on table "registration_registrationprofile" DETAIL: Key (id)=(25) is still referenced from table "registration_registrationprofile". Request Method: DELETE Request URL: https://dev.onepaper.biz/api/user/25/ File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 242, in _commit return self.connection.commit() The above exception (update or delete on table "profiles_customuser" violates foreign key constraint "registration_registr_user_id_5fcbf725_fk_profiles_" on table "registration_registrationprofile" DETAIL: Key (id)=(25) is still referenced from table "registration_registrationprofile". ) was the direct cause of the following exception: File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/djangovenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) … -
Customizing the Ordering Field in ElasticSearch in Django_Restful_framework
class PublisherDocumentView(DocumentViewSet): document = RecommendationDocument serializer_class = RecommendationElasicSerializer lookup_field = 'id' fielddata = True filter_backends = [ FilteringFilterBackend, CompoundSearchFilterBackend, DefaultOrderingFilterBackend, OrderingFilterBackend, SearchFilterBackend, SuggesterFilterBackend, # This should be the last backend ] search_fields = ( 'sku','artikelNr1','artikelNr2', 'statusCode' ,'statusText' ,'saisonRetourenCode','saisonRetourenText','saisonCode','saisonText','geschlechtCode','geschlechtText','rayonCode','rayonText','warenArtCode','warenArtText','wuCode','wuText','waCode','warenGruppe','alterCode','farbe','material','bezeichnung','pictureName','picturePathLocal','kollektion','comCode' ,'lieferant','eKchf','eti','vp','groessenCode','categories','groessen','zlQty', 'productId','published','productName','shortDescription','fullDescription','flag' ) multi_match_search_fields = ( 'sku','artikelNr1','artikelNr2', 'statusCode' ,'statusText' ,'saisonRetourenCode','saisonRetourenText','saisonCode','saisonText','geschlechtCode','geschlechtText','rayonCode','rayonText','warenArtCode','warenArtText','wuCode','wuText','waCode','warenGruppe','alterCode','farbe','material','bezeichnung','pictureName','picturePathLocal','kollektion','comCode' ,'lieferant','eKchf','eti','vp','groessenCode','categories','groessen','zlQty', 'productId','published','productName','shortDescription','fullDescription','flag' ) filter_fields = { 'artikelNr1': 'artikelNr1.raw', 'artikelNr2': 'artikelNr2.raw', 'statusText': 'statusText.raw', 'flag': 'flag.raw', } ordering_fields = { 'flag': 'flag.raw', } ordering = ('flag', ) I want to customize the ordering of this "flag" field based on their value like "isMust or IsNew" suppose to come first in ordering field. do you guys know how to do this? any body has any idea how to fix these problems. Thanks in advance -
How to use gulp in django project
I downloaded the "Neumorphism" template from the Internet and want to use it in my Django project. When I added the HTML and CSS files to my project separately, the drop down page on the mobile page did not open. I realized that I had to use the gulp file in the project. But I need to learn the steps to add a template that uses gulp and nodejs. I'm using virtualenv and need to know how to configure the file structure to work properly when running the server?(python manage.py runserver) And another question, to upload the site to the server, what are the conditions for using gulp on a personal computer? -
How to filter from two related models in django
This is my model class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='profile') mob_no = models.CharField(max_length=10,blank=False,default=None) address = models.TextField(blank=False,default=None) country = models.CharField(max_length=80,blank=False,default=None) pin = models.PositiveIntegerField(blank=False,default=None) sponsor_id = models.CharField(max_length=15,blank=False,default=None) #ref id is sponsor id of the person who added the user. ref_id = models.CharField(max_length=15,blank=False,default=None) class Meta: verbose_name_plural = "User Profile" def __str__(self): return self.user.username #---------------------------------------------User Payment Details------------------------------------------------------ class UserPaymentProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='payprofile') selected_product = models.CharField(max_length=80,blank=False,default='NIL') payment_status = models.BooleanField(default=False) Tid = models.CharField(max_length=40,blank=False,default=0) class Meta: verbose_name_plural = "User Payment Profile" def __str__(self): return self.user.username I am trying to get list of users with a specific sponsor_id and payment_status == True I could not fin a way to filter from both related models -
Multiplying the values of two different models in Django
Well i'm trying to create two models whereas the product model is: class Product(models.Model): id = models.AutoField(primary_key=True) price = models.FloatField(null=False) inStock = models.BooleanField(null=False) and another model for cart where: class Cart(models.Model): productID = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() total I want total here to equal Product.price multiplied by the Cart.quantity Is there a way how can I achieve it on Django? -
Valid (?) JSON data causing errors in Django, must be served to frontend as string and converted by JSON.parse() in javascript - why?
I have a JSON file hosted locally in my Django directory. It is fetched from that file to a view in views.py, where it is read in like so: def Stops(request): json_data = open(finders.find('JSON/myjson.json')) data1 = json.load(json_data) # deserialises it data2 = json.dumps(data1) # json formatted string json_data.close() return JsonResponse(data2, safe=False) Using JsonResponse without (safe=False) returns the following error: TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False. Similarly, using json.loads(json_data.read()) instead of json.load gives this error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) This is confusing to me - I have validated the JSON using an online validator. When the JSON is sent to the frontend with safe=False, the resulting object that arrives is a string, even after calling .json() on it in javascript like so: fetch("/json").then(response => { return response.json(); }).then(data => { console.log("data ", data); <---- This logs a string to console ... However going another step and calling JSON.parse() on the string converts the object to a JSON object that I can use as intended data = JSON.parse(data); console.log("jsonData", data); <---- This logs a JSON object to console But this solution doesn't strike me as a complete …