Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
class 'product' has no 'objects' member
[enter image description here][1]models.py from django.db import models class customer(models.Model): name=models.CharField(max_length=200 ) phone=models.CharField(max_length=200 ) email= models.CharField(max_length=200 ) data_created = models.DateTimeField(auto_now_add=True) def _self_(self): return self.name class Tag(models.Model): name=models.CharField(max_length=200 ) def _self_(self): return self.name class product(models.Model): CATEGORY= ( ('Indoor','Indoor'), ('Out Door', 'Out Door'), ) name=models.CharField(max_length=200 , null=True) price = models.FloatField(null=True) category =models.CharField(max_length=200 , null=True, choices=CATEGORY) description =models.CharField(max_length=200 , null=True) date_created = models.DateTimeField(auto_now_add=True) tags= models.ManyToManyField(Tag) class order(models.Model): STATUS= ( ('Pending','Pending'), ('Out for delivery', 'Out for delivery'), ('Delivery','Delivery'), ) customer = models.ForeignKey(customer,null=True , on_delete= models.SET_NULL) product = models.ForeignKey(product, null=True , on_delete= models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status =models.CharField(max_length=200 , null=True, choices=STATUS) views.py from django.shortcuts import render from django.http import HttpResponse from .models import * def home(request): return render(request, 'dashboard.html') def products(request): products= product.objects.all() return render(request,'products.html',{'products':products}) def customer(request): return render(request, 'customer.html') THE ERROR Class 'product' has no 'objects' member pylint(no-member)[9,15]. function already defined line 3 pylint(function-redefined) [12,3] . -
How to display related objects through DetailView
I'm trying to display a product, and available brands(has product as ForeignKey) for that product through DetailView. Based on Django documentation and similar answers on stackoverflow, I tried below code but it doesn't work. Product details are rendering but names of brands are not. I've checked through django-admin, that the brands the products are present in the database. Could someone please help. Models.py class Product(models.Model): name = models.CharField(max_length=256) price = models.IntegerField() class Brand(models.Model): name = models.CharField(max_length=256) product = models.ForeignKey(Product,on_delete=models.PROTECT,related_name='Brands') Views.py class ProductDetailView(DetailView): model = Product Urls.py path('detail/<int:pk>/',views.ProductDetailView.as_view(),name='product_detail'), product_detail.html <table class="table table-bordered table-hover table-secondary"> <tr> <th class="bg-secondary th-customer-detail">Name</th> <td>{{ product.name }}</td> </tr> <tr> <th class="bg-secondary th-customer-detail">Price</th> <td>{{ product.price }}</td> </tr> </table> <br> <ul> {% for brand in product.brand_set.all %} <li>{{ brand.name }}</li> {% endfor %} </ul> -
Howto use django regular inheritance in models and forms
How to define helpers to the Class Event so I can integrate them to EventForm and use them in event_new(request). The 'helpers' should be used in forms, views, templates but not go into the database. It's about showing existing events and autogenerate new events due to various aspects models.py class Event_helper(object): number = models.PositiveSmallIntegerField() class Event(Event_helper, models.Model): event_date = models.DateTimeField(auto_now=False, null=True, blank=True) forms.py class EventForm(forms.Event): class Meta: model = Event fields = ('event_date', 'number') views.py def event_new(request): if request.method == "POST": form = EventForm(request.POST) if form.is_valid(): event = form.save(commit=False) ... generate events ... event.save() -
Django, inconsistent queryset ordering with pagination
I'm seeing inconsistent ordered result as below. foos = Foo.objects.some_filter().order_by('-bool_field', 'bar__user_id') # Foo has foreign key to Bar # Bar has foreign key to User # whole foos (printing id only) [12951, 12941, 12943, 12944, 12945, 12940, 12954, 12946, 12948, 12947, 12953, 12956, 12952, 12942, 12950, 12949, 12955, 11245, 11247, 10399, 10900, 11452, 11\ 455, 11453, 9230, 9344, 11463, 11462, 11495, 10717, 9164, 9159, 9391, 9901, 11456, 11454, 11450, 9191, 10870, 10545, 11240, 11685, 11683, 11681, 11697, 11699\ , 11702, 11703, 11704, 11713, 11714, 11715, 11716, 11717, 11718, 11720, 11721, 11695, 11693, 11692, 11690, 11689, 11688, 11687, 11686, 11751, 11754, 11752, 1\ 1696, 11694, 11744, 11753, 11755, 11745, 11705, 11698, 11691, 11684, 11682, 11748, 11423, 11749, 11750, 11722, 11723, 11700, 11719, 11701] page = self.paginate_queryset(foos). # DRF PageNumberPagination # first page (id only) [12949, 12950, 12955, 12951, 12943, 12940, 12944, 12941, 12945, 12942] Q1. why the first page is different from the 10 of the whole foos # second page [12943, 12955, 12940, 12949, 12944, 12951, 12941, 11245, 11247, 10399] Q2. furthere more 12949 is duplicated whereas whole foos don't have duplicaates Below is the same info, just in pdb session (Pdb) [e.id for e in self.object_list[bottom:top]] [e.id for e … -
Using a readymade Template for django frontend
I tried using a readymade HTML5 template for my Django Project and updated the static links and all but it fails to load the CSS and js and other static files too. My folder structure : MyProject apps templates MyProject static MyProject css js etc My Settings for static : STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] TEMPLATES = [ ...... 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR,'static') . ..... ] I have tried using the collectstatic command. Adding STATICFILES_DIRS. Adding this code snippet to urls.py Nothing's working. -
Django / I get a list of coins from api. If a coin is deleted, how can I delete it?
I get a list of coins from API. Sometimes coins are removed. How can I check if the coins are not in the API, do I also have to delete it? Thanks Here is my code now, without deletion. for coin in response: coin_name = coin['name'] coin_symbol = coin['symbol'] coin_crr = coin['crr'] obj, created = Coins.objects.update_or_create( symbol=coin_symbol, defaults={'name': coin_name, 'symbol': coin_symbol, 'crr': coin_crr}, ) -
How to make API for Waiter App and Chef App?
I am currently working with resturant management system in django and waiter as well as chef application in java. I am confusion about api cretaion. I want to make a order taking by assigned waiter and sending ordered item to the chef app. How to make API in django for all these functionalities? -
Django : Increase variable in the model
I have this model: class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) score_question_viewed = models.IntegerField(default=0) def increase_score_question_viewed(self): print("After: " + self.score_question_viewed) self.score_question_viewed += 10 print("Before: " + self.score_question_viewed) When I call increase_score_question_viewed() I see in my terminal: Before: 0 After: 10 But after, when I do profil.score_question_viewed I see 0 The value has not been saved... Do you know how can I save my value ? -
MultiValueDictKeyError at /update 'date'
I'm trying to update my database but I encountered MultiValueDictKeyError. The problem is triggered by 'date' as: t.date = request.POST.get('date') I tried print(request.POST) with the result: <QueryDict: {'csrfmiddlewaretoken': ['9mgfDaQRsH4Pv5rvglufS3wC61QDL5i9tcOqmBQwNFAKFpzE79h9wBY8St9CwBsB'], 'ID_number': ['4'], 'date_month': ['1'], 'date_day': ['1'], 'date_year': ['2020'], 'first_name': ['Gedo'], 'last_name': ['Prasad'], 'Membership_Start_date_month': ['1'], 'Membership_Start_date_day': ['1'], 'Membership_Start_date_year': ['2020'], 'Membership_End_date_month': ['4'], 'Membership_End_date_day': ['1'], 'Membership_End_date_year': ['2020'], 'member_type': ['Gym&Sauna'], 'payment_type': ['3 Month'], 'rate': ['23'], 'paid': ['20'], 'due': ['3'], 'Contact_number': ['1121212129'], 'Email': ['gedo@pzrasad.com'], 'Remarks': ['gsa']}> Notice that the date field gives 'date_month', 'date_day', 'date_year' separately. Maybe that's the problem. But I don't know the answer. Any suggestions would be very helpful as I am a student and a beginner. Here is my models.py: class Member(models.Model): ID_number = models.IntegerField() date = models.DateField(verbose_name='date') first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) member_type = models.CharField( max_length=30, choices=MEMBERSHIP_CHOICES, ) payment_type = models.CharField( max_length=30, choices=PAYMENT_TYPE_CHOICES, ) Membership_Start_date = models.DateField(verbose_name='Membership_Start_date') Membership_End_date = models.DateField(verbose_name='Membership_End_date') rate = models.IntegerField() paid = models.IntegerField() due = models.IntegerField() Contact_number = models.CharField(max_length=14) Email = models.EmailField() Remarks = models.CharField(max_length=255, blank = True, null = True) def __str__(self): return str(self.ID_number) + " " + self.first_name + " " + self.last_name -
ImportError: cannt import name Httpresponse in django
demo.py from django.http import Httpresponse def index(request) : return Httpresponse("Hello") I am checking HttpResponse, HTTPResponse instead of Httpresponse.. but couldn't slove the problem..i am new in python so please tell me what's wrong in that.. Thank You in advance! -
TabError inconsistent use of tabs and spaces in indentation
views.py from django.shortcuts import render from django.http import HttpResponse from .models import * def home(request): return render(request, 'dashboard.html') def products(request): products=product.objects.all() return render(request,'products.html', {'products':products}) def customer(request): return render(request, 'customer.html') The error: from . import views File "/Users/dileepkumar/Desktop/dj/accounts/views.py", line 12 return render(request,'products.html', {'products':products}) ^ TabError: inconsistent use of tabs and spaces in indentation -
ModuleNotFoundError: No module named 'MyProject'
I'm collaborating with a group for an assignment we decided to use Django for, however, it seems that if one individual used upercase characters instead of lowercase characters (MyProject vs myproject) for example and therefore I often times get an error indicating ModuleNotFoundError: No module named 'MyProject' I've changed it before & resolved it and then pushed it up to GitHub.. but every so often we encounter the same issue. How can I fix this permanently so that it's no longer an issue? -
How to use CSS on the Django ModelForms?
I'm developing a small app and using Django ModelForms. I'm unable to provide any kind of styling to the form. Can someone tell me if there is a way to customize this form? My current form display My current template {% extends 'base.html' %} {% block content %} <!--begin::Portlet--> <div class="kt-portlet"> <div class="kt-portlet__head"> <div class="kt-portlet__head-label"> <h3 class="kt-portlet__head-title"> New Customer </h3> </div> </div> <!--begin::Form--> <form class="kt-form"> <div class="kt-portlet__body"> <div class="form-group"> {{ form }} </div> </div> <div class="kt-portlet__foot"> <div class="kt-form__actions"> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-secondary">Cancel</button> </div> </div> </form> <!--end::Form--> </div> <!--end::Portlet--> <h2>New Customer</h2> <form method="POST" class="kt-form">{% csrf_token %} {{ form }} <button type="submit" class="save btn btn-default">Add Customer</button> </form> {% endblock %} -
OperationalError at /admin/accounts/userstripe/ no such table: accounts_userstripe, why is it throwing an error even after migrations?
I'm trying to develop a website for an online store, and after creating and registering models, I don't know why, this error is thrown. What can I do? And also after running the migrate command, it is saying no migrations to apply. Can anyone please help me with this? My models.py: from django.db import models import stripe from django.conf import settings from django.contrib.auth.signals import user_logged_in stripe.api_key = settings.STRIPE_SECRET_KEY class UserStripe(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_id = models.CharField(max_length=120) def __unicode__(self): return str(self.stripe_id) def get_or_create_stripe(sender, user, *args, **kwargs): try: user.userstripe.stripe_id except UserStripe.DoesNotExist: customer = stripe.Customer.create( email = str(user.email) ) new_user_stripe = UserStripe.objects.create( user = user, stripe_id = customer.id ) except: pass user_logged_in.connect(get_or_create_stripe) -
FlowRuntimeError viewflow django
Really need you guys help here! Im currently using viewflow to construct my workflow on a django project. I wish to integrate django-jsignature3 with django-viewflow , however i have met with extreme difficulty in doing so. The documentations for viewflow is really confusing and the demo projects dont really have explanations so please be patient with me if what im asking is a dumb question. The error code is as shown below FlowRuntimeError Here is the error trace back on my cmd: raise FlowRuntimeError('Activation metadata is broken {}'.format(self.management_form.errors)) viewflow.exceptions.FlowRuntimeError: Activation metadata is broken <ul class="errorlist"><li>started<ul class="errorlist"><li>This field is required.</li></ul></li></ul> [04/Apr/2020 20:24:48] "POST /pipeline/20/approve1/57/ HTTP/1.1" 500 103532 Here is my code: flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess start = flow.Start( CreateProcessView ).Permission( auto_create=True ).Next(this.approve1) approve1 = flow.View( PreparerSignature, ).Next(this.check_approve1) check_approve1 = flow.If( cond=lambda act: act.process.approved_preparer ).Then(this.approve2).Else(this.end) approve2 = flow.View( VerifierSignature, ).Next(this.check_approve2) check_approve2 = flow.If( cond=lambda act: act.process.approved_verifier ).Then(this.delivery).Else(this.end) delivery = flow.View( UpdateProcessView, form_class=DropStatusForm ).Permission( auto_create=True ).Next(this.report) report = flow.View( UpdateProcessView, fields=["remarks"] ).Next(this.end) end = flow.End() views.py @flow_view def PreparerSignature(request, **kwargs): #this prepare statement might be the cause of the error request.activation.prepare(request.POST or None, user=request.user) form = PreparerSignatureForm(request.POST or None) if form.is_valid(): esig = form.save(commit=False) signature = form.cleaned_data.get('signature') if signature: signature_picture = … -
Django: How to generate weeks of month (starting from first day of month to next friday), then from saturday to next friday till the month ends?
I am working on a Django Project, which consists of forecasting the coming Accounts Payable (AP) and Accounts Receivable (AR). However, I stumbled across a problem as I do not know how to generate the weeks of a particular month. For example, for the month of April, I would like the dates to be split into: 01/04/20 - 10/04/20 (next friday), 11/04/20 - 17/04/20 (the friday after that) and so on and so forth. Within each week, a field 'amount' would be added up to show the total amount expected to pay/receive during that week. Here is my code thus far, and I managed to group the query sets by months, and the 'amount' field by months. However, I am not too sure how to group it by weeks of a month, as Django's ExtractWeek function works on a per-year basis. views.py class APView(LoginRequiredMixin,CreateView): model = AP form_class = APForm template_name = 'cash/ap.html' def get_context_data(self, **kwargs): context = super(APView, self).get_context_data(**kwargs) time_range = [] done = False time = self.kwargs['time'] start = int(self.kwargs['start']) end = int(self.kwargs['end']) context['bp'] = BusinessPartners.objects.prefetch_related('ap_set').all() context['ap'] = BusinessPartners.objects.annotate(timeline=Extract('ap__due_date', time)).values('timeline').annotate(total=Sum('ap__amount')).values('timeline','total', 'bp_name') while not done: time_range.append(start) if start == end: done = True break start += 1 context['timeline'] = … -
Is there any other better method for Overriding Model Serializer Update Method
I am created a model Serializer and overriding the methods .But in this case I need to save each serializer object one by one .... I am checking is there any other methods class PetSerializer(ModelSerializer): class Meta: model = Pet exclude = ['name', 'categoty','color','food'] def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.categoty = validated_data.get('categoty', instance.categoty) instance.color = validated_data.get('color', instance.color) instance.food = validated_data.get('food', instance.food) instance.save() In this case If I am having 10 fields I need to save one by one right ? Is there any other better way to handle this ? -
why i get error when i want to load html file in js in django project?
I want to load HTML file in Js file in django,but i get this error: Not Found: /login.html there is this file in templates folder! $(document).ready(function () { $('#load_').load('login.html') }); -
NameError at /register/ name 'cleaned_data' is not defined
I am developing a register form for my site and when I fill in the form I receive the error "NameError at /register/ name 'cleaned_data' is not defined" this is what I have: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2' ) def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
Not sure how to execute complex Query with Django
I'm stuck on a query I'm trying to execute. I have attached an image of the datamodel below. Essentally, I got 6 tables with various relations. Here's a quick summary: One User can have many Projects, and each Expense is tied to a specific project Each project can have many users, and each user can have many projects, put together through a joined table - UserProject To indicate the level of access a user has to a specific project, a field called role is added to the UserProject table - a user can either be a member or an admin of a project The query I wish to construct is to fetch all expenses that are created by the logged in user (request.user) and all expenses of all projects where the user has the role of admin from the UserProject table. See image of data model below: Any idea how I would proceed with that query? -
Is it possible in Django to call custom `QuerySet` method on reverse related object lookup?
E.g. there are next models and custom QuerySet: from django.db import models class ActiveQuerySet(models.QuerySet): def active(self): '''returns only active objects''' '''supposing here would be a lot of more complicated code that would be great to reuse ''' return self.filter(is_active=True) class Category(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True) is_active = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, related_name='products', related_query_name="product", blank=True, null=True, default=None) objects = ActiveQuerySet.as_manager() Could you tell me if there is a way to call the active() method like this: category = Category.objects.first() category.products.active() instead of doing like this: category.products.filter(is_active=True) Or how to implement appropriately such behavior? -
How to fetch total selected radio buttons in Django?
{% csrf_token %} {% for field in all %} {{field.ques}}<br> <input type="radio" name="field{{field.id}}">{{field.option1}}<br> <input type="radio" name="field{{field.id}}">{{field.option2}}<br> <input type="radio" name="field{{field.id}}">{{field.option3}}<br> <input type="radio" name="field{{field.id}}">{{field.option4}}<br> <br> {% endfor %} Here is my views.py if request.method=='POST': for field in range(len(correctOption)): selected.append(request.POST.get(????)) I am storing all selected options in a list, what should i write in request.POST.get() -
How do i implement a movie Recommender?
First of all I apologize if posting such thing is against the rules here, but I did a Google research, and actually did lots of it, however couldn't get the answer I wanted and wouldn't know where to post it. I want to create a recommender system in the form of an online application, similar to this, I even bought the Practical Recommender Systems book by Kim Falk which goes along the GitHub repo. however, I just couldn't get it working. I tried implementing my own solution using Django, however even the slightest computationally intensive tasks slowed the web application to a crawl! To be honest I am confused, and I want someone to steer me in the right direction. Is Django a good option for the application framework?Which Movie Dataset should I use? MovieLens 100K? Or MovieTweetings 100K? I currently structure my app in the following way: project_name (My top level project directory) movies_app (An app that handles the Movie model, and views for homepage + movies catalog + movie details page) accounts_app (An app that handles the custom User model, and views for profile management + register + login) recommender_app (An app that handles all of the recommendation … -
Hello everybody, how can I easily remove an information from a url
my users will be redirected to my site with some information like this http://127.0.0.1:8000/accounts/dasbboard/?trxref=621538940cbc9865e63ec43857ed0f&reference=621538940cbc9865e63ec43857ed0f using urllib will get give me query='trxref=621538940cbc9865e63ec43857ed0f&reference=621538940cbc9865e63ec43857ed0f' But I'm no okay with that, I want to be able to get the number after the reference(621538940cbc9865e63ec43857ed0f), what is the best way to do it in my view? thank you in advance. -
Docker and POSTGRESQL
I create new project using Docker on Django. when I write settings to connect to Postgres it has some Error - (conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known) Thats my code in project : settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 environment: POSTGRES_DB: "db" POSTGRES_HOST_AUTH_METHOD: "trust" and Dockerfile: # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ RUN pip install psycopg2-binary Please help to decide this problem.I read a lot information on stackoverflow about it.Changed code.But nothing to help me in this situation.