Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add style to base.html: Django framework?
file structure: app/template/base.html app/static/css/base.css I have created the base.html to contain the header, which I am importing to the other HTML pages to keep it the same throughout the website. And I want to style this header as well, so I am trying to link a base.css to my base.html, but no luck. Things which i have tried are : adding inline css, adding external css,adding internal css, clearing the cache, adding a block. code in base.html: {%load static%}<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'static/css/base.css' %}"> </head> <body> <nav> <button id="myButton" >Home</button> <button id="aboutButton" >About</button> <button id="contactButton" >Contact</button> </nav> {% block content %} {% endblock content %} <footer> <p>this is footer</p> </footer> <script type="text/javascript"> document.getElementById("myButton").onclick = function () { location.href = "{% url 'home' %}"; }; document.getElementById("aboutButton").onclick = function () { location.href = "{% url 'about' %}"; }; document.getElementById("contactButton").onclick = function () { location.href = "{% url 'contact' %}"; }; </script> </body> </html> that's my base.html code, which i want to link with base.css: .header { padding: 60px; text-align: center; background: #1abc9c; color: white; } .button { background-color: #4CAF50; /* Green */ border: none; color: white; … -
Restructure the following function for both robust functionality and maintainability
i have a python script wants to restructure for better functionality and maintainability. Suggestions are welcomed. The resulting return values in different scenarios should be constant. Code is pseudo code and does not have to run # Mock imports - assume these modules are imported import query_objs import enums from django import transaction import update_obj_in_db import api_client def rest_endpoint(input): qs = query_objs(id=input.id) obj = qs.get() obj.name = input.name + "_object" obj.save() if not qs.exists(): return 404 if len(input.name) > 5: return 422 if input.type != "bank_account": return 422 obj.type = enums.Types.BANK_ACCOUNT obj.save() with transaction.atmoic(): response = api_client.post(obj, input) if response.status != 200: return 500 update_obj_in_db(obj, input.details) return 200 -
Search filters that search/recommend similar for misspells as well Django REST framework
I have a Django REST app, what I want to do is: Make an API endpoint when we use ?search="India" it works great using the django-filters. I want it to work(can suggest some results if not finding the exact item) even for ?search="Inda" which is not spelled correctly by user error. How do I approach this issue? Do we use ML for this? I'm new to ML and am not aware of any ML things that might help me here. Any suggestions appreciated! -
Setting Cache-Control in Nginx / Gunicorn / Django
I am trying to set a Cache-Control in my Django/Gunicorn/Nginx project. However, all static files do not have any expiration. Here's how I try to set it. location ~* \.(?:js|css|png|jpg|jpeg|gif|svg|ico)$ { expires 1y; add_header Cache-Control "public, no-transform"; } I have also tried another way but it still didn't work: # Expires map map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } server { listen 80 default_server; listen [::]:80 default_server; expires $expires; -
How to Store Image File in Django from html form using Post request?
I am working on a project that require an profile pic. I created a Model in Django UserProfile class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) image = models.ImageField() adress = models.CharField(default='', max_length=150, blank=True) cnic = models.IntegerField(null=True) contact = models.IntegerField(null=True) city = models.CharField(max_length=50, null=True) about = models.CharField(max_length=50, null=True) location = models.CharField(max_length=150, null=True) subscriptions = models.IntegerField(null=True) rating = models.IntegerField(null=True) I am currently fetching data from HTML <form action="/users/profile/" method="POST" style="display: contents;"> {% csrf_token %} <div class="col-md-3 border-right"> <div class="d-flex flex-column align-items-center text-center p-3 py-5"> {% if profile.image %} <img class="rounded-circle mt-5" src="/media/{{profile.image}}" style="width: 200px;max-height: 300px;" id='image'> {% else %} <img class="rounded-circle mt-5" src="https://image.shutterstock.com/image-vector/house-not-available-icon-flat-260nw-1030785001.jpg" style="width: 200px;max-height: 300px;" id='image'> {% endif %} <label for="upload-photo" class="uploadImgLabel btn btn-outline-danger w-75">Browse</label> <input type="file" name="photo" id="upload-photo" required /> <span class="font-weight-bold">{{user}}</span><span class="text-black-50">{{user.email}}</span><span> </span> </div> All the other field is working correctly and I can visualize data by printing in views.py if request.method == 'POST': photo = request.POST.get('photo') fname = request.POST.get('firstname') lastname = request.POST.get('lastname') contact = request.POST.get('contact') address = request.POST.get('address') email = request.POST.get('email') country = request.POST.get('country') cnic = request.POST.get('cnic') city = request.POST.get('city') user = User.objects.get(username=request.user) user.first_name = fname user.last_name = lastname user.email = email user.save() obj = models.UserProfile.objects.get(user=request.user) obj.adress = address # obj.image = photo, <---- Here is the … -
application error django deployment heroku
I am trying to deploy my app to heroku and the deployment does not show me any error but when I try to load the website I get and Application error: An error occurred in the application and your page could not be served. I tried running heroku logs --tail as suggested and I get this traceback: app[web.1]: self.load_wsgi() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi app[web.1]: self.wsgi = self.app.wsgi() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi app[web.1]: self.callable = self.load() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load app[web.1]: return self.load_wsgiapp() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp app[web.1]: return util.import_app(self.app_uri) app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app app[web.1]: mod = importlib.import_module(module) app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked app[web.1]: ModuleNotFoundError: No module named 'api.wsgi' app[web.1]: [2021-05-01 17:13:14 +0000] [8] [INFO] Worker exiting (pid: 8) app[web.1]: [2021-05-01 17:13:14 +0000] [4] [WARNING] Worker with pid 8 was terminated due to signal 15 app[web.1]: [2021-05-01 17:13:14 +0000] [4] [INFO] Shutting down: Master app[web.1]: [2021-05-01 17:13:14 +0000] [4] [INFO] Reason: Worker failed to boot. … -
Django messes up the order of load tags?
I am using navbar of this project, in my django project (Bootstarp 4.6). Here is the code: Base.html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" href="{% static 'images/favicon.png' %}"> <!--Bootstarp CSS--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!--Bootstarp CSS ENDs--> <!--CSS--> {% block css %}{% endblock %} <!--CSS ENDs--> <title>{% block title %}{% endblock %}</title> </head> <body> <!--Navbar--> {% include 'quicky/navbar.html' %} <!--Navbar ENDs--> {% block content %} {% endblock %} <!--Bootstrap JS--> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <!--Bootstrap JS ENDs--> <!--JS--> {% block js %}{% endblock %} <!--JS ENDs--> </body> </html> Navbar.html : {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/quicky/navbar.css' %}"> {% endblock %} <nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark"> <a class="navbar-brand mr-auto mr-lg-0" href="#">Offcanvas navbar</a> <button class="navbar-toggler p-0 border-0" type="button" data-toggle="offcanvas"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse offcanvas-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Dashboard <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Notifications</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Profile</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Switch account</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Settings</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> … -
Can someone make me understand what the issue really is here? new to django
django==3.2 AssertionError at /api/content/coordinator/read/0 The request argument must be an instance of django.http.HttpRequest, not content_delivery.view.coordinator.Coordinator_View. class Coordinator_View(object): @staticmethod def run(request): obj = Coordinator_View() return obj.create(request) # this is where the actual error happens @api_view(['POST']) def create(self, request): ... -
make a new object in django restframework
i have this model class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField() i want make a new object using post method in restframework in django but i dont know what should i do please help me @api_view(['POST']) def create_product(request): ******* return Response({ ******* }, status=status.HTTP_201_CREATED) i should replace django code by **** please help me -
Querying the avg of a decimal field and doing top 10, issue on the amount of decimals
So my issue is that i made the following query, and i am trying to display it on a table. The query is supposed to bring the average of the margem_de_lucro (profit) field per type of vehicle therefore marca(brand), modelo (model) and ano (year of the car) need to be ordered by too or else, the table simply doesnt adjust, unfurtunately i am having trouble getting the average part to display correctly the number doesnt limit itself on the decimal fields and for what i can see it doesnt actually display the average. I am not sure what the problem is and i dont know how to limit it, would appreciate any help! Here is the query, query4= DataDB.objects.values('marca','modelo','ano','margem_de_lucro').annotate(medias=Avg('margem_de_lucro')).order_by('-medias')[:10] Here is the modal, of the called parts marca=models.CharField(max_length = 30,error_messages={'required':'Favor inserir uma marca'}) modelo=models.CharField(max_length = 60,error_messages={'required':'Favor inserir um modelo'}) ano=models.IntegerField( validators=[MinValueValidator(1960,'Favor inserir acima 1960.'), MaxValueValidator(2023,'Favor inserir abaixo 2023.')], error_messages={'required':'Favor inserir uma ano'}) margem_de_lucro=models.DecimalField(max_digits= 12,decimal_places=3,max_length= 12) And here is the table <table class="table table-striped table-dark" width="100%"> <thead> <th>Marca</th> <th>Modelo</th> <th>Ano</th> <th>Média de lucro</th> </thead> {%for q in query4 %} <tr> <td>{{q.marca}}</td> <td>{{q.modelo}}</td> <td>{{q.ano}}</td> <td>{{q.medias}}</td> </tr> {% endfor%} </table> The end result is as follows, -
500 internal server error on Heroku, while webapp runs locally
I successfully deployed a personal Django+React project built on Heroku but when I load the URL to my Heroku app I immediately get a 500 internal server error. From the console in Chrome it looks like this: Failed to load resource: the server responded with a status of 500 (Internal Server Error) and is caused by calling the endpoint /spotify/is-authenticated. This is called in a useEffect-hook (React) to check if the user is already logged in when a user enters the web page. The code in the App component looks as follows: useEffect(() => { fetch('/spotify/is-authenticated') .then(response => response.json()) .then(data => { console.log(`authentication status: ${data.status}`) setAuthenticated(data.status) hideLoading() }) // eslint-disable-next-line react-hooks/exhaustive-deps }, []) From the Heroku logs, the error looks as follows: 2021-05-01T16:46:31.825334+00:00 heroku[router]: at=info method=GET path="/spotify/is-authenticated" host=nameless-taiga-02413.herokuapp.com request_id=f334e22d-26d3-4fe8-8252-8e2810e8c19f fwd="77.164.173.60" dyno=web.1 connect=0ms service=37ms status=500 bytes=411 protocol=https As instructed by Django's security warning comment, debug mode in settings.py is DEBUG = False When I run the project with heroku local everything is fine and I can't find out why the app can't seem to reach the /spotify/is-authenticated endpoint... -
How to write a paginator which would set a default page depending on the current date?
I have a huge list of lessons ordered by the date. I want to include paginator so it would always set default page on a current date(if such lessons exists, and if not the nearest future lessons).Is it even possible to do? from django.contrib.auth.models import Lesson from django.core.paginator import Paginator lesson_list = Lesson.objects.all().order_by('datetime') paginator = Paginator(user_list, 10) -
Choose the correct option. Your option is not among the valid values. Django python
when entering the correct value into input, it outputs: Choose the correct option. Your option is not among the valid values. the error is that when entering, you must specify the pk field for the Service model and then the model is saved. And how to make the comparison by the name field take into account when writing the form? models class Service(models.Model): name = models.CharField(max_length=150, db_index=True, unique=True) used = models.IntegerField(default=0) def __str__(self): return self.name -
Django save a series of question and its corresponding answer set to database
I am a newbie in Django and I am working on a quiz functionality. I give the user an interface to create a quiz. It is based on a multi-step form. I input a certain number of questions and hit next. It displays that amount of fields for me to set the questions. Each question has 4 answers and I use radio buttons to select the right answer. The problem is I don't know how to retrieve them in my views when I hit the submit button. Like I want each question and its corresponding answers to be properly stored in the respective models. Can you guys please? It's lengthy but easy to grasp and some details can be overlooked as they are just fields :) Here is my code: models.py class PsychometricTest(models.Model): DIFF_CHOICES = ( ('easy', 'easy'), ('medium', 'medium'), ('hard', 'hard'), ) internship = models.ForeignKey(Internship, on_delete=models.CASCADE) name = models.CharField(max_length=120) description = models.TextField() number_of_questions = models.IntegerField() time = models.IntegerField(help_text="Duration of the quiz in minutes") required_score_to_pass = models.IntegerField(help_text="required score in %") difficulty = models.CharField(max_length=6, choices=DIFF_CHOICES) created = models.DateTimeField(auto_now_add=True) scheduled_date_time = models.DateTimeField() def __str__(self): return self.name+" - "+self.topic def get_questions(self): return self.question_set.all() class Question(models.Model): text = models.CharField(max_length=200) psychometric_test = models.ForeignKey(PsychometricTest, on_delete=models.CASCADE) created … -
Django Rest Framework - Efficient API Design
In any rest API, Data comes in request body We perform some Logic on data and perform some queries 3.finally API responds serialized data. My question is :- Where to put data processing Logic? And what is the efficient way of designing any REST API? -
Real time notification system with django and pyrebase
I built a django app for user and file management system which uses firebase as it's database via pyrebase. I want to build a notification system which will show events for each file upload, user changes and file changes. How can I assign these change events and show them in my html files? The notifications does not have to be real time but be a timestamp based event similar to all user. -
How to ORDER BY max no of same records in DJANGO
I want to order by movies in the Movies model according to the max number of occurrences of a tuple in the MyMovies model. models.py class Movies(models.Model): mid = models.CharField(max_length=255, primary_key=True) title = models.CharField(max_length=255, null=True, blank=True) rating = models.CharField(max_length=5, null=True, blank=True) type = models.CharField(max_length=255, null=True, blank=True) genre = models.CharField(max_length=255, null=True, blank=True) rdate = models.CharField(max_length=255, null=True, blank=True) language = models.CharField(max_length=255, null=True, blank=True) cover = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) sequal = models.CharField(max_length=255, null=True, blank=True) trailer = models.CharField(max_length=255, null=True, blank=True) year = models.CharField(max_length=5, null=True, blank=True) objects = models.Manager() def __str__(self) -> str: return self.title class MyMovies(models.Model): mid = models.ForeignKey(Movies, on_delete=CASCADE) uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True) watched = models.BooleanField() date = models.DateTimeField(auto_now_add=True) objects = models.Manager() view.py def showIndexPage(request): trending = list(MyMovies.objects.all().annotate(max_mid=Max(COUNT(mid))).order_by('-max_mid')) return render(request, 'index.html', {'trending': trending}) In the above code, MyMovies is my model with a foreign key mid referencing the Movie model. So, if in MyMovies there are 2 movies with mid 1, 4 movies with mid 2 and 1 movie with mid 3 Then the result should be a list (trending) of attributes of Movies which is ordered by no. of occurrences of a particular movie id: trending = [2, 1, 3] -
Following a tutorial I got a view retuning None instead because is_ajax is not working
I just started with ajax but can't seem to find the fix for this. I think it might have to do with the comment_id vs the blog_id. (followed this tutorial: https://www.youtube.com/watch?v=VoWw1Y5qqt8&list=PLKILtxhEt4-RT-GkrDkJDLuRPQfSK-6Yi&index=39&ab_channel=AbhishekVerma). This is what my views.py looks like def like_comment(request): comment = get_object_or_404(Comment, id=request.POST.get("comment_id")) blog = get_object_or_404(BlogPost, id=request.POST.get("blog_id")) comments = Comment.objects.filter(post=blog, reply=None) if request.user in comment.likers.all(): comment.likers.remove(request.user) else: comment.likers.add(request.user) context = { "comments": comments, "blog_post": blog, "body": markdown2.markdown(blog.body), "comment_form": CommentForm(), } if request.is_ajax(): html = render_to_string('blog/like_section.html', context, request=request) return JsonResponse({'form': html}) This is a snippet of my HTML {% if request.user.is_authenticated %} <form action={% url 'like_comment' %} method="POST"> {% csrf_token %} {% if user in comment.likers.all %} <input type="hidden" name="blog_id" value=" {{ blog_post.id }}"> <button type="submit" id="like" name="comment_id" value="{{ comment.id }}">Like</button> {% else %} <input type="hidden" name="blog_id" value=" {{ blog_post.id }}"> <button type="submit" id="like" name="comment_id" value="{{ comment.id }}">Dislike</button> {% endif %} {% else %} <div><small class="comment_time">Login to Like</small></div> {% endif %} </form> </div> <small class="comment_time">{{ comment.total_likes }} Likes</small> And this is the javascript: $(document).ready(function (event) { $(document).on('click', '#like', function (event) { event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: "POST", url: '{% url "like_comment" %}', data: { 'blog_id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function (response) { $('#like_section').html(response['form']) … -
How to I return JsonResponse from Paginator's page? Object of type Page is not JSON serializable
(this is my first stackoverflow question ever) I want to return JsonResponse from the dictionary "context" (seems to be a paginator Page) as coded below: myposts = userposts.all().values() myfollowers = userfollowers.ffollowers.all() myfollowings = userfollowers.ffollowings.all() context = {"posts": page_obj, "loops": range(1, totalpages + 1), "user": uprofile.username, "myposts": list(myposts), "mypostsnum": len(userposts.all()), "myfollowers": list(myfollowers), "myfollowersnum": len(userfollowers.ffollowers.all()), "myfollowings": list(myfollowings), "myfollowingsnum": len(userfollowers.ffollowings.all()) } this is the return I use: return JsonResponse(context, safe=False) Result I get: Object of type Page is not JSON serializable My question is how do I get JsonResponse from 'context'? -
Refused to apply style because its MIME type ('text/html') in django and next js
hello i did everything with integration but nothing seems working,its again saying the same error all next js files are default no changes settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'frontend/.next/static/css') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') pls help me find a solution to this problem i have done everything that i can do with this integration -
docker django django.db.utils.OperationalError: could not translate host name "thinkcentre" to address: No address associated with hostname
I am trying to create a docker, that run a django app which uses a Postgresql database on the same computer where I will be running the App . The database runs in current OS (Windows 10 Pro on that computer) and the docker accesses it but do not contains it. When I create my docker file and run it from another computer it works. When I create this same docker file on the computer that host the database I get thssi error: django django.db.utils.OperationalError: could not translate host name "thinkcentre" to address: No address associated with hostname My docker file is as followed: # For more information, please refer to https://aka.ms/vscode-docker-python # FROM python:3.7.10-slim-buster => couldn't install psygo2 dependencies FROM python:3.7.10 EXPOSE 7000 EXPOSE 5432 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 # set up a venv ENV VIRTUAL_ENV=/opt/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" # install psycopg2 dependencies # RUN apk update # RUN apk add postgresql-dev gcc python3-dev musl-dev RUN apt update # \ # && apt add postgresql-dev gcc python3-dev musl-dev # Install pip requirements RUN pip install --upgrade pip … -
Django: Calculate avrage recipe rating
I am creating a website that lets users post recipes. When the user clicks on a recipe they can see more details about it and they can also comment and give a rating. My question is how can I calculate the average recipe rating**enter code here Models.py class Recept(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset() naslov = models.CharField(max_length=100) sestavine = models.CharField(max_length=100) priprava = models.TextField() rec_img = models.ImageField(upload_to='rec_pics', default='default2.jpg') datum = models.DateTimeField(default=timezone.now) avtor = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) likes = models.ManyToManyField( User, related_name="blog_recept", blank=True) favorites = models.ManyToManyField( User, related_name='favorite', default=None, blank=True) newmanager = NewManager() CHOICES = ( (1, '1 stars'), (2, '2 stars'), (3, '3 stars'), (4, '4 stars'), (5, '5 stars'), ) class Reviews(models.Model): recept = models.ForeignKey( Recept, related_name="reviews", on_delete=models.CASCADE) user = models.ForeignKey( User, related_name="reviews", on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) stars = models.IntegerField(choices=CHOICES) datum = models.DateTimeField(default=timezone.now) Views.py class PostDetailView(FormMixin, DetailView): model = Recept form_class = CommentForm def get_success_url(self): return reverse('recept-detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) get_recept = get_object_or_404(Recept, id=self.kwargs['pk']) fav = bool if get_recept.favorites.filter(id=self.request.user.id).exists(): fav = True total_sestavine = get_recept.vejice() total_likes = get_recept.total_likes() total_likes2 = get_recept.total_likes2() # pokliče functions liked = False if get_recept.likes.filter(id=self.request.user.id).exists(): liked = True if get_recept.likes.exists(): last_like = get_recept.last_like() context['last_like'] … -
Django and Css Link
I have Made A Project of website Django I want To Link It With css & html How I can Do That? I Want To Use Django Just Like Search Engine For Front-End -
django_crontab is adding my jobs, but they don't seem to execute. Anu solution?
I got a django project running with django-crontab (github) on Ubuntu 20. in <my_django_app> directory I added a cron.py file: from .models import <my_model> from datetime import datetime def remove_stamps(): for stamp in <my_model>.objects.order_by('-stop_date'): if stamp.can_be_removed(): stamp.delete() else: break def close_stamps(): for stamp in <my_model>.objects.filter(stop_date=None): stamp.stop_date = datetime.now() stamp.save() in settings: CRONJOBS = [ ('*/4 * * * *', '<my_django_app>.cron.remove_stamps'), ... ] CRONTAB_LOCK_JOBS = True I deployed the project as follows: First created a <new_user> in the command line with @root like this: adduser --system --home=/var/opt/<project_name> --no-create-home --disabled-password --group --shell=/bin/bash <new_user> Using Nginx I ran the virtual environment with this <new_user> using gunicorn like this: [Unit] Description=<project_name> [Service] User=<new_user> Group=<new_user> Environment="PYTHONPATH=/etc/opt/<project_name>:/opt/<project_name>" Environment="DJANGO_SETTINGS_MODULE=settings" ExecStart=/opt/<project_name>/venv/bin/gunicorn \ --workers=4 \ --log-file=/var/log/<project_name>/gunicorn.log \ --bind=127.0.0.1:8000 --bind=[::1]:8000 \ <project_name>.wsgi:application [Install] WantedBy=multi-user.target Next I added the django_crontab jobs using: PYTHONPATH=/etc/opt/<project_name>:/opt/<project_name> DJANGO_SETTINGS_MODULE=settings su <new_user> -c "/opt/<project_name>/venv/bin/python3 /opt/<project_name>/manage.py crontab add" Checking the crontab jobs with .... crontab show gives: <HASH KEY> -> ('*/4 * * * *', '<my_django_app>.cron.remove_stamps') <HASH KEY> -> ('*/5 * * * *', '<my_django_app>.cron.close_stamps') Using journalctl _COMM=cron --since="2021-5-1 14:00" to check if the job runs, gives following: May 01 17:00:01 ubuntu-2gb-hel1-2 CRON[276942]: pam_unix(cron:session): session opened for user <new_user> by (uid=0) May 01 17:00:01 ubuntu-2gb-hel1-2 CRON[276940]: pam_unix(cron:session): session … -
django CreateView forms not loading in html
I have found a lots of similar problems on this topics. None of them has proper solution. CreateView form from models not loading. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author: models.ForeignKey( User, on_delete=models.CASCADE, related_name='post_author') blog_title: models.CharField(max_length=264, verbose_name="Title") slug: models.SlugField(max_length=264, unique=True) blog_content: models.TextField(verbose_name="What is on your mind?") blog_image: models.ImageField( upload_to='blog_images', verbose_name='images') publish_date: models.DateField(auto_now_add=True) updated_date: models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title views.py from django.shortcuts import render, HttpResponseRedirect from django.views.generic import CreateView, DeleteView, UpdateView, ListView, DetailView, View, TemplateView from App_Blog.models import Blog, Comment, Likes from django.urls import reverse, reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. def blog_list(request): return render(request, 'App_Blog/blog_list.html', context={}) class CreateBlog(LoginRequiredMixin, CreateView): model = Blog template_name = 'App_Blog/create_blog.html' fields = '__all__' urls.py from django.urls import path from App_Blog import views app_name = 'App_Blog' urlpatterns = [ path('', views.blog_list, name='blog_list'), path('write/', views.CreateBlog.as_view(), name='create_blog'), ] I am trying to load the form in this html page: create_blog.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title_block %} Write a Blog {% endblock title_block %} {% block body_block %} <h2>Start Writing:</h2> <form method="POST" enctype="multipart/form-data"> {{ form | crispy }} {% csrf_token %} <button type="button" class="btn btn-success …