No module named 'ecommerce.store' in django - python

I run command python3 manage.py runserver It throws an error showing that no module named ecommerce.store but it is.
This is my ecommerce.store.views file
from ecommerce.store.models import Product
from django.shortcuts import render
from .models import *
def store(request):
products = Product.objects.all()
context = {'products':products}
return render(request, 'store/store.html', context)
def cart(request):
context = {}
return render(request, 'store/cart.html', context)
def checkout(request):
context = {}
return render(request, 'store/checkout.html', context)
This is my ecommerce.store.admin file
from django.contrib import admin
from .models import *
admin.site.register(Customer)
admin.site.register(Product)
admin.site.register(Order)
admin.site.register(OrderItem)
admin.site.register(ShippingAddress)
This is my ecommerce.store.models file
from django.db import models
from django.contrib.auth.models import User
from django.db.models.fields.related import ForeignKey
class Customer(models.Model) :
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
def __str__(self) :
return self.name
class Product(models.Model) :
name = models.CharField(max_length=200, null=True)
price = models.FloatField()
digital = models.BooleanField(default=False, null=True, blank=True)
def __str__(self) :
return self.name
class Order(models.Model) :
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=True)
transaction_id = models.CharField(max_length=200, null=True)
def __str__(self) :
return str(self.id)
class OrderItem(models.Model) :
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0, blank=True, null=True)
date_added = models.DateTimeField(auto_now_add=True)
class ShippingAddress(models.Model) :
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
zipcode = models.CharField(max_length=200, null=False)
date_added = models.DateTimeField(auto_now_add=True)
def __str_(self):
return self.address
This is my ecommerce.store.urls file
from django.urls import path
from . import views
urlpatterns = [
path('', views.store, name="store"),
path('cart/', views.cart, name="cart"),
path('checkout/', views.checkout, name="checkout"),
]
This is the image of the actual error showing in terminal please help me
enter image description here
Thanks for helping me

from ecommerce.store.models import Product will find package ecommerce from project root dir, this will find the subdirectory ecommerce not root directory ecommerce, you can use absolute import:
from store.models import Product
or just use relative import(recommended way):
from .models import Product

try change your wrong import:
from ecommerce.models import Product

I had a similar issue, found out that I did not import the forms into views.py header file.
Check to make sure that this has been imported

Related

Product detail and images in django problem

I'm trying to create a simple car dealership app and i'm stuck. I have searched days and i have tried so many times to fix this but i can't. What i'm doing wrong i don't know and my brain is not working anymore. Thanks for help.
Error:
NoReverseMatch at /
Reverse for 'car_detail' with keyword arguments '{'slug': '2021-ram-1500-trx-crew-cab-4x4-57-box'}' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)$']
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.2.8
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'car_detail' with keyword arguments '{'slug': '2021-ram-1500-trx-crew-cab-4x4-57-box'}' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)$']
Exception Location: C:\Users*\Desktop\Testdealer\envdealer\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable: C:\Users*\Desktop\Testdealer\envdealer\Scripts\python.exe
Python Version: 3.9.7
Models.py:
from django.db import models
import datetime
from django.urls import reverse
class Car(models.Model):
brand = models.CharField(max_length=100)
CATEGORY = (
('New', 'New'),
('Used', 'Used')
)
slug = models.SlugField(max_length=200, null=True, unique=True)
category = models.CharField(max_length=50, choices=CATEGORY)
image_main = models.ImageField(upload_to='images')
body_style = models.CharField(max_length=100, blank=True)
engine = models.CharField(max_length=100, blank=True)
stock_number = models.IntegerField(blank=True, null=True)
mpg = models.CharField(max_length=100, blank=True)
exterior_color = models.CharField(max_length=100, blank=True)
interior_color = models.CharField(max_length=100, blank=True)
drivetrain = models.CharField(max_length=100, blank=True)
mileage = models.IntegerField(blank=True, null=True)
sold = models.BooleanField(default=False, blank=False)
transmission = models.CharField(max_length=50, blank=True)
YEAR_CHOICES = [(r, r) for r in range(1940, datetime.date.today().year+1)]
year = models.IntegerField(
('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
power = models.IntegerField()
fuel = models.CharField(max_length=50, blank=True)
price = models.CharField(max_length=10, blank=True)
description = models.TextField()
date = models.DateField()
def __str__(self):
return self.brand
def get_absolute_url(self):
return reverse('car_detail', kwargs={'slug': self.slug})
# def get_absolute_url(self):
# return reverse('car_detail', kwargs={
# 'car_id': self.id
# })
class CarImage(models.Model):
"""
The Product Image table.
"""
name = models.CharField(max_length=200, blank=True)
car = models.ForeignKey(
Car, on_delete=models.CASCADE, related_name="car_image")
image = models.ImageField(
verbose_name="image",
help_text="Upload a product image",
upload_to="images/",
default="images/default.png",
)
alt_text = models.CharField(
verbose_name="Alturnative text",
help_text="Please add alturnative text",
max_length=255,
null=True,
blank=True,
)
class Meta:
verbose_name = "Car Image"
verbose_name_plural = "Car Images"
def __str__(self):
return self.name
Views.py:
from django.shortcuts import render, get_object_or_404
from .models import Car, Dealer, CarImage
from django.core.mail import send_mail
def car_detail(request, id, slug):
cars = Car.objects.get(pk=id)
images = CarImage.objects.filter(car_id=id)
context = {'cars': cars, 'images': images}
return render(request, 'car_detail.html', context)
Urls.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from cars import views
..........
path('<int:id>/<slug:slug>', views.car_detail, name="car_detail"),
The .get_absolute_url() [Django-doc] of the Car model only specifies the slug, not the id parameter:
class Car(models.Model):
# &vellip;
def get_absolute_url(self):
# add id to the context &downarrow;
return reverse('car_detail', kwargs={'id': self.pk, 'slug': self.slug})

TypeError: __str__ returned non-string (type NoneType). Not sure how to solve this

[![Nurse admin page[![][1]][1][models.py
from django.db import models
#Work Related aka Department and Work Shift
class Department(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class WorkShift(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
start_datetime = models.DateTimeField(null=True, blank=True)
end_datetime = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.name
#Personel Related aka Employees and Patients
class Doctor(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Nurse(models.Model):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
reports_to = models.OneToOneField(Doctor, default="", blank=True, null=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return str(name)
class Patient(models.Model):
STATUS = (
('Sick', 'Sick'),
('Healing', 'Healing'),
('Cured', 'Cured'),
('Deceased', 'Deceased'),
)
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(blank=True, null=True)
status = models.CharField(max_length=200, null=True, blank=True, choices=STATUS)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
care = models.ForeignKey(Nurse, default="", blank=True, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .models import Doctor, Nurse, Patient
from django.http import HttpResponse
# Create your views here.
def index(request):
patient = Patient.objects.all()
nurse = Nurse.objects.all()
doctor = Doctor.objects.all()
total_patient = patient.count()
sick = patient.filter(status='Sick').count()
healing = patient.filter(status='Healing').count()
cured = patient.filter(status='Cured').count()
total_nurse = nurse.count()
# if request.method == 'POST':
# form =
context = {
'patient':patient, 'nurse':nurse,
'doctor':doctor, 'total_patient':total_patient,
'sick':sick, 'healing':healing, 'cured':cured,
'total_nurse':total_nurse
}
return render(request, 'lifesaver/index.html', context)
def patient(request):
patient = Patient.objects.all()
total_patient = patient.count()
context = {
'patient':patient,
'total_patient':total_patient
}
return render(request, 'lifesaver/patient.html', context)][1]
forms.py
from django import forms
from .models import Doctor, Nurse, Patient
from django.auth.contrib.forms import UserCreationForm
class DoctorForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Doctor',
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=department.objects.all)
class NurseForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
class PatientForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Patient'
'class': 'form-control'
}))
HTML for patient
{% extends 'lifesaver/main.html' %}
{% block content %}
<h1>SUPERSTAR</h1>
{% for patient in patient %}
{{patient.name}}
{% endfor %}
{% endblock content %}
I get this error when I go to try to add another Nurse. The URL is http://127.0.0.1:8000/admin/lifesaver/nurse/add/. Everything else behaves as expected, except the adding the Nurse part.
If I try to remove the def __str___ part, the error still displays. I believe the error lies in the:
work_shift = models.OneToOneField(WorkShift, default="",
blank=True,
null=True,
on_delete=models.CASCADE)
part since when I included that code, the error spawned. Furthermore, the code is to add a work shift to certain employees and the goal is that the employees shift will display in their profile.
How do I fix this issue?
EDIT: When accessing the HTML template, the web page behaves as expected and has no issues.
In your Nurse model replace this:
def __str__(self):
return str(Nurse.name)
with this:
def __str__(self):
return self.name

Django Many to Many Field add() got an unexpected keyword argument 'id'

I want to add items from Available classic to Chosen classic
how can i do that as in image below
i can get Chosen classic by
Profile.objects.get(user=request.user).classic.add(id=2)
but i can't add iems from Available classic to Chosen classic
any one can help this problem fast please
Thanks for all
Models.py
from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Language(models.Model):
language = models.CharField(
max_length=2,
choices=[
('AR', 'Arabic'),
('EN', 'English'),
],
default='AR'
)
def __str__(self):
return self.language
class Classic(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
classic = models.ManyToManyField(Classic, blank=True, null=True)
workOut = models.ManyToManyField(WorkOut, blank=True, null=True)
chillOut = models.ManyToManyField(ChillOut, blank=True, null=True)
romantic = models.ManyToManyField(Romantic, blank=True, null=True)
happy = models.ManyToManyField(Happy, blank=True, null=True)
sad = models.ManyToManyField(Sad, blank=True, null=True)
lang = models.ManyToManyField(Language, blank=True, null=True)
def __str__(self):
return str(self.user)
def update_user_profile(sender, **kwargs):
if kwargs['created']:
user = Profile.objects.create(user=kwargs['instance'])
post_save.connect(update_user_profile,sender=User)
Admin.py
from django.contrib import admin
# Register your models here.
from . import models
class ClassicAdmin(admin.TabularInline):
model = models.Classic
class PlayLists(admin.ModelAdmin):
inlines = [ClassicAdmin]
class Favo(admin.ModelAdmin):
filter_horizontal = ['classic']
admin.site.register(models.Language, PlayLists)
admin.site.register(models.Profile, Favo)
what's wrong with in my code
thank for all
Thant's works with me
Profile.objects.get(user=request.user).classic.add(Classic.objects.get(id=1))

Subquery returns more than 1 row in Django while connecting models

I want to get authorName whenever someone search for a book and yeah I have tried many to many but it is very confusing and after researching some things I got to a view which I thought should work fine but it is returning an error "1242, 'Subquery returns more than 1 row'" here are some of the relevant code:
Models
from __future__ import unicode_literals
from django.db import models
class Books(models.Model):
bid = models.BigIntegerField(primary_key=True)
bname = models.CharField(max_length=200, blank=True, null=True)
bdescription = models.TextField(blank=True, null=True)
def __str__(self):
return self.bname
class Authors(models.Model):
aid = models.AutoField(primary_key=True)
aname = models.CharField(max_length=200, blank=True, null=True)
adescription = models.TextField( blank=True, null=True)
def __str__(self):
return self.aname+"\n"
class Bookauth(models.Model):
bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True)
aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True)
Views for what I thought was right
def authbook(request):
s = Authors.objects.all()
r = Books.objects.filter(bookauth__aid = s).values()
return HttpResponse(r)

Database and Models present still programming error is coming in DJango

I am trying to get the models data on the browser using the urls.py and views.py for last 3 days and failing miserably, although I am able to get the database in a json file but not on browser. This is the error log [http://dpaste.com/2DQZX1Z][1] and the code is here
models.py
from __future__ import unicode_literals
from django.db import models
class Authors(models.Model):
aid = models.AutoField(primary_key=True)
aname = models.CharField(max_length=200, blank=True, null=True)
adescription = models.CharField(max_length=8000, blank=True, null=True)
class Books(models.Model):
bid = models.IntegerField(primary_key=True)
bname = models.CharField(max_length=200, blank=True, null=True)
bdescription = models.CharField(max_length=8000, blank=True, null=True)
class Bookauth(models.Model):
bid = models.ForeignKey(Books, models.DO_NOTHING, db_column='bid', blank=True, null=True)
aid = models.ForeignKey(Authors, models.DO_NOTHING, db_column='aid', blank=True, null=True)
views.py
from __future__ import unicode_literals
from django.shortcuts import render
import requests
from django.http import HttpResponse
from django.db import models
from .models import Books
import json
from django.core import serializers
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def getObject(request):
all_books = Books.objects.all()
html = serializers.serialize('json', all_books)
return HttpResponse(html)
#data = serializers.serialize("json", Books.objects.all())
#return HttpResponse(data, mimetype='application/json')
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^non', views.index, name = 'index'),
url(r'^auth', views.author_search, name = 'AuthSearch'),
url(r'^book', views.getObject, name = 'Books')
]
change your models to this and then makemigrations then migrate and then check in the browser
from __future__ import unicode_literals
from django.db import models
class Authors(models.Model):
aid = models.AutoField(primary_key=True)
aname = models.CharField(max_length=200, blank=True, null=True)
adescription = models.TextField( blank=True, null=True)
class Books(models.Model):
bid = models.IntegerField(primary_key=True)
bname = models.CharField(max_length=200, blank=True, null=True)
bdescription = models.TextField(blank=True, null=True)
class Bookauth(models.Model):
bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True)
aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True)

Categories

Resources