Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error on installing crispy python library with wheels in python:3.10.5-alpine docker image
Ahoi I tried to create an docker image from a Docker file of my djanog application. In the dockerfile i first use a builder to install the libraries from the requirements.txt file with wheel. When installing the crispy library it raises a ModuleNotFoundError: No module named 'silx'. The silx library is also in the requirements.txt file but is getting installed later. I also tried to put the silx entry in the requirements.txt before the crispy lib, but the error is getting raised anyway. Here is the error when i try to build the image: docker command to build the image: docker build . --progress=plain Collecting crispy==0.7.3 Downloading crispy-0.7.3.tar.gz (409 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 409.6/409.6 KB 106.5 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [12 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/setup.py", line 149, in <module> main() File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/setup.py", line 77, in main version=get_version(), File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/setup.py", line 53, in get_version from crispy import version File "/tmp/pip-wheel-9r0etvcg/crispy_5ce9bef2b34f47b19aabc37ccd7cfab8/crispy/__init__.py", line 3, in <module> from silx.resources import register_resource_directory ModuleNotFoundError: No … -
Django: Why is one template url working but the other isn't?
Essentially, my index.html postlist works great, and on the link to the post detail view it works correctly. However I copied the same code to my Profile view with only the posts of the request.user. It works without the {%url 'post_detail' post.slug %} as the rest of the paginated posts render as expected. However with this url, it throws this error: NoReverseMatch at /blog_app/profile/ Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$'] The code in the views and templates are essentially identical, why does this not work? Views.py: (the working one) class PostList(generic.ListView): model = Post queryset = Post.objects.filter(status=1).order_by("-created_on") template_name = "index.html" paginate_by = 6 (the not working one) class Profile(generic.ListView): model = Post template_name = "profile.html" paginate_by = 6 def get_queryset(self): return Post.objects.filter(author=self.request.user) urls.py: urlpatterns = [ path('', views.PostList.as_view(), name="home"), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), path('poll/<slug:slug>', views.PostPoll.as_view(), name='post_poll'), path('blog_app/create_post/', views.CreatePost.as_view(), name='create_post'), path('blog_app/profile/', views.Profile.as_view(), name='profile'), ] My two templates: (working one) {% for post in post_list %} <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> <div class="image-container"> {% if "placeholder" in post.featured_image.url %} <img class="card-img-top" src="https://codeinstitute.s3.amazonaws.com/fullstack/blog/default.jpg"> {% else %} <img class="card-img-top" src=" {{ post.featured_image.url }}"> {% endif %} <div class="image-flash"> <p class="author">Author: {{ post.author }}</p> </div> … -
Django: order elements of a form field
I have two models named Quiz and Course class Quiz(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='quizzes',) and class Course(models.Model): name = models.CharField(max_length=30) I'm using quiz model in a createview. class newQuiz(CreateView): model = Quiz template_name = 'teacher/new_quiz.html' fields = ['name', 'course', ] course field is shown as an choice field in the form how can i order the course choices in ascending order while showing in the form -
Using placeholder tags in non-django CMS pages
In the Django CMS there's the {% placeholder 'content' %}. I tried to use it on a non-django-cms page, i.e., a detail-view page that comes from an apphook. However, when I switch to the structure view in the detail-view page and the placeholder does not seem to reflect. Is that's how it's supposed to work or is there a problem with my code? If it's how it's supposed to work is there a way to make placeholder appear in the page? -
Django templateview not recognizing my template_name
Currently I have in settings set my main directory to the templates folder so that I have a project level templates. Within that folder I have a home.html file. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is my views.py file from django.views.generic import TemplateView class HomePageView(TemplateView): template_name: "home.html" Whenever I runserver I receive this error: ImproperlyConfigured at / TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()' I'm following a book to the T (Django for Beginners) and i'm unsure why this error could be happening. Has the syntax for template_name changed? I've checked all the documentations and my name seems to be okay. I've also tried to input the pathname to the file instead. Any help would be wonderful. Thank you -
How to get local-memory cache in Django Templates?
I set local-memory cache, then I tried to get it to display in the Django Template "index.html" as shown below: # "index.html" {{ cache.get.success }} But, it displayed nothing so are there any ways to get local-memory cache in Django Templates? -
Django: cleaned_data for special characters and punctuation marks
I want to validate the Name field in my form. Now I have in my forms: def clean_name(self): name = self.cleaned_data['name'] if re.search(r'\d', name): raise ValidationError('The name must not have numbers') if re.search(r'\s', name): raise ValidationError('The name must not have spaces') return name But I also want to create validation for special characters and punctuation marks. I have tried some ways with [[:punct:]], but this returns an error to me, and I guess that this doesn't work with Python or another way of using it is needed. Is there any way to do this, I need help. -
How to save all data collected from a multi step form in the database with Django
I'm attempting to construct a multi-step form, but I'm having trouble saving all the form's data. When I click submit, I can only save the Investment ID which is the input field on the first step. The remaining ones don't save to the database. Any ideas as to what I'm not understanding? I don't want to use Django form tools. views from django.shortcuts import render, reverse from django.http import HttpResponseRedirect from .models import Withdraw def create_withdraw(request): if request.method != 'POST': return HttpResponseRedirect(reverse('investment:withdraw')) else: investment_id = request.POST.get('investment_id') front_id = request.FILES.get('front_id') back_id = request.FILES.get('back_id') id_no = request.POST.get('id_no') proof_of_address = request.FILES.get('proof_of_address') user_pic = request.FILES.get('user_pic') try: withdraw = Withdraw.objects.create( investment_id=investment_id, front_id=front_id, back_id=back_id, id_no=id_no, proof_of_address=proof_of_address, user_pic=user_pic ) withdraw.save() messages.success(request, 'withdrawal request submitted successfully') return HttpResponseRedirect(reverse('investment:withdraw')) except: messages.success(request, 'request failed! Try again') return HttpResponseRedirect(reverse('investment:withdraw')) model from django.db import models class Withdraw(models.Model): investment_id = models.CharField(max_length=20, null=True) front_id = models.ImageField(upload_to="user_doc", null=True, blank=True) back_id = models.ImageField(upload_to="user_doc", null=True, blank=True) id_no = models.CharField(max_length=20, null=True, blank=True) proof_of_address = models.FileField(upload_to="users_doc", null=True, blank=True) user_pic = models.ImageField(upload_to="user_doc", null=True, blank=True) created_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.investment_id template {% extends 'base2.html' %} {% load static %} {% block content %} <!-- MultiStep Form --> <div class="flex justify-center md:w-1/2 mx-auto"> <form id="msform" action="{% url 'investment:create-withdraw' … -
VSCode not using test database for Django tests
I've got an issue where VSCode's test feature uses the production database instead of creating a test database. tests.py from django.test import TestCase # For VSCode test discovery from django import setup import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testing.settings") setup() class MyTestCase(TestCase): SomeModel.objects.create() my_model = SomeModel.objects.all() assert len(SomeModel.objects.all()) == 1 I have previously created 1 instance of SomeModel, so if you do SomeModel.objects.all() in the shell, it returns a queryset with that one instance. If I run this test from vscode's tester it will fail. And when I debug it, I can see my_model have two instances of SomeModel in the queryset. It does not use a test database, and uses the production database When I run this from python manage.py test my_app.tests it passes. And it outputs 'Creating test database' and 'Destroying test database' at the start and end of the test respectively. I assume this uses a test database. How can I make VSCode use a test database for the tests and am I missing something? -
How to get data from url in django without query parameters
sorry for my noob question as I am just starting to learn Django. I would appreciate if someone could tell me how can i change data dynamically on page in django. Let me clear this: What I want: When url is http://localhost/data/1111, page data should be like data is 1111. When url is http://localhost/data/2222, page data should be like data is 2222. What I did: def index(request): print(int(request.GET["data"])) # for debugging only return HttpResponse("data of Page") and url was: path('<int:data>', views.index, name='index') -
Set hourly limit on DateTimeField Django
class Event(models.Model): start = models.DateTimeField(default=timezone.now) end = models.DateTimeField() How can I set hard limit for setting end_date? So if the user wants to set anything over 5hours from start system won't let him do that -
The specified start time of the periodic task is ignored
I am trying to specify the time at which a periodic task created using the django-celery-beat application should be run, thus: # Incomplete project structure ├── config │ ├── asgi.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── order_monitoring │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── models.py │ ├── tasks.py │ ├── tests.py │ ├── urls.py │ ├── utils │ │ ├── scraperr │ │ │ ├── browser.py │ │ │ ├── chromedriver │ │ │ ├── db_scraper │ │ │ └── scraper.py │ │ └── utils.py │ └── views.py # config/settings.py ... USE_TZ = True TIME_ZONE = 'Europe/London' REDIS_HOST = '127.0.0.1' REDIS_PORT = '6379' CELERY_BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_IGNORE_RESULT = False CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_ENABLE_UTC = False CELERY_TIMEZONE = TIME_ZONE # config/celery.py import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config',) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # order_monitoring/utils/utils.py ... timezone = pytz.timezone('Europe/London') schedule, _ = CrontabSchedule.objects.get_or_create( minute='1', hour='*', day_of_week='*', day_of_month='*', month_of_year='*', timezone=timezone, ) … -
Django simpleJWT error "detail": "No active account found with the given credentials"
i'm trying to log into an account that isn't superuser and getting an error from rest_framework "detail": "No active account found with the given credentials" using a custom user model models.py : lass UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError('Users must have an email') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name) user.set_password(password) user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin ): first_name = models.CharField(unique=True, max_length=200) last_name = models.CharField(unique=True, max_length=200) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.CharField(unique=True, max_length=200) username = models.CharField(unique=True, max_length=200) email = models.EmailField(unique=True) User_Roles = models.ForeignKey(User_Roles, on_delete=models.CASCADE) USERNAME_FIELD = 'username' objects = BaseUserManager() i checked that the passwords are being hashed in the db but does not seem to be the case serializers.py : class RegisterSerializer(ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}) class Meta(): model = CustomUser fields = ['username', 'email', 'first_name', 'last_name', 'password', 'password2'] def save(self): user = CustomUser( email=self.validated_data['email'], username=self.validated_data['username'], first_name=self.validated_data['first_name'], last_name=self.validated_data['last_name'], ) password = self.validated_data['password'], password2 = self.validated_data['password2'], if password != password2: raise serializers.ValidationError({'password': 'Passwords must Match'}) user.set_password(str(password)) user.save() return user i had error where the password type was a tuple rather than a string or byte, and user.set_password(str(password)) seems to have fixed the issue that i wasn't able to figure out, … -
header not visible in django page
I am trying to render a page with header but header is not being rendered. content of categories.html is displaying perfectly. I have added header block on index.html page.What am i doing wrong here? index.html {% load static %} <link rel="icon" href="{% static 'stocks/logo.png' %}"> <html> <body> <div> {% block header %} {% endblock %} </div> {% block stocks_page %} {% endblock %} </div> </body> </html> header.html {% extends "stocks/index.html" %} {% block header %} <h1>Header content goes here</h1> {% endblock %} categories.html {% extends "stocks/index.html" %} {% load static %} {% block stocks_page %} <link rel="stylesheet" type="text/css" href="{% static 'stocks/style.css' %}"> {% if categories %} <h2>Product categories</h2> <table> <tr> <th>Name</th> <th>Count</th> </tr> {% for each in categories %} <tr> <td>{{ each.name }}</td> <td>{{ each.count }}</td> </tr> {% endfor %} </table> {% endif %} <form action="/stocks/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} views.py def product_categories(request): ---------------------- < code > ---------------------- return render(request, 'stocks/categories.html') -
DJANGO WSGI: ModuleNotFound when deploying as monorepo
I am trying to deploy a dockerized django app to digitalocean. It passes the build section, but shows the following error in deploying section: No module named 'backend-server'. 'backend-server' is the name of the directory that has all the backend files in my monorepo. From the error log, I'm assuming there's a problem with my wsgi settings, but I cannot find where to start looking. [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [2] [INFO] Starting gunicorn 20.1.0 [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [2] [INFO] Listening at: http://127.0.0.1:8000 (2) [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [2] [INFO] Using worker: sync [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [4] [INFO] Booting worker with pid: 4 [2022-07-30 14:35:47] [2022-07-30 14:35:47 +0000] [4] [ERROR] Exception in worker process [2022-07-30 14:35:47] Traceback (most recent call last): [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker [2022-07-30 14:35:47] worker.init_process() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process [2022-07-30 14:35:47] self.load_wsgi() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi [2022-07-30 14:35:47] self.wsgi = self.app.wsgi() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi [2022-07-30 14:35:47] self.callable = self.load() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load [2022-07-30 14:35:47] return self.load_wsgiapp() [2022-07-30 14:35:47] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp [2022-07-30 14:35:47] return util.import_app(self.app_uri) [2022-07-30 14:35:47] … -
Django: get_context_data for comments related post
I have a models: class Post(models.Model): post_text = models.CharField(max_length=100, unique=True) slug = models.SlugField(unique=True) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') post_relation = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='comments') comment_text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) In my views I need get comments for posts in get_context_data: class ResultsView(DetailView, FormMixin): model = Post template_name = 'posts.html' form_class = CommentForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comm'] = Comment.objects.filter(is_active=True) return context But in comm i get all comments in db. In html: {% for comment in question.comments.all %} <div class="media mb-4"> <div class="media-body"> <h5 class="mt-0">{{ comment.author }}</h5> {{ comment.comment_text }} </div> </div> {% endfor %} I try {% for comment in comm %}, try {% for comment in comm.all %} and always get all comments in db, not only comments in post. Also I try fix this string in views: context['comm'] = Comment.objects.filter(is_active=True), but don't have a result. The answer seems to be very simple, but I've already spent several hours trying and reading. Any help is welcome. -
Why does my Django test pass when it should fail?
I am new to testing of any sorts in coding. This is followup on this answer to my question. Answer establishes that this type of model method should not save object to database: @classmethod def create(cls, user, name): list = cls(user=user, name=name) return list If this is the case I am curious why does this test pass and says everything is ok? from django.test import TestCase from .models import List from django.contrib.auth.models import User class ListTestCase(TestCase): def setUp(self): user_1 = User(username="test_user", password="abcd") user_1.save() List.objects.create(user=user_1, name="mylist") List.objects.create(user=user_1, name="anotherlist") def test_lists_is_created(self): user_1 = User.objects.get(username="test_user") list_1 = List.objects.get(user=user_1, name="mylist") self.assertEqual("mylist", list_1.name) -
What is the problem named, 'img' attribute has no file associated with it.?
My motive is to show the product_image in the orderlist template. The ProductOrder works well and it also stores the product_image url in the img in the database. But when tried to show the image in the template, it has shown an error. Where did the actual problem occur? Please give me a relevant solution. models.py: class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_image = models.ImageField(blank=True, null=True, upload_to = "1_products_img") class ProductOrder(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserOrderRelatedName',on_delete=models.CASCADE) img = models.ImageField(blank=True, null=True) views.py: this works well, def Order(request, quick_view_id): OrderProduct = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: ProductOrder.objects.create( img = OrderProduct.product_image ) return redirect('quick_view', quick_view_id) def OrderList(request): AllOrder = ProductOrder.objects.all() context = { "AllOrder":AllOrder, } return render(request, "order_list.html", context) template: {% for order in AllOrder %} <img style="width: 100px;" src="{{order.img.url}}"> {% endfor %} error: ValueError at /OrderList/ The 'img' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/OrderList/ Django Version: 4.0.4 Exception Type: ValueError Exception Value: The 'img' attribute has no file associated with it. Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib', 'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39', 'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env', … -
Login Authentication with simplejwt in Django Rest Framework with templates and ajax
I am trying to make an application with Django Rest Framework and template without using any front-end application. I created the login form and user list by following this documentation https://www.django-rest-framework.org/topics/html-and-forms/. It works fine when submitting forms and showing list with templates. But when I am trying to authenticate login with simplejwt from the browser, the authentication fails. Failed Authentication Then I looked around and found this documentation https://ilovedjango.com/django/rest-api-framework/authentication/tips/working-example-of-jwt-authentication-with-ajax-django-rest-framework/ . I can use the ajax post call to get the token and set it to local storage on submit and set the header of another API later from the local storage, but in that case, it is not going to the action="{% url 'user:user-list-list' %}" of the form in the template after submit. So it stays on the login page and hits only the token/ URL for the token. When I add location.href = "{% url 'user:user-list-list' %}" in the ajax success, it loads the user_list but says 401 unauthorized. Here is my user_login.html template: {% load rest_framework %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <h1>User Login</h1> <form action="{% url 'user:user-list-list' %}" method="POST" id="login"> {% csrf_token %} <div class="form-group "> <label>Username</label> <input id="username" name="username" … -
how can i put a search box in my django app?
my code trying to make a search box for searching books is here, im trying to make a search box, when user enters the name of a book , like google, it be shown on page , when i add {{form}} to book.html file it has to shows a box, but it doesnt , views.py: def books(request): if request.method == 'POST': form = DashboardFom(request.POST) text = request.POST['text'] url = 'https://www.googleapis.com/books/v1/volumes?q='+text r = requests.get(url) answer = r.json() result_list = [] for i in range(10): result_dict = { 'title':answer['items'][i]['volumeInfo']['title'], 'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'), 'description':answer['items'][i]['volumeInfo'].get('description'), 'count':answer['items'][i]['volumeInfo'].get('pageCount'), 'catagories':answer['items'][i]['volumeInfo'].get('catagories'), 'rating':answer['items'][i]['volumeInfo'].get('pageRating'), 'thumbnail':answer['items'] [i]['volumeInfo'].get('imageLinks').get('thumbnail'), 'preview':answer['items'][i]['volumeInfo'].get('previewLink') } result_list.append(result_dict) context={ 'form':form, 'result':result_list, } return render(request,'dashboard/books.html',context) else: form = DashboardFom() context = {'form':form} return render(request,'dashboard/books.html',context) forms.py: class DashboardFom(forms.Form): text = forms.CharField(max_length=100,label='Enter your search : ') and also my books.html: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class='text-center container'> <h2>Search books and browse your favorite</h2> <p>just enter the search query to obtain the results</p><b></b> <form action="" method="POST"> {% csrf_token %} {{form}} <input class="btn btn-danger" type="submit" value="Submit"> </form><br> {% for result in results %} <a href="{{result.preview}}" target="_blank"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-3"> <img class="img-fluid" src="{{result.thumbnail}}" alt=""> </div> <div class="col-md-9"> <h3 class="p-0 m-0">{{result.title}}</h3> <b> <u> <h5 class="p-0 … -
How do I rename app on Github marketplace
I have a marketplace app https://github.com/marketplace/django-doctor/ (For context it offers fixes to Python and Django mistakes right inside the Github PR). but since creating the marketplace app I renamed the product to Code Review Doctor (it used to only offer fixes to Django code, but expanded to Python too and so the name had to change oops) I cannot see any way to rename the app and the link. Is this achievable some other way? I can't find a way to contact GitHub customer support. -
Why am I getting an error that my model form object has no attribute 'cleaned_data'?
I have a form on a page that users use to write comments. There is a view (comment) that should take in the users inputs along with some other information and save it to a model. However, when I tested it out, I got the error: 'CommentForm' object has no attribute 'cleaned_data' How do I fix this? views.py: def comment(request, id): if request.method == 'POST': form = CommentForm(request.POST) # the form if form.is_valid: current = get_object_or_404(Listing, id=id) user = User.objects.get(pk=request.user.id) obj = Comment() # the model obj.user = user obj.listing = current obj.date = datetime.datetime.now() obj.title = form.cleaned_data['title'] # this is where the error occurs obj.comment = form.cleaned_data['comment'] obj.rating = form.cleaned_data['rating'] obj.save() return listing(request, current.id, current.name) html: <form action=" {% url 'comment' listing.id %} " method="post" class="comment-form"> {% csrf_token %} <h2>Comment</h2> {{ commentForm.title }} {{ commentForm.comment }} {{ commentForm.rating }} <input type="submit" value="Comment" class="submit-btn"> </form> forms.py: class CommentForm(forms.Form): title = forms.CharField(max_length=60, widget=forms.TextInput(attrs={ 'class': 'comment-title', 'placeholder': 'Title', })) comment = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={ 'class': 'comment', 'placeholder': 'Enter Comment' })) rating = forms.FloatField(min_value=0, max_value=5, widget=forms.NumberInput(attrs={ 'class': 'rating', 'placeholder': 'Rating' })) -
Django - Prevent admin command to run twice
My problem is simple, i have an admin command name "send email": The problem is, the admin user succeed to call this function twice in a row. Probably in click on "Go" many time. So it sent email many time. There is a way to prevent it ? I tried to put a timeout in the end of the admin function "send_email" but it's not good ... It take 10 second between each users, and i have lot of users. def send_email(modeladmin, request, queryset): ... time.sleep(10) -
Does create() method save model object to Django database?
I just came across using create methods in Djangos models.Model subclass. Documentation has this example code: from django.db import models class Book(models.Model): title = models.CharField(max_length=100) @classmethod def create(cls, title): book = cls(title=title) # do something with the book return book book = Book.create("Pride and Prejudice") Does this already save new Book object to database? My intuition suggests that save() method should be called on the line # do something with the book or else it should not work. However when I try testing it, it seems that addin save() to it does not affect anything what so ever. Why is that the case and how does it actually save object to database? PS. I came across this while trying to learn testing with TestCase. If classmethod does not save anything to database problem is probably my testing code, but that would be whole another question. -
I am working on django project through github in which i get this error even after import or install all requirements
raise ImproperlyConfigured(error_msg) from exc django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable