Database and Models present still programming error is coming in DJango - python

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)

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})

No module named 'ecommerce.store' in django

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

ImportError: cannot import name 'BaseContact'

I have a problem while running my Django code.
File "E:\sophienwald\amocrm\models.py", line 3, in <module>
from amocrm import BaseContact, amo_settings, fields, BaseLead
ImportError: cannot import name 'BaseContact'
But I noticed a strange feature... If I swap "BaseContact" and "BaseLead" it says that compiler can't import BaseLead. "fields" and "amo_setting" work fine.
Bit of code from amocrm\models.py:
import logging
from amocrm import BaseContact, amo_settings, fields, BaseLead
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils.functional import cached_property
from wagtail.admin.edit_handlers import MultiFieldPanel, FieldPanel
from wagtail.contrib.settings.models import BaseSetting
from wagtail.contrib.settings.registry import register_setting
logger = logging.getLogger(__name__)
#register_setting
class AmocrmSettings(BaseSetting):
PIPELINE_FIELDS = [
('stay_tuned_pipeline_name', 'stay_tuned_status_name'),
('new_posts_pipeline_name', 'new_posts_status_name'),
('back_call_pipeline_name', 'back_call_status_name'),
]
login = models.CharField('Логин', max_length=120, null=True, blank=True)
token = models.CharField('Токен', max_length=120, null=True, blank=True)
subdomain = models.CharField('Поддомен', max_length=120, null=True, blank=True)
run_async = models.BooleanField('Обновлять асинхронно', default=False)
# forms.StayTunedContact
stay_tuned_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True)
stay_tuned_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True)
# forms.NewPostsContact
new_posts_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True)
new_posts_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True)
# forms.BackCallContact
back_call_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True)
back_call_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True)
panels = [
MultiFieldPanel([
FieldPanel('login'),
FieldPanel('token'),
FieldPanel('subdomain'),
FieldPanel('run_async'),
], 'Авторизация'),
]
There is part of models.py with "BaseContact"
class Contact(BaseContact):
"""
Amocrm package contact model with custom fields
"""
phone = fields.EnumCustomField('Телефон', enum='WORK')
email = fields.EnumCustomField('Email', enum='WORK')
def __str__(self):
return f'name: {self.name}, phone: {self.phone}, email: {self.email}'

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))

Sequence in the django model access between model through foreign key to model how to fix my models?

I have such a problem that can be turned into a lesson, a hack, with models, and with url-routing, it turns out
Need to be sequenced, that is, by url
Series / serial_slug / season_slug / series_slug /
But to get access to the seasons of the series you need so
Series / serial_slug / season_slug /
It turns out I do not have access to the
series / serial_slug /
season_slug / no access to serial_slug in the Season model, since it is
important for jango that if any model needs access, then the model must
be on top of the requested momme, and thus access to There is no serial model, since it is below the season model, if they
are reversed, it will not work, although the idea should be like this:
In the "Serial" model there is a lot of seasonal that is "ManyToMany" to
the model "Season" that is the logical field there is a model Serial
from above, then there is the model Season, then comes the Series, but
it does not robit! In
the "Season" model there are a lot of series, that is, "ManyToMany" for
the Series model, and to get a consistent url, you need access to all
models, that is, the "Series" model has a season "ForeignKey" for the
"Season" model then The model "Season" has only 1 series again access through
"ForeignKey", if you do so, then it will not work, because, he needs to
have a model on top, to which the query is coming!
I think that this is a great idea for the Django series, namely the
sequence, the dependence of the models, and also the sequence in the
url, through reverse (), that is, the function get_absolute_url (), I
have the code on pastebin, | https://pastebin.com/RAJP6CNv | can you please see if I can throw The
link to my question in stackoverflow, there something explained, but it
did not help, maybe you'll understand, thanks for the lesson!
this is my main url.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^series/', include("serials.urls", namespace='series')),
url(r'^', include("serials.urls", namespace='homeview')),
]
this is my app urls.py
from django.conf.urls import include, url
from .views import homeview, post_of_serial, post_of_season, post_of_serie
urlpatterns = [
url(r'^$', homeview, name='homeview'), # /series/
url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), # /series/Prison_Break/
url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'), # /series/Prison_Break/season_5/
url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'), # /series/Prison_Break/season_5/2/
]
this is my models.py
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import datetime
class Status(models.Model):
name = models.CharField(max_length=120)
is_active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "|{0}| |{1}|".format(self.name, self.is_active)
class Meta:
ordering = ["-timestamp"]
verbose_name = 'Staus'
verbose_name_plural = 'Statuses'
class Season(models.Model):
id = models.AutoField(primary_key=True)
name_of_the_season = models.CharField(max_length=40)
slug = models.SlugField(unique=False, blank=True)
name_for_easy_access = models.CharField(max_length=40)
preview_of_season = models.ImageField(upload_to="previews/preview_for_season/", default=None,width_field="width_field", height_field="height_field")
width_field = models.IntegerField(default=150)
height_field = models.IntegerField(default=150)
number_of_released_series = models.IntegerField(default=0)
year = models.IntegerField(default=2017)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
is_active = models.BooleanField(default=True)
def get_absolute_url(self):
return reverse('series:post_of_season', kwargs=
{'serial_slug': self.serial.slug,
'season_slug': self.slug,
})
def __str__(self):
return "%s" % self.name_for_easy_access
class Meta:
ordering = ["-timestamp"]
verbose_name = 'Season'
verbose_name_plural = 'Seasons'
class Serial(models.Model):
id = models.AutoField(primary_key=True)
rus_name_of_seriall = models.CharField(max_length=40)
eng_name_of_seriall = models.CharField(max_length=40)
slug = models.SlugField(unique=False, blank=True)
number_of_serial = models.DecimalField(max_digits=10, decimal_places=2, default=True)
preview_of_serial = models.ImageField(upload_to="previews/preview_for_serials/", default=None,width_field="width_field", height_field="height_field")
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
seasonss = models.ManyToManyField(Season, default=None, blank=True)
timestamp = models.DateField(auto_now_add=True)
end_or_in_proccess = models.ForeignKey(Status, default=None)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
is_active = models.BooleanField(default=True)
def get_absolute_url(self):
return reverse('series:post_of_serial', kwargs={'serial_slug': self.slug})
def __str__(self):
return "%s" % self.rus_name_of_seriall
class Meta:
ordering = ["-timestamp"]
verbose_name = 'Serial'
verbose_name_plural = 'Serials'
class Series(models.Model):
id = models.AutoField(primary_key=True)
rus_name = models.CharField(max_length=60)
eng_name = models.CharField(max_length=60)
is_active = models.BooleanField(default=True)
serial_of_this_series = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True)
season_of_this_series = models.ForeignKey(Season, on_delete=models.CASCADE, default=True)
number_of_series = models.IntegerField(default=0, blank=True, null=True)
slug = models.SlugField(unique=False, blank=True)
description = models.TextField(max_length=700, blank=True, default=None)
rating = models.FloatField(default=0, blank=True)
timestamp_rus = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
timestamp_eng = models.CharField(max_length=60)
time_of_series = models.DecimalField(max_digits=10, decimal_places=2, default=0)
def get_absolute_url(self):
return reverse('series:post_of_serie', kwargs=
{'serial_slug': self.serial_of_this_series.slug,
'season_slug': self.season_of_this_series.slug,
'series_slug': self.slug})
def __str__(self):
return "%s | %s" % (self.rus_name, self.number_of_series)
class Meta:
ordering = ["-timestamp_rus"]
verbose_name = 'Series'
verbose_name_plural = 'Series'
You can fix these by putting string instead of class like
Change
models.ForeignKey(Serial)
to
models.ForeignKey("Serial")

Categories

Resources