Django can't import module due to a circular import - python

Following a tutorial and am have the module
views.py file
#attempt2/src/products/views.py
from django.shortcuts import render
from .forms import ProductForm, RawProductForm
from .models import Product
def product_create_view(request):
#this creates an instance of that form
my_form = RawProductForm()
context = {
"form": my_form
}
return render(request, "product/product_create.html", context)
But I get the following error
File "C:\Users\dancc\dev2\attempt2\src\products\views.py", line 2, in <module>
from .forms import ProductForm, RawProductForm
File "C:\Users\dancc\dev2\attempt2\src\products\forms.py", line 4, in <module>
from products.views import product_create_view
ImportError: cannot import name 'product_create_view' from partially initialized module 'products.views' (most likely due to a circular import) (C:\Users\dancc\dev2\attempt2\src\products\views.py)
I've tried searching to see where it might be importing a different product_create_view but there is not another one, none of the files or folders' names repeat
this is forms.py
#attempt2/src/products/forms.py
from django import forms
from products.views import product_create_view
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
'title',
'description',
'price'
]
#This is what product_create_view is using
class RawProductForm(forms.Form):
title = forms.CharField()
description = forms.CharField()
price = forms.DecimalField()
This is models.py file
#attempt2/src/products/models.py
from django.db import models
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120) #max_length required
description = models.TextField(blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=10000)
summary = models.TextField()
This is views.py file
#attempt2/src/products/views.py
from django.shortcuts import render
from .forms import ProductForm, RawProductForm
from .models import Product
...
def product_create_view(request):
#this creates an instance of that form
my_form = RawProductForm()
context = {
'form': my_form
}
return render(request, "product/product_create.html", context)
Here are the folders

You are importing the product_create_view from the products.views module, but in your forms.py, you do not use that function. Since the products.forms module imports the products.views module, and vice versa, this creates a cycle when importing one of the two.
You can remove the from products.views import product_create_view line from the forms.py file, and thus simply let the view use the forms you defined, not in the opposite direction.

Related

Django serializer returns empty list

I have a class-based view that returns all the data in the table. But while accessing the URL all I get is an empty list.
models.py
from django.db import models
class EmployeeModel(models.Model):
EmpID = models.IntegerField(primary_key=True)
EmpName = models.CharField(max_length=100)
Email = models.CharField(max_length=100)
Salary = models.FloatField()
class Meta:
verbose_name = 'employeetable'
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import EmployeeModel
from .serializers import EmployeeSerialize
class EmployeeTable(APIView):
def get(self,request):
emp_obj = EmployeeModel.objects.all()
empserializer = EmployeeSerialize(emp_obj,many=True)
return Response(empserializer.data)
serializers.py
from rest_framework import serializers
from .models import EmployeeModel
class EmployeeSerialize(serializers.ModelSerializer):
class Meta:
model = EmployeeModel
fields = '__all__'
urls.py
from django.contrib import admin
from django.urls import path, include
from .views import EmployeeTable, transformer_list
urlpatterns = [
path('display/',EmployeeTable.as_view()),
]
The table has 5 rows. It is not empty.
I want to serialize all 5 rows
I have also created the same but in my case, it worked see the below images
See my serializer
See my models below
and my output is here below
I think there are some issue at your code or some mistake can be there can you please provide full information

Django : HttpRequest.__init__() takes 1 positional argument but 2 were given

So I simply want when I click on the particular article to output its slug, for example if the slug of the given article is django-rules then i want it to be outputted as django-rules when i click on it. just that
here is my model
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add = True)
#add in tubnail and author later
def __str__(self):
return self.title
def snippet(self):
return self.body[:50]+'...'
Here is my views.py
from datetime import date
from django.shortcuts import render
from .models import Article
from django.http import HttpRequest
# Create your views here.
def article_list(request):
articles = Article.objects.all().order_by('date')
return render(request,'articles/article_list.html', {'articles': articles} )
def article_detail(request, slug):
return HttpRequest(slug)
url.py
from posixpath import relpath
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.article_list, name = 'list'),
path('<slug:slug>/', views.article_detail, name = 'detail'),
]
Please dont suggest to add as_view()
its not working.
Instead of return HttpRequest(slug), you need to return HttpResponse(slug).

I have a python django app that was working fine until Pylance was automatically installed. Now I get an error: Exception has occurred:

My code is:
from django.shortcuts import render # Create your views here.
from django.views.generic import ListView # <- new
from .models import Post
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
And the error I receive is
from .models import Post
Exception has occurred: ImportError
attempted relative import with no known parent package
Post is defined in:
from django.db import models # Create your model fields here.
from django.utils import timezone # for the DateTimeZone field below
from django.contrib.auth.models import User # the author field below needs this
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField() # TextField has no length limitation
date_posted = models.DateTimeField(default=timezone.now) # Use the django timezone
author = models.ForeignKey(User, on_delete=models.CASCADE) # if the User is deleted, so will this model
def __str__(self):
return self.title
Any help would be appreciated.

Django how to get one result using slicing queryset

I have to fetch the usernames of my authors' posts
Here the views.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .forms import CreateUserForm
from .models import Post
from .forms import PostForm
def counter(request):
authors = Post.objects.values_list('author', 'title')
authors_id = Post.objects.values_list('author')
authors_name = User.objects.get(id=authors_id)
context = {'authors':authors, 'authors_name':authors_name}
return render(request, 'account/counter.html', {'authors': authors})
My models.py is:
from django.db import models
from django.conf import settings
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
And here my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import Post
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined']
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'text', 'author']
Now the problem is that on 'authors_id' I have this Error: The QuerySet value for an exact lookup must be limited to one result using slicing, or if i get just one result value of the list the answer's error is: Field 'id' expected a number but got (3,).
So because it takes also the comma from 'values_list'.
I've to got back each author's post and the title of each post the author wrote.
How can I slice the queryset's list?
try this
authors_id = Post.objects.values_list('author', flat=True)
authors_name = User.objects.get(id__in=authors_id)
or
authors_id = Post.objects.values_list('author', flat=True)[0]
authors_name = User.objects.get(id=authors_id)
Refer this https://docs.djangoproject.com/en/3.1/topics/db/queries/#the-pk-lookup-shortcut

SyntaxError: invalid syntax when trying migrate

models.py
from django.db import models
class User(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField(max_length=256, unique=True)
views.py
from django.shortcuts import render
form appTwo.moldels import User
# Create your views here.
def index(request):
return render(request, 'appTwo/index.html')
def users(request):
user_list = User.object.order_by('first_name')
user_dict = {'users':user_list}
return render(request, 'appTwo/users.html', context=user_dict)
protwo/urls.py
appTwo/urls.py
from django.conf.urls import path
from appTwo import views
urlpatterns = [
path('', views.users, name='users'),
]
I've tried migrating but it causes a syntax error. The stack trace is included below:
File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/proTwo/urls.py", line 18, in <module>
from appTwo import views
File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/appTwo/views.py", line 2
form appTwo.moldels import User
^
SyntaxError: invalid syntax
(myDjango) hamid#hamid-PC:~/Desktop/my_django_stuff/project_two/proTwo$
You misspelled models:
form appTwo.moldels import User
to
form appTwo.models import User
Other than the typo in "moldels" pointed out by FBSO, there is also another in the same line in "form", it should be "from":
from appTwo.models import User

Categories

Resources