Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Django require change permission to add a foreign key?
I have two models in my application, Product and Holder. A Holder can have n products, and a Product must have one Holder. These are the classes: class Product: title = models.CharField(verbose_name=_('Title'), max_length=100) holder = models.ForeignKey(verbose_name=_('Main Holder'), to=Holder, on_delete=models.PROTECT) ... class Holder: name = models.CharField(verbose_name=_('Name'), max_length=50, unique=True) ... When a user that is a staff_member tries to create or change a Product, that specific user has to have the database's change_holder permission assigned to them, otherwise they can't assign a Holder to that Product. The list of holders won't even load up on the respective field on Admin, as the following image illustrates. Anyway, what I'd like to know is what justifies this behavior. Why would a user need permission to change the foreign key model, if they're not changing that model, but the one that contains the key? -
How can i implement a function to any user add products to my site(Django)?
I am trying to insert my product by category, and the product attributs in django. I have two model Product(Tool) and Category. If i'm logged has user i want to add my product in my site. This is my product models from django.db import models from django.urls import reverse from model_utils.models import TimeStampedModel from utool import settings class AvailableManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_available=True) class Category(TimeStampedModel): name = models.CharField(max_length=255, unique=True) slug = AutoSlugField(unique=True, always_update=False, populate_from="name") class Meta: ordering = ("name",) verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name def get_absolute_url(self): return reverse("pages:list_by_category", kwargs={"slug": self.slug}) class Tool(TimeStampedModel): category = models.ForeignKey( Category, related_name="tools", on_delete=models.CASCADE ) name = models.CharField(max_length=255) slug = AutoSlugField(unique=True, always_update=False, populate_from="name") image = models.ImageField(upload_to="tools/%Y/%m/%d", blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) is_available = models.BooleanField(default=True) # user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) objects = models.Manager() available = AvailableManager() class Meta: ordering = ("name",) def __str__(self): return self.name def get_absolute_url(self): return reverse("pages:detail", kwargs={"slug": self.slug}) And this is my product views from django.views.generic import DetailView, ListView from .models import Category, Tool class ToolDetailView(DetailView): queryset = Tool.available.all() class ToolListView(ListView): category = None paginate_by = 6 def get_queryset(self): queryset = Tool.available.all() category_slug = self.kwargs.get("slug") if category_slug: self.category = get_object_or_404(Category, slug=category_slug) queryset = queryset.filter(category=self.category) return queryset … -
'SalaryAdmin' object has no attribute 'request'
Hello I want to add method to list display in django admin but am getting error say SalryAdmin has no attribute request here my admin @admin.register(Salary) class SalaryAdmin(admin.ModelAdmin): list_display = ['user_name', 'action'] def action(self, obj): if not self.request.user.is_superuser: if obj.hr_state == 'request-change-approved' and self.request.user.user_role.position.code == 'HRM': return True else: return False else: return True any help appreciated -
Using ckeditor in Django without the built-in provided forms
I am new to Django and till now, I have not been using Django forms. Instead, I have been making my own customised forms in templates by using Bootstrap and css. But, now, I have a field where I want to use a rich text editor like Ckeditor. Is there a way to use it without the Django built-in forms? Thank youuu for your reply :)) -
use of upload_to function when creating on object in django
here is my model in django : import os def upload_location_buy(instance, filename): ext = filename.split('.')[-1] filename = '%s.%s' % (instance.name+"_"+str(random.randint(1000, 9999)), ext) print(os.path.join('uploads', filename)) return os.path.join('uploads', filename) class Buy(models.Model): pic_front = models.ImageField(blank=True, upload_to=upload_location_buy,default='') When i try : b = Buy(pic_front="appartement_a.jpg") b.save() it does nothing exception linking the current pic in the current path, so not using the function in the model. And when i do : b = Buy(pic_front=upload_location_buy("appartement_a.jpg")) b.save() it give me an error because it seems to need the instance. TypeError: upload_location_buy() missing 1 required positional argument: 'filename' How to create a buy object, giving it a picture and using the upload_location_buy whend doing it without the admin ? When i upload a pic in the admin it works. how to give it the instance name or do it correctly ? regards -
I am getting an error no such table: users_profile. Why so?
I have the following Profile model as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') slug = AutoSlugField(populate_from='user') bio = models.CharField(max_length=255, blank=True) friends = models.ManyToManyField("Profile", blank=True) def __str__(self): return str(self.user.username) def get_absolute_url(self): return "/users/{}".format(self.slug) path('users/', users_list, name='users_list'), @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) my_friends = request.user.profile.friends.all() sent_to = [] friends = [] for user in my_friends: friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends += friend for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) random_list = random.sample(list(users), min(len(list(users)), 10)) for r in random_list: if r in friends: random_list.remove(r) friends += random_list for i in my_friends: if i in friends: friends.remove(i) for se in sent_friend_requests: sent_to.append(se.to_user) context = { 'users': friends, 'sent': sent_to } return render(request, "users/users_list.html", context) and I have users_list.html template. I have tried building the database tables with migrate command and tables have been created. But I still get the error message: no such table: users_profile What could be the problem? -
Adding item to cart in Python, Django. FieldError at /add/1 -> Cannot resolve keyword 'book' into field. Choices are: author,
I have two functions, one adds items to the cart and one removes. While I try to add the item to the cart I get an error: FieldError at /add/1 Cannot resolve keyword 'book' into field. Choices are: author, author_id, bookorder, description, id, price, publish_date, review, stock, title Where do I go wrong? Any help is appreciated! models.py from django.db.models.query import prefetch_related_objects from django.utils import timezone from django.contrib.auth.models import User class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return "%s, %s" % (self.last_name, self.first_name) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField() publish_date = models.DateField(default=timezone.now) price = models.DecimalField(decimal_places=2, max_digits=8) stock = models.IntegerField(default=2) class Meta: verbose_name ='Book' verbose_name_plural = 'Books' db_table = 'book' class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) order_date = models.DateField(null=True) payment_type = models.CharField(max_length=100, null=True) payment_id = models.CharField(max_length=100, null=True) def add_to_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = Book.objects.get(book=book, cart=self) preexisting_order.quantity += 1 preexisting_order.save() except BookOrder.DoesNotExist: new_order = BookOrder.objects.create( book=book, cart=self, quantity = 1 ) new_order.save def remove_from_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = BookOrder.objects.get(book=book, cart=self) if preexisting_order.quantity > 1: preexisting_order.quantity -= 1 preexisting_order.save() else: preexisting_order.delete() except BookOrder.DoesNotExist: pass class BookOrder(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, … -
CSRF exempt for contactform - Django
Is it safe to use a CSRF exempt for a contactform or a form using the send_mail function from Django? So according to the docs; The first defense against CSRF attacks is to ensure that GET requests (and other ‘safe’ methods, as defined by RFC 7231#section-4.2.1) are side effect free. Is a POST request, which only creates an email message and does not touch the database, considered as a "safe" method? Example code from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect def send_email(request): subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('from_email', '') if subject and message and from_email: try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') *example from docs I'm just wondering if I'm not missing something before I add the CSRF exempt. Now I hear you thinking, why would someone want to disable the CSRF validation? In the EU we have to comply to the GDPR. By setting a cookie, we need to explicitly ask the user to accept cookies, if we can prevent setting … -
Emailing a PDF Generated from HTML: expected bytes-like object, not HttpResponse
I am trying to email a PDF that has been generated from a HTML template. I get the following error: expected bytes-like object, not HttpResponse generate_pdf: def generate_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None view for pdf emailing: def pdfView(request): data = {'test':'test', 'mylist': 'test' } pdf = generate_pdf('main/test.html', data) msg = EmailMessage("title", "content", to=["email@email.com"]) msg.attach('my_pdf.pdf', pdf, 'application/pdf') msg.content_subtype = "html" msg.send() return HttpResponse(pdf, content_type='application/pdf') -
Save image from Django to S3 AWS without admin.py
I'm in a face recognition project and I would like that the final result show the image that the person upload (His/Her face) and the image of a person that you look a like. I want to store the uploaded image by some user to my S3 AWS bucket but I'm not using the admin.py script because I created a new template: where you upload your pic and then the "Ir" button runs a python function called "fibocal". template.html <div class="container-contact100-form-btn" id = "hola"> <ul><button type="submit" class="notify-btn" onclick="showLoaderOnClick('{% url 'gallery:fibocal' %}')"> <span> Ir </span> </button></ul> </div> and the "fibocal" function is in views.py: def fibocal(request): if request.method == 'POST': img_loaded = request.FILES['image'] imagenes = FR(img_loaded) return render(request, 'base.html', {'name': imagenes[0], 'prct':imagenes[1], 'imagen': imagenes[2]}) else: return render(request, 'home/register.html', {}) So, I would like that when the user upload the image it will be save to the S3 budget, but I don´t know how to add the "Save" button that is in the default admin template by default. I would like to add a new function to "Ir" button that save the image at the S3 AWS and also runs the fibocal function. Thanks! -
How to make reverse foregnkey/1to1/MtoM connections explicit in django models?
Say there are two models like these: class Post(models.Model): ... class User(models.Model): posts = ManyToManyField(post, ...) ... I know that Post.user is still available in the django querysets and I know about relatedname but there are cases where I also need to add field users to Post model, to which, if I remember correcly, django issues a warning. In my case, I need to write a serializer (project uses DRF) for such implicit field, which is not possible (because "model Post doesn't have field users" to continue the example). And even if it's ok to ignore warning and just make fields explicit, situation is still hard since MtoM is an reverse of MtoM and 1to1 is a reverse of 1to1 but there is no reverse to foreignKey. -
how can restrict access to media image url
how can restrict access to media image url , and make it accessible only by access owner user in django , here is my class model : class private_image(models.Model): i_user = models.OneToOneField(User, related_name='related_PRF_user', on_delete=models.CASCADE) i_image= models.ImageField(upload_to='images', blank=True, null=True ) and my media settings is : MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root/') MEDIA_URL = '/media_url/' i believe, i can make a small function to check access-user and requested URL '/media_url/images/' to get image name , and then get an object from database using image name and then check the owner(i_user) if same access-user . but how can i tell Django to use this function before service MEDIA_URL requests . if you have an example , that will be very helpful . thank you in advanced -
Django and Vuetify
Good morning, good afternoon or good night. How are you? I'm implementing an application using the famous and our Python friend Django and inside it I'm using Vuetify with our VueJs. I always used this using and creating APIs in Django and consuming it on Vuetify. However, I was given the challenge of using Vuetify inside Django using its CDN, but I have a lot of difficulties and I wanted to know if anyone here on the stack has been there. (In case of doubt, not that of npm install inside the django project, but just consume and call the components .Vue like this using your cdn too) In the base.html of django I was able to redenrize a vue page <!DOCTYPE html> {% load static %} <!--{% url 'social:begin' 'google-oauth2' as url_login_gmail %}--> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Odontotolgia Undb</title> <link rel="shortcut icon" href="https://www.undb.edu.br/hubfs/avatar_site.png"> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"> <style type="text/css"> a{ color: #fff; text-decoration: none; text-decoration-line: none; text-decoration-style: initial; text-decoration-color: initial; } </style> </head> <body> <div id="app"> <v-card height="665px" > <v-navigation-drawer v-model="drawer" :mini-variant.sync="mini" permanent absolute > <v-list-item class="px-4"> <v-list-item-avatar> <v-img src="https://randomuser.me/api/portraits/men/85.jpg"></v-img> </v-list-item-avatar> <v-list-item-title> &nbsp; … -
Why is Django not pulling from session? Also .get funtion no longer lights up as the .all function does? Nothing displays from database
`from django.shortcuts import render,redirect, HttpResponse` `from user_login_app.models import User` `from .models import Book,Author,Rating` `from django.contrib import messages` def index(request): `user=User.objects.get(id=request.session['user_id'])`===================================================On this line the get function isn't operating I can no longer pull from session and the function doesn't light up the way it did. I also get no user display on the page. Normally the .get function highlights as the .all function does, also displays the logged in user on the page. No I get nothing from Session. To be clear, I also made all migrations. I have items in my database. I just can't pull them out. As I have in the past. `author=Author.objects.all()` `rating=Rating.objects.all()`My context statment no longer renders anything. I double checked it agianst past projects. those were all written very similarly. `context={` `'users':user,` `' authors':author,` `'ratings':rating,` } return render(request,'book_home.html',context) I don't get why my .get function doesn't work?? I hope someone has an answer to this puzzle. -
Django - complex annotation/aggregation based on date difference
I have models Category, Lead and Event. The event describes an action of generating leads (downloaded from external source) and can be created anytime - eg 2 times a day, then 7 days nothing, then 1 time a day etc. Event has a new_leads field that keeps track of Lead objects. Each Lead has some category (like clothes, electro etc). I'm trying to predict (based on the history) how many leads would be generated if I created a new event today. I started with annotating Event queryset by the counts of leads for each category. categories = Category.DEFAULT_CATEGORIES annotations = {category[0]:Count('new_leads',filter=Q(new_leads__category__name=category[1])) for category in categories} events = Event.objects.all().annotate(**annotations) Now, for every event, I can just call the category attribute this way: event.clothes which returns a number of new clothes. This is where I don't know how to continue. I want to calculate/annotate the average new leads count per day. Eg. for a particular event and category, I'll divide the number of leads by a number of days since the Event before. Something like event.clothes_avg_per_day and then I'd aggregate the average from all the events for all the categories. That way I'd have an average number of new leads per category … -
Output HTML Table in Django For Each Date in SQL Query
I am creating a call reports dashboard in django, and I want to output a postgresql Select query in an HTML table for each date of the month like this: For whatever reason I am having a very hard time figuring this out. This is my HTML, I know I am not doing the looping right here, I've just been running out of ideas. {% for i in lt.itertuples %} <table class="table" style="float:left"> <caption>{{ i.to_date }}</caption> <thead> <tr> <th>Extension</th> <th>Calls</th> </tr> </thead> {% for d in df4.itertuples %} <tr> <td> {{ d.member_extension }} </td> <td> {{ d.count }} </td> </tr> {% endfor %} </table> {% endfor %} </div> And this is a snippet of my Python: query=pd.read_sql_query("select DISTINCT date(start_date) as 'DATE()' from Reports3; ",con3) query2=pd.read_sql_query("SELECT COUNT(*),member_extension from Reports3 group by member_extension ",con3) df4 = pd.DataFrame(query) lt = pd.DataFrame(query2) ext4=pd.unique(df4['member_extension']) context={'df4':df4, 'ex4':ext4, 'lt':lt } return render(request,'index2.html',context) -
Send to server float array using libcurl c++
I am using a portaudio callback where I receive periodically a buffer of audio and store it on main_buffer. I only set the settings bellow for curl and only use the CURLOPT_POSTFIELDS to set the float buffer before sending it with curl_easy_perform. On the server side I am using python django: float main_buffer[256]; url_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, URL); //portaudio periodic callback callback(){ //... curl_easy_setopt(curl, CURLOPT_POSTFIELDS, main_buffer); curl_easy_perform(curl); } The request received in server has no content inside body. How to send main_buffer the right way ? Thank you ! -
How to Solve this django.db.utils.IntegrityError
I have no idea why this error keeps showing. This error seems to occur whenever I try to migrate my models.py. Here is the error first: django.db.utils.IntegrityError: The row in table 'leads_lead' with primary key '1' has an invalid foreign key: leads_lead.class_duration_id contains a value '50' that does not have a corresponding value in leads_classduration.id. Here is my full lead model(commented out my classduration after this error occurred, but it is still the same): class Lead(models.Model): first_name = models.CharField(_('Korean Name'), max_length=20) last_name = models.CharField(_('English Name'), max_length=20) username = models.CharField(max_length=100, null=True, blank=True) age = models.IntegerField(default=0) organisation = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.SET_NULL) agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="leads", null=True, blank=True, on_delete=models.SET_NULL) description = models.TextField(null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) phone_number = models.CharField(max_length=20) email = models.EmailField() # ENROLLED IN CLASS FROM WHEN TO WHEN class_start_date = models.DateField(null=True, blank=True, default=datetime.date(1111,11,11)) class_end_date = models.DateField(null=True, blank=True, default=datetime.date(1111,11,11)) weekday = models.ManyToManyField('Weekday', blank=True, help_text='Select weekdays for the student') time = models.TimeField(null=True, blank=True, default=datetime.time(0,0)) # LEAD_CLASS_DURATION = ( # (10, '10 minutes'), # (20, '20 minutes'), # (25, '25 minutes'), # (30, '30 minutes'), # (50, '50 minutes'), # ) # class_duration = models.IntegerField( # choices=LEAD_CLASS_DURATION, # null=True, # blank=True, # ) # input_classes: managed by … -
trying to use custom user model with django-allauth framework
i have a custom user model that looks like this from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager # user manager code class MyUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """ Creates and saves a User with the given email, first name, last name and password. """ if not email: raise ValueError("Users must have an email address") user = self.model( email=self.normalize_email(email), **extra_fields, ) user.set_password(password) user.save(using=self._db) return user # Create your models here. class CustomUser(AbstractUser): email = models.EmailField(unique=True) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email my serializer.py class RegisteSerializer(serializers.Serializer): password = serializers.CharField(style={"input_type": "password"}, write_only=True) password2 = serializers.CharField(style={"input_type": "password"}, write_only=True) email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) first_name = serializers.CharField(min_length=2, max_length=50) last_name = serializers.CharField(min_length=2, max_length=50) USERNAME_FIELD = 'email' class Meta: model = User fields = [ 'id', 'first_name', 'last_name', "email", "password", "password2", ] extra_kwargs = {'password': {'write_only': True}} def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( ("A user is already registered with this e-mail address.")) return email def validate_password(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password'] != data['password2']: raise serializers.ValidationError( ("The two password fields didn't match.")) return data def get_cleaned_data(self): return { 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'password': … -
django User matching query does not exist
i'm trying to signup with an otp for verification by sending email to the user mail, but getting this error, trying to signup with an otp for verification by sending email to the user mail, but getting this error, if is there any better solution do this with django would be appreciate, models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] is_buyer = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) objects = CustomUserManager() def __str__(self): return self.email class UserOTP(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) time_st = models.DateTimeField(auto_now = True) otp = models.SmallIntegerField() class Vendor(models.Model): user = models.OneToOneField(User, related_name='vendor', on_delete=models.CASCADE) business_name = models.CharField(max_length=50) def __str__(self): return self.user.email forms.py class VendorSignUpForm(UserCreationForm): business_name = forms.CharField(required=True) email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('business_name', 'email', 'password1', 'password2', ) @transaction.atomic def save(self): user = super().save(commit=False) user.is_vendor = True user.save() customer = Vendor.objects.create(user=user) customer.business_name=self.cleaned_data.get('business_name') customer.save() return user views.py def signup(request): if request.method == 'POST': get_otp = request.POST.get('otp') print(get_otp) if get_otp: get_user = request.POST.get('user') user = User.objects.get(email=get_user) if int(get_otp) == UserOTP.objects.filter(user = user).last().otp: user.is_active = True user.save() messages.success(request, f'Account is Created For {user.email}') return redirect('login') else: messages.warning(request, f'You Entered a Wrong OTP') … -
Exclude object from queryset if any of it's many to many related objects has a given property value
let's say I have a models like this: class Bar(Model): value = IntegerField() class Foo(Model): bars = ManyToManyField(Bar) Now, how do I get a queryset of Foo objects, excluding the ones, which have any of bars object with value of 0? Corresponding Python code would be like this: foos_ids_to_exclude = [] for foo in Foo.objects.all(): for bar in foo.bars.all(): if bar.value == 0: foos_ids_to_exclude.append(foo.id) break resulting_queryset = Foo.objects.exclude(id__in=foos_ids_to_exclude) But how do I do this on DjangoORM level? It's even possible? I want to do this without evaluating the queryset if possible. -
What extensions of python markdown can be used to parse sequence charts and flow charts?
I'm developing a blog app by using django, there's a feature is that showing articles written by markdown.I have imported django-mdeditor to edit markdown content. Now I want to parse and show it on another page. I parse markdown contents like this: import markdown content = markdown.markdown(markdown_string) Now I have been able to successfully parse some markdown syntax, but I can't do it well on sequence charts and flow charts. Are there some extensions of python-markdown or some other modules can do it well? Thank for your answer firstly!! -
The page code in Django is output instead of the form
I output it in html in this way - {{news}} When you open the page, it shows the code of the page itself ................................................................................ Views.py from django.shortcuts import render from .models import Comment from .forms import CommentForms def index(request): return render(request , 'mainToo/index.html') def reviews(request): form = CommentForms() data = { 'form' : form } news = Comment.objects.all() return render(request , 'mainToo/reviews.html', {'news':news} , data) models.py from django.db import models class Comment(models.Model): nameAndSurname = models.CharField('Фамилия и имя' , max_length=50 ) text = models.TextField('Ваш отзыв' , max_length=1000 ,) date = models.DateTimeField('Дата и время') def __str__(self): return self.nameAndSurname class Meta: verbose_name='Отзыв' verbose_name_plural='Отзывы' forms.py from .models import Comment from django.forms import ModelForm , TextInput class CommentForms(ModelForm): class Meta: model = Comment fields = ['nameAndSurname' , 'text' , 'date'] urls.py from django.urls import path from . import views urlpatterns = [ path('' , views.index , name='home'), path( 'reviews/' , views.reviews , name='reviews'), ] -
If we are using Generic views in Django, then the templates must be present within the templates folder in the app in which the views are specified?
I am new to Django framework and the instructor what normally does is that he joins the path with the base dir for generic templates like base.html and all ,and for login and signup and app specific templates he creates a dir within the app and populates the html there, he never mentioned how it works and I am confused what method would I follow , can someone explain this in an easy way!! -
I am trying to build a website with django and it is giving me this error [closed]
I am trying to build a website with Django and it is giving me error. I run with python manage.py runserver. Traceback (most recent call last): File "C:\CS\Projects\ideas\New folder (2)\study-planner-master\manage.py", line 21, in <module> main() File "C:\CS\Projects\ideas\New folder (2)\study-planner-master\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Anurag\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", line 189, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.