Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import Deep Learning Models into Django
Background I was building a demo search engine and met a problem of loading my DL models into django. My code is basically structured like this: models/ DPR.py # save model defination utils/ manager.py # save model hyperparameter settings backend/ SearchApp/ view.py # where I want to use my model To clarify, my model should be initialized this way: from utils.manager import Manager from models.DPR import DPR manager = Manager() model = DPR(manager) Problems I want to load the model once after the django app run. I failed to load the model in backend/SearchEngine/app.py as suggested in here because I cannot import DPR and Manager into this file. So any idea? Thanks in advance. -
How do i update manytomanyfield in django?
I want to assign a job to an artisan who clicks 'Accept' but i cant get to assign or update the model to indicate that someone has accepted it.Below is my codes: I want to assign a job to an artisan who clicks 'Accept' but i cant get to assign or update the model to indicate that someone has accepted it.Below is my codes: #model here is the model **class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default =1) img = CloudinaryField(blank=True,null=True) status = models.CharField(max_length=200, null=True, blank=True, default='Pending') description=models.TextField(max_length=100,null=True,blank=True) #location = models.ForeignKey('artsans.Area' ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=300, null=True,blank=True) artisan_assigned = models.ManyToManyField('artisan.Artisan' ,blank=True) date_created = models.DateField(auto_now_add = True, null=True, blank=True) #date_accepted = models.DateField(auto_now_add = True, null=True, blank=True) #payment_id class Meta: verbose_name_plural='Orderitem' ordering = ['-date_created'] #2nd model 2nd model class Artisan(models.Model): user = models.OneToOneField(User,null=True,blank=True, on_delete= models.SET_NULL,related_name='artisan') nin = models.CharField(max_length=20, null=True, unique = True) location = models.ForeignKey(Area ,on_delete =models.CASCADE ,null=True,blank=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=15, null=True,unique=True) profession_name = models.CharField(max_length=200, null=True, unique = False) profile_img = CloudinaryField(blank=True,null=True) #date_created = models.DateTimeField(auto_now_add=True, null=True) date_created = models.DateField(auto_now_add = True, null=True, blank=True) def __str__(self): return str(self.user.username) # view file #view.py def jobAccepted(request,id): artisan = [Artisan.objects.filter(user=request.user)] if OrderItem.objects.get(id=id, ordered=True,status='Paid'): … -
Django is hashing my passwords different when creating a User vs trying to authenticate a user
I'm having trouble getting authentication to work and I found that the problem is my when I create a user their password is hashed in a different style than PBKDF2. Instead the passwords are always in a format like this: !iak7ijJTzsXRgsbwqtQBtXCZeU3Ccd96k2PpOCRa . However, when I'm working in my views make_password and check_password are using PBKDF2. Model: class UserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError("User must have an email address") user = self.model( email = self.normalize_email(email), ) user.set_password(password) user.save() return user def create_super_user(self, email, password=None): if not email: raise ValueError("User must have an email address") user = self.model( email = self.normalize_email(email), ) user.is_admin = True user.save() return user class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) email=models.EmailField( verbose_name='Email', max_length=255, unique=True ) password=models.CharField( max_length=255, verbose_name='password' ) username = None first_name = None last_name = None is_active = models.BooleanField(default=True) EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email I suspect the issue is coming from my custom Model, but it's identical to one I wrote for another app that had no issues. Register View: class CreateUser(APIView): serializer_class = CreateUserSerializer def post(self, request, format='json'): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): email = serializer.data.get('email') password = serializer.data.get('password') … -
Django Class based view filtering queryset but not?
I have a bit of a challenge with the way a date filter is working: Django Class based view, starting here https://github.com/varlenthegray/wcadmin/blob/master/customer/views.py#L61 class CustomersCustomReport(generic.ListView): model = Customer template_name = 'customer/reports/custom_report.html' def get_queryset(self): from_date = self.request.GET.get('fromDate') to_date = self.request.GET.get('toDate') self.queryset = Customer.objects.filter(is_active=True) if from_date: from_date = datetime.strptime(from_date, '%m-%d-%Y').strftime('%Y-%m-%d') print("Checking date from " + from_date) self.queryset.filter(next_service__gte=from_date) if to_date: to_date = datetime.strptime(to_date, '%m-%d-%Y').strftime('%Y-%m-%d') print("Checking date to " + to_date) self.queryset.filter(next_service__lte=to_date) return self.queryset I'm expecting this to return a filtered query based on the date that is a form field. https://wcadmin.innovated.tech/customer/report/custom_report?fromDate=04-01-2022&toDate=04-30-2022 I know this data isn't filtered because the entire customer list is 521 entries of mock data that are active. I was following information from this question: How Can I Filter By Date Range Using Djangos Built in ListView? I know it's getting data from the database, I know it's getting the date range I want from the URL due to the print, and the model is set to DateField for next_service, so I'm not quite sure what's going wrong here? -
Django ManyToMany through field with JSON:API and Swagger
I created a serializer that has a field called products_list, which is Nested. My problem is that I'm using Swagger autogenerated documentation with drf-yasg, and that field does not appear in the expected body for the endpoint. I installed and copied the SWAGGER_SETTINGS on https://github.com/glowka/drf-yasg-json-api My documentation schema code looks like this: from drf_yasg import openapi from drf_yasg.generators import OpenAPISchemaGenerator from drf_yasg.views import get_schema_view class BothHttpAndHttpsSchemaGenerator(OpenAPISchemaGenerator): def get_schema(self, request=None, public=False): schema = super().get_schema(request, public) schema.schemes = ["http", "https"] return schema schema_view = get_schema_view( openapi.Info( title="Mobile quoter API", default_version='1.0.0', description="API managing quoting app", terms_of_service="https://www.google.com/policies/terms/", ), generator_class=BothHttpAndHttpsSchemaGenerator, public=True, ) These are my Serializers: class QuoteSerializer(serializers.ModelSerializer): """Serializer for Quotes""" products_list = QuoteProductsSerializer(many=True, write_only=True, required=True) extra_info = serializers.CharField(required=False) class Meta: model = Quote fields = ( 'client', 'extra_info', 'products_list', 'generated_by', 'closed_at', 'created_at', 'cost', ) extra_kwargs = { 'quoteproducts_set': {'write_only': True}, 'generated_by': {'read_only': True}, 'closed_at': {'read_only': True}, 'created_at': {'read_only': True}, 'cost': {'read_only': True}, } My models: class Quote(SafeModel): client = models.ForeignKey(Client, on_delete=models.PROTECT) generated_by = models.ForeignKey(User, on_delete=models.PROTECT) closed_at = models.DateTimeField(blank=True, null=True) extra_info = models.TextField(blank=True) cost = models.DecimalField(max_digits=9, decimal_places=2) products = models.ManyToManyField(Product, through='QuoteProducts') # Quote model does not have a created_at field because SafeModel has one class QuoteProducts(Model): product = models.ForeignKey(Product, on_delete=models.PROTECT) quote = models.ForeignKey(Quote, on_delete=models.PROTECT) quantity … -
how do I update the cart with AJAX and django
I'm trying to use ajax to update the {{cartItems}} on nav when someone hits the add-to-cart button on shop.html without reloading the page, so far this is what I was able to work on. So how do I make this work? would really appreciate your help, thx!! rest of the important code is here: https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352 urls.py path('ajax_update/', views.ajax_update, name="ajax_update"), nav.html <span class="bag-icon"> {% url 'store:cart' as url %} <a id="icons-account" href="{% url 'store:cart' %}"><i class="fas fa-shopping-bag {% if request.path == url %}change{% endif %}"></i><a id="lil-icon-two">{{cartItems}}</a></a> </span> cart.js var updateBtns = document.getElementsByClassName('update-cart') for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) console.log('USER:', user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', cart) document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/" /*replacing location.reload() with ajax*/ function updating_cart_ajax(){ $.ajax({ url: 'ajax_update/', success: function (result) { $('.shop').reload(result) }, }); } } function updateUserOrder(productId, action){ console.log('User is logged in, … -
Can you order QuerySets in Django using a custom function?
I'm fairly new to Django and was following a tutorial. A little ways through, I decided to make my own ordering for a model, but this involves a custom function. This section of the program involves taking all the rooms and ordering them vertically on the page. Since the model is quite simple, I hope you can deduce the basic gist of the Room model as I am not very good at explaining (the entire model isn't shown but I think the relevant parts are). I want to order the rooms by the number of participants in the room. The function get_participants() defined at the bottom of the model does the work of getting the number of participants, however I cannot figure out how to apply this. class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) participants = models.ManyToManyField( User, related_name='participants', blank=True) def get_participants(self): return len(self.participants.all()) Here is one of the view functions where I have attempted to implement this function for sorting. I read somewhere that you can use the built-in python sorted() method on QuerySets, though I'm not sure this is the case. def home(request): q = request.GET.get('q') if request.GET.get('q') != None else '' rooms = sorted(Room.objects.filter( … -
Pass arguments from get_context_data() to a form
I have the following CBV: class UserSupplementTransporterView(TemplateView): model = Supplement template_name = 'tool/transporter-detail.html' context_object_name = "tarifs" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug = self.kwargs['slug'] context['supplement'] = get_object_or_404(Supplement, slug=slug) print(context['supplement'].header_row) return context I want to extract the value of context['supplement'].header_row and pass it to my forms.py: class CompareFormTransporteur(forms.ModelForm): file = forms.FileField(label="Fichier CSV", required=True) header_row = forms.IntegerField(label="Header row", required=True) class Meta: model = CheckFile fields = ['file',] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request if self.instance: self.initial['header_row'] = 2 #To be filled dynamically def clean(self): super().clean() extension = os.path.splitext(self.request.FILES['file'].name)[1] integer = self['header_row'].value() print(integer) if extension in ['.xlsx', '.xls']: uploaded = parse_excel(self.request.FILES['file'], rowheader=integer) elif extension == ".csv": uploaded = parse_csv(self.request.FILES['file']) elif extension == ".xml": uploaded = parse_xml(self.request.FILES['file']) self.request.session['uploaded'] = uploaded self.request.session['profile'] = self.cleaned_data.get('profile') print(self.cleaned_data.get('profile')) If needed, here are my models: class CheckFile(models.Model): name = models.CharField(max_length=200, blank=True) month = models.DateField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) profile = models.CharField('Choix du profil', blank=False, choices=PROFILE_CHOICES, max_length=100, default="Client") file = models.FileField(blank=True, null=True, upload_to="uploads/", validators=[validate_file_extension]) def __str__(self): return self.name class Meta: verbose_name = "file" verbose_name_plural = "files" class Supplement(models.Model): transporter = models.ForeignKey(Transporter, on_delete=DO_NOTHING, blank=True, null=True) company = models.ForeignKey(Company, on_delete=DO_NOTHING, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=DO_NOTHING, blank=True, null=True) header_row = models.IntegerField(blank=True) supplement_annonce_incomplete = models.DecimalField('Supplément annonce incomplète', … -
Pipenv ModuleNotFoundError
Searching for solution: pipenv install django pipenv shell django-admin startproject test . python manage.py runserver Result: ModuleNotFoundError: No module named 'django' It is working with: pipenv run python manage.py runserver But it worked before without pipenv run What's the case? Already reinstalled pipenv, cleared --lock, removed virtualenvs from .local folder, still same error when running python manage.py runserver inside project. -
Django: simplejwt isn't working with @api_view
I am trying to apply JWT token authentication to my Django app. I am following this tutorial https://simpleisbetterthancomplex.com/tutorial/2018/12/19/how-to-use-jwt-authentication-with-django-rest-framework.html I added these settings # settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } Then I added authentication check to api_view # views.py @api_view(['GET', 'POST']) @authentication_classes([authentication.TokenAuthentication]) @permission_classes([permissions.IsAuthenticated]) def task(request): if request.method == 'POST': if "type" in request.data: category_name = request.data["type"] task = create_task.delay(category_name) return Response({"message": "Create task", "task_id": task.id, "data": request.data}) else: return Response({"message": "Error, not found 'type' in POST request"}) Then I have an error: "Authentication credentials were not provided." for the following request: How can I fix the error? -
How to send data from two forms to two tables in Django database using one view?
I would like to send data from two forms to two tables in the Django database but I am getting the error "FOREIGN KEY constraint failed" error. How can I include two forms in the view to send data to the database tables? My models are the User model and class Account(models.Model): def create_new_ref_number(): not_unique = True while not_unique: unique_ref = random.randint(1000000000, 9999999999) if not Account.objects.filter(account_number=unique_ref): not_unique = False return str(unique_ref) user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE, default='0') DOB = models.DateField('DOB', max_length=20) address = models.CharField('Address', max_length=120) contact_number = models.CharField('Contact Number', max_length=120) ... account_number = models.CharField('Account Number', unique=True, max_length=20, null=False, editable=True, default=create_new_ref_number) ... current_balance = models.IntegerField('Balance', default=0, null=True) # transaction atomic allows to group changes in DB # if save operation will fail transaction creation will be also restored @transaction.atomic def apply_deposit(self, amount: int): # create new deposit transaction Trans.objects.create( user=self.user, amount=amount, account_number=self.account_number ) # update balance self.current_balance += amount self.save() def __str__(self): return str(self.name) My forms are class NewForm(ModelForm): class Meta: model = Account fields = ('DOB', 'address', 'contact_number', 'account_number') exclude = ['user', 'account_number'] labels = { 'DOB': '', 'address': '', 'contact_number': '', } widgets = { 'DOB': forms.DateInput(attrs={'class':'form-control','placeholder':'Date of Birth: dd/mm/yyyy'}, format='%m/%d/%y'), 'address': forms.TextInput(attrs={'class':'form-control','placeholder':'Address'}), 'contact_number': forms.TextInput(attrs={'class':'form-control','placeholder':'Contact Number'}) } and class … -
Count and Sum objects from different models - Django
I'm working on my Django project and I'm triying to order my posts by the sum of 2 related models. So this query should take the attendance count from the Post model and the attendant count from the Attending model and get the total sum. These are the models: class Post(models.Model): title = models.CharField(max_length=100) attendance = models.ManyToManyField(User, related_name='user_event_attendance') class Attending(models.Model): attendant = models.ForeignKey(User, related_name='events_attending', on_delete=models.CASCADE, null=True) post = models.ForeignKey('Post', on_delete=models.CASCADE, null=True) By now I have the 'attendance' count of the post model and ordered by the count: views.py new_query = Post.objects.filter( Q(status='NOT STARTED', post_options='PUBLIC') | Q(status='IN PROGRESS',post_options='PUBLIC')).distinct().annotate(total=Count('attendance')).order_by(-total') -
Problem with "extra_context" in a login view
I'm looking at login views rn but have troubles trying to redirect using the "next" variable that I'm trying to assign a value to inside of "extra_context" dictionary. Overriding "extra_context" in a custom view that inherits from "LoginView" also doesn't work. Redirecting with "next_page" or when hardcoding a value for GET's "next" field works fine. Here's my code. HTML <form class="" action="{%url 'luecken:login'%}" method="post"> {% csrf_token %} <table> <tr> <td>Username: </td> <td>{{form.username}}</td> </tr> <tr> <td>Password: </td> <td>{{form.password}}</td> </tr> </table> <button type="submit" name="logInBtn">Log in</button> <input type="hidden" name="next" value="{{next}}/"> </form> urls.py from django.urls import path, include from . import views from django.contrib.auth.views import LoginView # Custom urls app_name = 'luecken' urlpatterns = [ path('', views.homepage, name = 'homepage'), path('login', LoginView.as_view(extra_context={'next':'/some_url/'}), name='login') -
Django upload excel file
I'm trying to load my old excel format file (xls). But I got error with empty row. How can I break loop from empty row? def isNaN(num): return num != num wb = pd.ExcelFile(file) first_sheet = wb.sheet_names[0] ws = wb.parse(first_sheet, header=5) for row in ws.itertuples(): if isNaN(row[11]): break Error: AttributeError: 'dict' object has no attribute 'headers' -
Django List View get_queryset not rendering all objects
I have the following ListView which I want to use also for filtering the results class Membresias(ListView): model = Cliente template_name = 'main/membresias.html' def get_queryset(self): nombre = self.request.GET.get('nombre') if nombre is None: return Cliente.objects.all() else: return Cliente.objects.filter(nombre = nombre).values() when the 'nombre' variable is not None it show the results, PROBLEM: but when I leave it blank or is None, it does not show any records at all and according to the validation the queryset should retrieve all the records. Here is part of the html for the table <div class = "container"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Nombre</th> <th scope="col">Email</th> <th scope="col">Teléfono</th> <th scope="col">Activo</th> </tr> </thead> <tbody> {% for cliente in object_list %} <tr> <th scope="row"><a href="{{ cliente.get_absolute_url }}">{{cliente.id}}</a></th> <td>{{cliente.nombre}}</td> <td>{{cliente.email}}</td> <td>{{cliente.telefono}}</td> {% if cliente.activo == False %} <td><input type="checkbox" readonly class="form-check-input mt-1" id="Estatus" disabled value={{cliente.activo}}></td> {% else %} <td><input type="checkbox" readonly class="form-check-input mt-1" checked id="staticEmail" disabled value={{cliente.activo}}></td> {% endif %} </tr> {% endfor %} </tbody> </table> </div> -
codigo de favoritos en django
tengo una laguna mental y no se que estoy haciendo mal, me gustaria saber sus opiniones, estoy intentando crear un sistema de favoritos en django, y llamo al modelo en las template y todo bien, la cuestion es cuando quiero crear el boton para agregar a favoritos, me gustaria verificar si el producto existe dentro de los productos favoritos para poder pintar un boton u otro, dejo el codigo html {%for producto in productos%} <div class="col-md-4"> <figure class="card card-product-grid"> <div class="img-wrap"> <a href="{{ producto.redireccionar }}"><img src="{{ producto.imagenes.url}}"></a> </div> <!-- img-wrap.// --> <figcaption class="info-wrap"> <div class="fix-height"> <a href="{{ producto.redireccionar }}" class="title">{{producto.nombre_producto}}</a> <!--<div class="price-wrap mt-2"> <span class="price">{{producto.precio}}</span> </div> price-wrap.// --> </div> <a href="{% url 'add_cart' producto.id %}" class="btn btn-block btn-success"> Preguntar Disponibilidad </a> {% if producto.id in favoritos.product.id%} {{favorito.product.nombre_producto}} {%endif%} </figcaption> </figure> </div> <!-- col.// --> {%endfor%} </div><!-- row end.// --> ``` estoy colocando {% if producto.id in favoritos.product.id%} pero no funciona, funciona si le coloco un for pero se pinta mas de un boton, se pinta botones igual a la cantidad de productos en favoritos existentes, alguna sugerencia? espero haberme explicado bien -
djangoFilterBackend not filtering when using __in with ListAPIView and one of the filters is empty
I'm using DjangoFilterBackend to filter some input. The URL is written in javascript. It can be something like this: https://myApp/?se_ID__in=1,2&se_PR_ID__in=3 The thing is that not all the filters are always necesary. If all the filters are used there is no problem at all. But if some of them is not in the URL the filter is not working, it behaves as if this unused filter had a null value instead taking into account all the posible values of that field (skip the filter). I am doing some aggregations at the end of the view, after filtering. But as I said if one the posible filters is not used I get an empty JSON. Here my django files: serializers.py class FiltroSerializer(serializers.Serializer): se_ID = serializers.CharField(required=False, default='all', help_text='Sender ID') se_PR_ID = serializers.CharField(required=False, default='all', help_text='Sender pr ID') rc_ID = serializers.CharField(required=False, default='all', help_text='Receiver ID') cr_PR_ID = serializers.CharField(required=False, default='all', help_text='Receiver pr ID') class Meta: model = Data models.py from django.utils.translation import gettext_lazy as _ class Data(models.Model): shSeCustomerName1 = models.CharField(max_length=300, verbose_name=_('shSeCustomerName1')) shRcCustomerName1 = models.CharField(max_length=300, verbose_name=_('shRcCustomerName1')) se_ID = models.CharField(max_length=300, verbose_name=_('SenderID'), blank=True, null=True) se_DESC = models.CharField(max_length=300, verbose_name=_('SenderDESC'), blank=True, null=True) se_PR_ID = models.CharField(max_length=300, verbose_name=_('SenderProcessID'), blank=True, null=True) se_PR_DESC = models.CharField(max_length=300, verbose_name=_('SenderProcessDESC'), blank=True, null=True) rc_ID = models.CharField(max_length=300, verbose_name=_('ReceiverID'), blank=True, null=True) rc_DESC = … -
Django filters with APIVIew return the complete queryset
I'm trying to use django filter with APIVIew like I saw in this post and I'm geting an unexpected behavior: If the word passed on filter doesn't exists, it return nothing - OK If the word passed on filter exists, it return the complete queryset. I tried to use filters with ModelViewSet before and it works, but I have no success with APIView. I'm using the following code: views: from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from core.models import Profile from core.serializers import ProfileSerializer from django_filters.rest_framework import DjangoFilterBackend class ProfileFilter(DjangoFilterBackend): def filter_queryset(self, request, queryset, view): filter_class = self.get_filter_class(view, queryset) if filter_class: return filter_class(request.query_params, queryset=queryset, request=request).qs return queryset class ListProfileView(APIView): serializer_class = ProfileSerializer filter_fields = ('nome', 'link') queryset = Profile.objects.all() def get(self, request, format=None): queryset = Profile.objects.all() ff = ProfileFilter() filtered_queryset = ff.filter_queryset(request, queryset, self) if filtered_queryset.exists(): serializer = self.serializer_class(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response([], status=status.HTTP_200_OK) def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) model: from django.db import models class Profile(models.Model): nome = models.CharField(max_length=200, null=False, blank=False) link = models.CharField(max_length=200, null=False, blank=False) serializers: from rest_framework.serializers import ModelSerializer from core.models import Profile class ProfileSerializer(ModelSerializer): class Meta: model = … -
Django contact form with class based views
Can anyone explain me how to make send email form on page. So my forms.py class ContactForm(forms.Form): name = forms.CharField(required=True) last_name = forms.CharField() adults = forms.IntegerField() children = forms.IntegerField() email = forms.EmailField(required=True) message = forms.CharField(widget=forms.Textarea) views.py class TourDetailView(DetailView): model = models.Tour template_name = 'tours/tour-detail.html' form_class = forms.ContactForm success_url = 'tours.html' As far as i understand i need to get from request data , but i dont know how to do it. There are a lot of information in function based views, but i didnt get how to do it in class based views. And it would be nice of you to explain where should i put send_mail function. Any help will be appreciated. -
RelatedObjectDoesNotExist: User has no customer
I am following a Django youtube E-comerce tutorial by Dennis Ivy. I follow the tutorial line by line. from the initial i use to run the program and view all the output but alone the way i start getting this error message "RelatedObjectDoesNotExist: User has no customer". Am confuse because i keep repeating the video to see where i was wrong but could not trace it. please what is the solution? I realise the last time i tried, it open on its own using 'internet explorer' it display. when i open in 'chrome', it show the same erro. but when i deleted a customer from database it start showing the same erro again in 'internet explorer'. I dont want to give up on the tutorial cos i need it. please someone should assist me. Thanks from multiprocessing import context from django.shortcuts import render from .models import * from django.contrib.auth.models import User from django.http import JsonResponse import json # Create your views here. def store(request): if request.user.is_authenticated: customer = request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete =False) items =order.orderitem_set.all() cartItems=order.get_cart_items else: items=[] order = {'get_cart_total':0, 'get_cart_items':0} cartItems=order['get_cart_items'] products = Product.objects.all() context = { 'products':products, 'cartItems':cartItems, } return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: … -
Calculate Input Fields while user is filling data in form - Django Model Form
I have a user form through which I can save data to the database. I want certain fields to be auto calculated while I am filling the the form. For e.g. Net Weight = Gross Weight - Tier Weight and stuff like that. I also want to add RADIO BUTTONS for fields like LOADING, UNLOADING, DEDUCTION, etc. where values will be calculated when user selects one of the option given. I am also attaching a design of the type of form I want, I just don't know how to make that using Django.enter image description here I am using Django Model Form. Kindly Guide me. Models.py class PaddyPurchase(models.Model): ref_no = models.IntegerField(primary_key='true') token_no = models.CharField(max_length=20, unique='true') agent_name = models.CharField(max_length=20) trip_no = models.IntegerField() date = models.DateField() vehicle_no = models.CharField(max_length=10) bora = models.IntegerField() katta = models.IntegerField() plastic = models.IntegerField() farmer_name = models.CharField(max_length=30) farmer_address = models.CharField(max_length=40) farm_mob = models.CharField(max_length=10) gross_weight = models.IntegerField() tier_weight = models.IntegerField() net_weight = models.IntegerField() bora_weight = models.IntegerField() suddh_weight = models.FloatField() loading = models.IntegerField() unloading = models.IntegerField() unloading_point = models.CharField(max_length=20) dharamkanta_man = models.CharField(max_length=10) rate = models.IntegerField() bardana = models.CharField(max_length=7) gross_total = models.IntegerField() deduction = models.IntegerField() kanta = models.IntegerField() hemali = models.IntegerField() our_vehicle_rent = models.IntegerField() agent_commission = models.IntegerField() other_amt = models.IntegerField() other_remarks … -
How to send an image from React-Native app to the Django server using Expo ImagePicker?
const [image, setImage] = useState(null); const pickImage = async () => { // No permissions request is necessary for launching the image library let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, }); console.log(result.uri); if (!result.cancelled) { setImage(result); } }; I study React-Native and Django and I know about FormData, but I don't understand how put into my code. -
Conditional field in Django (Admin)
I've been using the Django ORM to model my database/objects, and Django Admin to render my admin pages (including nested admin pages). I've been meaning to implement the following, but without success: I have a 'project' model. Then I have 'file' model, with a ForeignKey relationship to 'project'. The file model has a 'filetype' field. SUPPORTED_FILE_TYPES = ( ('csv', 'csv'), ('xls', 'xls'), ) class Project(models.Model): name = models.CharField(max_length=200) class File(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) filetype = models.CharField( max_length=20, choices=SUPPORTED_FILE_TYPES, default=SUPPORTED_FILE_TYPES[0], ) Then in Django admin, I just nestedAdmin to make sure I can add files right from the project view. class FileInline(nested_admin.NestedStackedInline): model = File extra = 0 inlines = [ColumnInline] class ProjectAdmin(nested_admin.NestedModelAdmin): inlines = [FileInline] formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } Now a 'file' can be either a excel or a csv file. Each has different attributes (e.g. an excel file has 'sheets', whereas a csv has a 'delimiter' and 'thousand_seperator' fields). I want that, when I add a file and select which filetype it is, to have form fields appear that belong to the filetype I selected. I've been struggling with how to implement this. Several options crossed my mind: Using GenericForeignKeys, but I didn't manage to … -
TemplateDoesNotExist at / new.html
i'm trying to connect the html file with my views.py although everything seem correct but still after running the server it shows TemplateDoesNotExist kindly check my directories order and code i will appreciate your assistance. This is the folder order i couldnt paste it in image i dont know why views.url from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'new.html') -
When i create a user from admin page , i can't login
In django i am building a user db but i have a problem with this . When i try python3 manage.py createsuperuser this works fine but when i try creating user with admin page i can create user but user's password is not hashing and in login template i can't login . Django version 4.0 login views.py : def loginacc(request): if request.method == "POST": tcNo = request.POST.get("tcNo") password = request.POST.get("password") user = authenticate(request, tcNo=tcNo, password=password) if user is not None: login(request, user) return render(request, "home/home.html") else: return render(request, "accounts/accounts.html", {"error": "Name or password is wrong . "}) return render(request, 'accounts/accounts.html') student models.py : class Student(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) tcNo = models.IntegerField(unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) nickname = models.CharField(max_length=255, blank=True, null=True) objects = StudentBaseUserManager() USERNAME_FIELD = 'tcNo' REQUIRED_FIELDS = ['first_name', 'last_name', 'email', "nickname"] def save(self, *args, **kwargs): self.nickname = self.first_name + "-" + self.last_name return super(Student, self).save(*args, **kwargs) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def __str__(self): return self.email class StudentBaseUserManager(BaseUserManager): def create_user(self, tcNo, first_name, nickname, last_name, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, tcNo=tcNo, ) …