Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save timeslot details when creating a booking instance django
I have a django app in which I am implementing a booking system. I have created a TimeSlot model that has a start_time, end_time, and time_slot_owner. I want to implement a booking system in which the timeslot details, such as the start_time, end_time, and time_slot_owner are added to the Booking Model once it has been created. My TimeSlot model: class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() My Booking Model: class Booking(models.Model): bookings_owner = models.ForeignKey(User, on_delete=models.CASCADE) # time_slot = models.ForeignKey(TimeSlot, on_delete) meals_booked = models.IntegerField(default=0, validators=[MinValueValidator(0)]) start_time = models.TimeField() end_time = models.TimeField() restaurant = models.ForeignKey(User, on_delete=models.CASCADE, related_name="restaurant") What I have in my create_booking function so far in views.py def create_booking(request): instance = Booking() data = request.POST.copy() data["bookings_owner"] = request.user form = BookingForm(data or None, instance=instance) if request.method == "POST" and form.is_valid(): start_time = request.POST.get("start_time") print(start_time) form.save() return HttpResponseRedirect(reverse("food_avail:view_bookings")) return render(request, "food_avail/create_booking.html", {"booking": form}) When I click on Book: It leads me to this page where I can enter number of meals I want to book: Once I enter the number of meals I want the final page to show the following details for each booking: Booking.booking_owner.username | TimeSlot.time_slot_owner.username | TimeSlot.start_time | TimeSlot.end_time | Booking.meals_booked -
Reportlab pdf prints only one page
I am able to create table with reportlab as shown below, but it prints only on one page, how I can print data to multiple pages def pdf_view(request): enc = pdfencrypt.StandardEncryption("pass", canPrint=0) buf = io.BytesIO() c = canvas.Canvas(buf, encrypt=enc) width, height = A4 textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [] users = User.objects.filter(is_staff=False) for user in users: lines.append(user.username) lines.append(user.email) lines.append(user.first_name) table = Table(lines, colWidths=10 * mm) table.setStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)]) table.wrapOn(c, width, height) table.drawOn(c, 0 * mm, 5 * mm) styles = getSampleStyleSheet() ptext = "This is an example." p = Paragraph(ptext, style=styles["Normal"]) p.wrapOn(c, 50 * mm, 50 * mm) # size of 'textbox' for linebreaks etc. p.drawOn(c, 0 * mm, 0 * mm) # position of text / where to draw c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='users.pdf') -
how to create object in django
is it possible to create new product using the scrap.py in django ? when never i run scrap.py i get this error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. my app models file from django.db import models from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() content = models.TextField(max_length=400) def __str__(self): return self.name scrap.py file from models import Product Product.objects.create( name = 'BMW', age =25 , content = 'cool car' ) -
I need to create a login system with Django
I need to create a login system with Django using something like @login_required, but I don't wanna use the Users in "AUTHENTICATION AND AUTHORIZATION", Users are stored in my app. Can someone help me? I need to store login info in cache or something? -
Why I get an error when adding __init__(self) method to Django rest framework viewset class?
I Am keep getting a error when trying to build a Django API. I have this class: from uuid import UUID from django.shortcuts import render from django.http.response import JsonResponse from django.http.request import HttpRequest from rest_framework import viewsets, status from rest_framework.parsers import JSONParser from rest_framework.response import Response from Instruments import serializers from Instruments.services import InstrumentsService from rest_framework.decorators import api_view from Instruments.services import InstrumentsService from Instruments.models import Instrument from Instruments.serializers import InstrumentsSerializer # Application views live here class InstrumentViewSet(viewsets.ViewSet): # instruments = Instrument.objects.all() def __init__(self): # self.instrument_service = InstrumentsService() # self.instruments = Instrument.objects.all() super().__init__() def list(self, request: HttpRequest): try: self.instruments = Instrument.objects.all() serializer = InstrumentsSerializer(self.instruments, many=True) # data = self.instrument_service.get_instruments() data = serializer.data return JsonResponse(data, status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse( {"Status": f"Error: {exc}"}, status=status.HTTP_400_BAD_REQUEST, safe=False, ) when the init() method is defining even if it is just doing pass the django server gives me this error when I send a request: TypeError at /api/ __init__() got an unexpected keyword argument 'suffix' If I remove or comment out the init() method it works.why?? -
Accessing static file images through url not working django
I am currently trying to configure my django project so that I can access static file images via url. However, it is currentely saying that the image does no exist. Here are my settings for static files: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, '/static/images') Here are my base project urls: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) And my folder structure is, in the root of my project: static->images->[all images in here] Upon trying to access an image via url like this: http://127.0.0.1:8000/images/*proper image name* It tells me that the image doesn't exist. Does anyone know why this may be happening? -
Python remote developer skills requirement
As an absolute beginner in python programming language, I find the language interesting and easy to learn. However, I intend to take up a job later as a python developer. My problem is I'm a little confused on what core areas to dwell on primarily rather than attempting to know all the classes, libraries and modules. I get overwhelmed. What core areas and possibly tutorials do I concentrate on? -
Put DISLIKE by removing LIKE. Django
Maybe someone can help. There is a Django project where I am trying to add a LIKE / DISLIKE function. I figured out how to add or remove LIKE / DISLIKE. But my logic has a gap in that the user can put both LIKE and DISLIKE (this is not entirely correct). Therefore, I want to make a "feint with the ears" as follows: if the user puts LIKE, then changes his mind and puts DISLIKE, then DISLIKE would be added, and LIKE would be canceled automatically (as happens on YouTube). I have the following views: class AddLikeView (View) class RemoveLikeView (View) class AddDisLikeView (View) class RemoveDisLikeView (View) As far as I understand, I need to write some kind of logic in AddDisLikeView and RemoveLikeView. Tell me please. class AddDisLikeView(View): def post(self, request, *args, **kwargs): blog_post_id = int(request.POST.get('blog_post_id')) user_id = int(request.POST.get('user_id')) url_from = request.POST.get('url_from') user_inst = User.objects.get(id=user_id) blog_post_inst = News.objects.get(id=blog_post_id) try: blog_dislike_inst = BlogDisLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst) except Exception as e: blog_dislike = BlogDisLikes(blog_post=blog_post_inst, disliked_by=user_inst, dislike=True) blog_dislike.save() return redirect(url_from) class RemoveLikeView(View): def post(self, request, *args, **kwargs): blog_likes_id = int(request.POST.get('blog_likes_id')) url_from = request.POST.get('url_from') blog_like = BlogLikes.objects.get(id=blog_likes_id) blog_like.delete() return redirect(url_from) -
Unable to send multiple to database in Django
My aim is to send all the Added items to my database. There is no error while posting data to the database but my form populates the database with only one entry, i.e., "The value of the last input among all inputs". I am new to Django development, please guide me on where I am doing wrong. My Html looks like this: Tables in my database: Primary key Table: Foreign Key Table: Table that already contains items. Table that is made to receive the items from table one. I am just trying to learn how to post data of multiple inputs, otherwise there isn't any logic behind this operation. From models.py: class Item(models.Model): Id = models.AutoField(primary_key=True) itemName = models.CharField(max_length=30,unique=True) cId = models.ForeignKey(Category,on_delete=CASCADE) def __str__(self): return self.itemName class TransferedItems(models.Model): Id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) item = models.ForeignKey(Item, on_delete=CASCADE) From views.py: def transfer(request): if request.method == "POST": a = request.POST.get("a"); obj = TransferedItems(item_id = a); obj.save(); return HttpResponse("sent") else: return HttpResponse("form submission failed") From HTML: <html lang="en"> <body> <div class="maindiv"> <div class="divA"> <label for="coffee">Coffee</label> <select name="coffee" id="coffee"> {% for opt in opts %} <option value="{{opt.Id}}"> {{opt.itemName}} </option> {% endfor %} </select> <button onclick="addtocart()">ADD</button> </div> <div class="divB"> <form method="post" id="cart-screen-form" action="transfer"> {% csrf_token … -
Django render or redirect not working in view after AJAX POST
I am using navigator.geolocation to get an update on location with it's provided watchPosition function with following code: function updatePosition() { if(navigator.geolocation) { navigator.geolocation.watchPosition(calculateDistance); } else { console.log("Geolocation is not supported by this browser.") } } If then new location coordinates I fetch is under a kilometer in distance, I issue a post request and try to render another view. I use google maps API to calculate the distance with function computeDistanceBetween. Here is the code: function calculateDistance(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var dis = google.maps.geometry.spherical.computeDistanceBetween(pos, mapOptions.center); if(dis <= 1000 && dis >= 0 && rendered == false) { var url = '/app/near_park/'; var csrftoken = getCookie('csrftoken'); $.ajax({ url: url, type: "POST", data: { csrfmiddlewaretoken: csrftoken, in_proximity : 1 }, success: function() { rendered = true; console.log("Success"); }, error: function(xhr, errmsg, err) { console.log(xhr.status+": "+xhr.responseText); } }); } } Here is the view handling the post request: def index_close(request): context_dict = {} try: current = Owner.objects.get(user=u) context_dict['checked_in'] = current.checked_in except: context_dict['checked_in'] = False print("##########") #return redirect(reverse('dogpark:register')) return render(request, 'dogpark/index_close.html', context=context_dict) Whenever I get a location update using the sensor utility of dev tools, I do see the print of hash marks on terminal but the redirect or … -
serializer.data not showing any data
I'm still getting to know DRF but when I run the command serializer.data it returns an empty set. Here is what I'm working with models.py import datetime from django.db import models from django.db.models.fields.related import ForeignKey from django.utils import timezone from accounts.models import CustomUser class IndustriaCategoria(models.Model): name = models.CharField(max_length=20, null=False, blank=False) def __str__(self): return self.name class Post(models.Model): category = models.ForeignKey(IndustriaCategoria, on_delete=models.CASCADE) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=512, null=False, blank=False) body = models.TextField() timestamp = models.DateTimeField(default=timezone.now) link = models.URLField(max_length=500, null=True) ups = models.IntegerField(default=0) score = models.IntegerField(default=0) hotness = models.IntegerField(default=0) serializers.py from django.db.models import fields from rest_framework import serializers from .models import IndustriaCategoria, Empresa, Post, Comment class IndustriCategoria(serializers.Serializer): class Meta: model = IndustriaCategoria fielst = ('__all__') class PostSerializer(serializers.Serializer): class Meta: model = Post fields = ('__all__') I have a management command which creates some data so I can just start throwing commands. Here is where the problem comes up: >>> from accounts.models import CustomUser >>> from forum.models import IndustriaCategoria, Post >>> from forum.serializers import PostSerializer, IndustriaCategoria >>> u = CustomUser.objects.all().first() >>> i = IndustriaCategoria.objects.all().first() >>> post = Post(category=i, author=u, title='hello world', body='this is a test', link='https://helloworld.com') >>> post.save() >>> serializer = PostSerializer(post) >>> serializer.data {} Any idea why I got an empty … -
Cart delete an item and apply a coupon in js
I am trying to remove an item without removing the cart and reducing a price if the customer has a coupon or exceeds a certain quantity while js before using Django here is the html code js if you have any advice do not hesitate html <div data-name="name" data-price="250" data-id="2"> <img src="x.jpg" alt="" /> <h3>name</h3> <input type="number" class="count" value="1" /> <button class="tiny">Add to cart</button> </div> <script type="text/template" id="cartT"> <% _.each(items, function (item) { %> <div class = "panel"> <h3> <%= item.name %> </h3> <span class="label"> <%= item.count %> piece<% if(item.count > 1) {%>s <%}%> for <%= item.total %>$</span > </div> <% }); %> </script> js addItem: function (item) { if (this.containsItem(item.id) === false) { this.items.push({ id: item.id, name: item.name, price: item.price, count: item.count, total: item.price * item.count }); storage.saveCart(this.items); } else { this.updateItem(item); } this.total += item.price * item.count; this.count += item.count; helpers.updateView(); }, containsItem: function (id) { if (this.items === undefined) { return false; } for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; if (id == _item.id) { return true; } } return false; }, updateItem: function (object) { for (var i = 0; i < this.items.length; i++) { var _item = this.items[i]; … -
Best way to render a sortable table from a Django Model which displays custom fields?
I want to generate a table based on selected fields from a model(decided by an algorithm), and I want to be able to sort the columns in that table. I also want the user to be able to click on a button on each row which leads to a new page generated by a key from that row (ie. "edit") I have tried django-tables2, but it seems that this would prevent me from adding the buttons and adding the algorithms I want which govern what types of fields are on display. The generation of the custom table itself is not a problem - but I can't seem to find any sources on making a sorting function. Where can I find this? -
Incorrect redirect of NGINX with Docker
I'm building my first project with Django, NGINX and Docker. Below the nginx.conf: upstream project { server website:8000; } server { listen 80; server_name MY-DOMAIN; location / { proxy_pass http://project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 4G; } location /static/ { alias /app/static-folder/; } location /media/ { alias /app/media-folder/; } } And the docker-compose: version: '3.7' services: website: container_name: web_project image: project/django build: ./djangodocker restart: always env_file: prod.env command: sh -c "cd djangodocker/ && gunicorn djangodocker.wsgi:application --bind 0.0.0.0:8000" volumes: - static-folder:/app/static-folder - media-folder:/app/media-folder expose: - 8000 nginx: container_name: nginx_web_project image: project/nginx build: ./nginx volumes: - static-folder:/app/static-folder - media-folder:/app/media-folder ports: - 8000:80 depends_on: - website volumes: static-folder: media-folder: I can build the image but I can't see the website into the correct url. I see the website at MY-DOMAIN:8000 instead of MY-DOMAIN and this is my problem. -
How to map different request types to different views using the same exact path in Django?
I want to have a url something like api/instrument/{id} and then based on the request type GET, POST, DELETE route the request to a different view in my Django app. I have these views: from django.shortcuts import render from django.http.response import JsonResponse, from django.http.request import HttpRequest from rest_framework.parsers import JSONParser from rest_framework import status from Instruments.services import instruments_service from models import Instrument from serializers import InstrumentsSerializer from rest_framework.decorators import api_view from services import InstrumentsService # Application views live here @api_view('GET') def get_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() data={} try: data = instrument_service.get_instrument_by_id(id) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) @api_view('POST') def update_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() instrument_data = JSONParser().parse(request) data={} try: data = instrument_service.update_instrument_by_id(id, instrument_data) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) @api_view('DELETE') def delete_instrument_by_id(request:HttpRequest, id): instrument_service = InstrumentsService() data={} try: data = instrument_service.delete_instrument_by_id(id) return JsonResponse(data,status=status.HTTP_200_OK, safe=False) except Exception as exc: return JsonResponse({"Status":f"Error: {exc}"},status=status.HTTP_404_NOT_FOUND , safe=False) I see that people using django make ONE function to hanlde all requests and then they have logioc inside it but that seems so wrong to me. Is there a way to map the same URL endpoint to different function based on the request type? -
How to read a specific field in a MongoDB collection
I want to print a specific field on html on mongodb, but I am getting an error, how can I do it? I'm getting IndexError: list index out of range error. view py; def deleted2(request): mpid = ('XX') tuy = ('XX') client = MongoClient("XX") print('connectionsuccess') database = client["1"] collection = database["2"] query = {} query["XX"] = mpid query["$or"] = [ { "Tuy": tuy } ] print('querysuccess') cursor = collection.find(query) sonuc= loads(dumps(cursor)) msg=sonuc[0]["_id"] print(msg) client.close() return render(request, 'deleted.html',{'msg':msg}) -
Identity Verification by SMS/Email | Django
Please help me with choosing a solution for implementing identity verification using a one-time token with a limited lifetime. By identity verification, i mean the need to send a token/code to a user via a phone number or email. For example, to reset password. I am interested in a solution that is best for use in a modern web application. Please tell me based on your experience in developing such systems. The solutions I have on my mind: Use redis as storage. In case of working with email, generate a token and save it in redis, where the key - user's email address. In the case of working with SMS, create a code and save it in redis, where the key - user's phone number. Possible disadvantage: since redis is designed to work with a key-value pair, it is impossible to have two tokens/codes at once. (meaning that they will have different purposes). It is possible that this is not necessary at all. Use the Django object model as storage. Something like this: class TokenManager(models.Manager): # Some util-methods. # ... def delete_expired(self): expires = models.ExpressionWrapper( models.F("created_at") + models.F("lifetime"), models.DateTimeField() ) self.annotate(expires_at=expires).filter(expires_at__lte=now()).delete() class Token(models.Model): # Roughly speaking, token identifier. Examples: "password-reset", … -
How to limit CheckboxSelectMultiple choices for paid membership in Django
I'm struggling with my code in Django. My app is Garden, when you create a new garden and you are a member of 'plus' membership, you can select unlimited plants. But if you are a member of free membership you can select only 3 plants. How can I do that? models.py class Garden(models.Model): name = models.CharField(max_length=256) description = models.TextField(blank=True, default='') address = models.CharField(max_length=512) plant = models.ManyToManyField(Plant, related_name="gardens", through="GardenPlant") user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) class Membership(models.Model): PLUS = 'PL' FREE = 'FR' MEMBERSHIP_CHOICES = ( (PLUS, 'plus'), (FREE, 'free') ) slug = models.SlugField(null=True, blank=True) membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default=FREE, max_length=30) price = models.DecimalField(default=0, max_digits=999, decimal_places=2) class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='user_membership', on_delete=models.CASCADE) membership = models.ForeignKey(Membership, related_name='user_membership', on_delete=models.SET_NULL, null=True) class Subscription(models.Model): user_membership = models.ForeignKey(UserMembership, related_name='subscription', on_delete=models.CASCADE) active = models.BooleanField(default=True) def __str__(self): return self.user_membership.user.username forms.py class GardenForm(forms.ModelForm): class Meta: model = Garden fields = ['name', 'description', 'address', 'plant'] def clean_plant(self): value = self.cleaned_data['plant'] if len(value) > 3: raise forms.ValidationError("You can't select more than 3 items.") return value plant = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Plant.objects.all()) def save(self, user): garden = super().save(commit=False) garden.user = user garden.save() garden.plant.add(*self.cleaned_data.get('plant')) views.py def create_garden(request): form = GardenForm(request.POST or None) if form.is_valid(): form.save(request.user) return redirect('/garden') context = {"form": form, "has_subscription": subscription_check(request.user)} return render(request, "create_garden.html", … -
Heroku push is failing with error: node:internal/modules/cjs/loader:936 throw err;
I'm trying to build a small web application with django and react. I already added the buildpacks for both. Now I wanted to run git push heroku master, but I keep getting this output: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpacks: remote: 1. heroku/nodejs remote: 2. heroku/python remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: remote: NPM_CONFIG_LOGLEVEL=error remote: NODE_VERBOSE=false remote: NODE_ENV=production remote: NODE_MODULES_CACHE=true remote: remote: -----> Installing binaries remote: engines.node (package.json): 16.13.0 remote: engines.npm (package.json): 8.1.0 remote: remote: Resolving node version 16.13.0... remote: Downloading and installing node 16.13.0... remote: npm 8.1.0 already installed with node remote: remote: -----> Installing dependencies remote: Prebuild detected (node_modules already exists) remote: Rebuilding any native modules remote: rebuilt dependencies successfully remote: Installing any new modules (package.json) remote: remote: changed 3 packages, and audited 567 packages in 1s remote: remote: 55 packages are looking for funding remote: run `npm fund` for details remote: remote: found 0 vulnerabilities remote: remote: -----> Build remote: Running build remote: remote: > frontend@1.0.0 build remote: > webpack --mode production remote: remote: node:internal/modules/cjs/loader:936 remote: throw err; remote: ^ remote: remote: Error: Cannot find module '../lib/bootstrap' … -
django extra select to qs
How can i add addition select in queryset? queryset = ActivityCollection.objects.filter(date_at__gte=from_date, date_at__lte=to_date).order_by('date_at') it looks { "date_at": "2021-11-24", "views": 25, "clicks": 1, "cost": "25.00" }, i need to get: { "date_at": "2021-11-24", "views": 25, "clicks": 1, "cost": "25.00", "cpc": "25" } cpc = cost / clicks -
Django static css is not loading on page
I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working). I can't get my css static file to load on this practice page, css_practice.html. I have the following structure djangoAjax settings.py ... djangoAjaxApp static ok.css templates css_practice.html My settings.py: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = '############################################' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'djangoAjaxApp', ] 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 = 'djangoAjax.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djangoAjax.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL … -
how to save two dynamic relates forms together - django
I'm trying to save three forms together : this the scenario ; form 1 Invoice number, form 2 item names can have several items in one invoice , form 3 Serial number, serial number if in the form2 item one quantity = 10 then we have 10 unique serial numbers , and second item quantity = 4 we have to add 4 unique serial number , in one submit button . i've used maodelformset_factory to make the forms dynamic here is the models class ItemName(models.Model): item_name = models.CharField(max_length=60,unique=True) class Invoice(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) company = models.ForeignKey(ClientCompany,on_delete=models.PROTECT) invoice_no = models.IntegerField(blank=True,null=True) items = models.ManyToManyField(ItemName,through='Item') class Item(models.Model): invoice = models.ForeignKey(Invoice,on_delete=models.PROTECT,related_name='invoice') item = models.ForeignKey(ItemName,on_delete=models.PROTECT,related_name='item_name') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Serial(models.Model): item = models.ForeignKey(Item,on_delete=models.PROTECT) serial_no = models.CharField(max_length=15,unique=True) status = models.BooleanField(default=True) and i've used modelform i think it doesnt require to post the forms , the Serial and Item are modelformset_factory , and here is the view @login_required def create_invoice_view(request): form = InvoiceForm() item_formset = itemformset(queryset=Item.objects.none()) serial_formset = serialformset(queryset=Serial.objects.none()) if request.POST: form = InvoiceForm(request.POST) item_formset = itemformset(request.POST) serial_formset = serialformset(request.POST) if form.is_valid() and item_formset.is_valid() and request.user.is_superuser: invoice_obj = form.save(commit=False) invoice_obj.admin = request.user invoice_obj.save() data = { 'id':invoice_obj.id } for item in item_formset: item_obj = … -
infinite loop while overriding save method in Django
I want to override the save method in order to update quantity if the cart_item already exists insert new entry if the cart_item does not already exists but every time after the save method it gets stuck in infinite loop class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return str(self.id) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self) -> str: return self.product.name def save(self, *args, **kwargs): try: cart_item = CartItem.objects.get(cart_id=self.cart.id, product_id=self.product.id) cart_item.quantity += self.quantity pprint(cart_item) cart_item.save() #after this line goes into infinite loop except CartItem.DoesNotExist: super().save(*args, **kwargs) #after this line goes into infinite loop pprint("-------------------------here") `` -
Django Celery with Redis Issues on Digital Ocean App Platform
After quite a bit of trial and error and a step by step attempt to find solutions I thought I share the problems here and answer them myself according to what I've found. There is not too much documentation on this anywhere except small bits and pieces and this will hopefully help others in the future. Please not that this is specific to Django, Celery, Redis and the Digital Ocean App Platform. This is mostly about the below errors and further resulting implications: OSError: [Errno 38] Function not implemented and Cannot connect to redis://...... The first error happens when you try run the celery command celery -A your_app worker --beat -l info or similar on the App Platform. It appears that this is currently not supported on digital ocean. The second error occurs when you make a number of potential mistakes. -
How to calculate sums and multiplications in a django formset without using javascript?
I am a newbie in django and more in javasript, the question is that I am trying to do calculations in my formset with javascript but it does not come out, is there any way to do addition and multiplication in django formsets in an easier way?