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
Related
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).
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.
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.
I'm very new to Django but I started to create a project and I need some help. My question is very basic but I can't find the right answer.
I made a questionnaire that works fine but I don't know how to do that if a logged in user adds his answers Django associate the answers to the user.
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template import loader
from .models import Stressz_teszt
from .forms import StresszForm
from django.forms import ModelForm
def stressz_item(request):
form = StresszForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('stressz/login.html')
return render(request, 'stressz/stressz-form.html', {'form':form})
Urls.py
from . import views
from django.urls import path
from django.forms import ModelForm
urlpatterns = [
path('', views.index, name='index'),
path('login/', views.login, name='login'),
#stressz teszt form
path('add', views.stressz_item, name='stressz_item'),
path('<int:item_id>/', views.detail, name='detail'),
Forms.py
from django import forms
from django.forms import ModelForm
from .models import Stressz_teszt
class StresszForm(forms.ModelForm):
class Meta:
model = Stressz_teszt
fields = ['stressz_v01', 'stressz_v02', 'stressz_v03', 'stressz_v04', 'stressz_v05',] ...
Models.py
from django.db import models
from django.contrib.auth.models import User
class Stressz_teszt(models.Model):
def __str__(self):
return self.stressz_name
user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
stressz_name = models.CharField(max_length=200)
stressz_company = models.CharField(max_length=300)
stressz_v01 = models.IntegerField()
stressz_v02 = models.IntegerField()
stressz_v03 = models.IntegerField()
stressz_v04 = models.IntegerField()
stressz_v05 = models.IntegerField()
...
Thank you in advance!
You can do it like this :
def stressz_item(request):
if form.is_valid():
stressz_teszt = form.save(commit=False)
stressz_teszt.user_name = request.user
stressz_teszt.save()
return redirect('stressz/login.html')
return render(request, 'stressz/stressz-form.html', {'form': form})
I am learning to develop and trying to develop a screen in django 1.1 and I am getting this error below. I already took a look at some stacks I already looked at httpresponse, however, I was not successful
could someone help me and explain what could be wrong?
I'm getting this error on the console:
Internal Server Error: /gerencia-margem/list
Traceback (most recent call last):
File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response
response = middleware_method(request, response)
File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/middleware/locale.py", line 38, in process_response
if (response.status_code == 404 and not language_from_path and
AttributeError: 'HistoricoComissao' object has no attribute 'status_code'
[18/Nov/2020 13:30:06] "GET /gerencia-margem/list HTTP/1.1" 500 77145
This is models,
# -*- coding: utf-8 -*-
from django.db import models
class HistoricoComissao(models.Model):
class Meta:
verbose_name = u'Historico Comissão'
verbose_name_plural = u'Historico Comissões'
pednum = models.CharField(max_length=40, blank=True)
margem = models.DecimalField(decimal_places=4, max_digits=15, null=True, blank=True)
data = models.DateTimeField()
historico = models.TextField((u'Historico HTML'), blank=True)
status = models.PositiveSmallIntegerField(choices=[(1, 'Em Aberto'),
(3, 'Pendente'),
(4, 'Finalizado'),])
def __unicode__(self):
return str(self.pednum)
this is the views
from django.views import View
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from ..models import HistoricoComissao
def listview(request):
template_name = 'comissao/margenslist.html'
comissoes = HistoricoComissao.objects.all
context = {
'comissoes': comissoes
}
return render(request,template_name,context)
this is urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^list$', views.HistoricoComissao, name='historico_comissao'),
]
In your urls.py you use as view HistoricoComissao, but that is a re-export of a Django model, not of a view. You should use the listview:
from django.conf.urls import url
from . import views
urlpatterns = [
# link to a view function ↓
url(r'^list$', views.listview, name='historico_comissao'),
]
I am learning to develop and trying to develop a screen in django 1.1.
Please upgrade. Django-1.1 was end of life before 2013. Furthermore a lot of things have changed in the meantime (and often improved).