Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assertion error parsing response to POST request from DRF viewset with DRF APIClient in tests
I've run into a strange issue with Django Rest Framework testing engine. The weird thing is that everything used to work fine with Django 3 and this issue turned up after I migrated to Django 4. Apart from testing, everything works well, and responds to queries as expected. The problem I'm using DRF APIClient to make queries for unit tests. While GET requests perform predictably, I fail to make POST requests work. Here is some minimalistic example code I created to figure out the issue. The versions I'm using: Python 3.9 Django==4.0.3 djangorestframework==3.13.1 from django.db import models from django.urls import include, path from django.utils import timezone from rest_framework import routers, serializers, viewsets router = routers.DefaultRouter() # models.py class SomeThing(models.Model): created_at = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=100, null=True, blank=True) # serializers.py class SomeThingSerializer(serializers.ModelSerializer): class Meta: fields = "__all__" model = SomeThing # views.py class SomeThingViewSet(viewsets.ModelViewSet): queryset = SomeThing.objects.all().order_by('id') serializer_class = SomeThingSerializer # urls.py router.register("some-things", SomeThingViewSet, basename="some_thing") app_name = 'question' urlpatterns = ( path('', include(router.urls)), ) Here is my test case: import json from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.test import APITestCase, APIClient class TestUserView(APITestCase): self.some_user = get_user_model().objects.create(login="some_user@test.ru") @staticmethod def get_client(user): client = APIClient() client.force_authenticate(user=user) return client def test_do_something(self): client … -
How to create multiples request in Django
I want to receive a request.POST values N times, where N is a number entered by the user. The views.py is: def valores(request): global peso_unitario, preco_unitario peso_unitario = [] preco_unitario = [] N = a print('N=' + str(N)) for i in range(N): form = Form(request.POST) c = int(request.POST.get('peso_u')) d = int(request.POST.get('preco_u')) peso_unitario.append(c) preco_unitario.append(d) return render(request, 'valores.html') return render(request, 'pacote_m.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) In this code in the end I have two returns, where the first is inside the for loop because I want to receive the values N times and return them to the template valores.html. The last return is in the end, after the for loop will redirect to a new template, this template pacote.html will show the values calculated according to I programmed, but it isn't the problem. The template valores.html is: {% extends 'basic.html' %} {% block content %} <form action="page2" method="GET"> {% csrf_token %} <h1>Digitados:</h1> numero de objetos={{n_objetos}}<br> peso peso maximo={{peso_maximo}}<br> <!--- Peso unitario: <input type="text" name="peso_u"><br><br> Preco unitario: <input type="text" name="preco_u"><br><br> ---> <table> <thead> <tr> <th>Peso unitario</th> <th>Preco unitario</th> </tr> </thead> <tbody> <tr> <td><input type="text" name="peso_u"></td> {{form.peso_u}} <td><input type="text" name="preco_u"></td> {{form.preco_u}} </tr> </table> <input type="submit"> </form> {% endblock %} My forms.py is: class Form(forms.Form): … -
How to mix the order of items of a Django object on a page?
I am trying to create a game that allows users to play a quiz, which is stored as a Django object, but I want the order of the questions to be different (as in random) every time. Is there a way to accomplish this? models.py class Quiz(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, default="") title = models.TextField(default="") question1 = models.TextField() answer1 = models.TextField() question2 = models.TextField() answer2 = models.TextField(default="") question3 = models.TextField() answer3 = models.TextField() ... (The questions and answers go to 10.) views.py def quiz(request, quiz_id): quiz = get_object_or_404(Quiz.objects, pk=quiz_id) return render(request, "capstone/quiz.html", { "quiz": quiz }) I was thinking about generating a random number, but I think that would be too complicated with the number of questions. Is there any easier way to randomly display the questions to the user? -
jinja2 emplateNotFound (but file exists)
In one of my views in Django 4.0 I want to render a summary of lesson with Jinja2. Even though a template exists for sure in good location I get jinja2.exceptions.TemplateNotFound which is very confusing. views.py: from jinja2 import Environment, FileSystemLoader def generate(request): if request.method == 'POST': ... var1 = "foo" var2 = "bar" var3 = 123 BASE_DIR = Path(__file__).resolve().parent.parent templatesPath = str(BASE_DIR) + '/static/tex/' fileSystemLoader = FileSystemLoader(templatesPath) env = Environment(loader = fileSystemLoader) renderedLatex = env.get_template(templatesPath + 'lesson_template.tex').render(pvar1, var2, var3) After calling the view the output is: jinja2.exceptions.TemplateNotFound: /home/user1/Projects/Dramath/Dramath-Project/static/tex/lesson_template.tex Just to be sure there is no typo I copied full path to the template file and compared it with the above - both paths are the same. For a quick test I tried to relocate lesson_template.tex in project root directory but it didin't do much. Any ideas where might be issue? -
How to show answers based on the certain question Django?
I'm writing a site where users can ask questions. I don't understand what problem is in my code, but when I'm trying to show all answers on certain question - nothing appears on the screen. I tried to use everything: QuerySet with filter, get, using id, but nothing works. Seems like problem in two thing: Django doesn't understand what answers to show or my template is incorrect. Here is the code: models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) detail = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.detail urls.py urlpatterns = [ path('', QuestionView.as_view(), name='forum'), path('search/', SearchView.as_view(), name='search'), path('question/<slug:slug>/', QuestionDetailView.as_view(), name='detail'), path('answer/', AnswerView.as_view(), name='answer') ] views.py class QuestionView(ListView): model = Question template_name = 'forum/forum.html' context_object_name = 'questions' ordering = ['-date_posted'] paginate_by = 1 class QuestionDetailView(DetailView): model = Question template_name = 'forum/detail.html' class AnswerView(ListView): model = Answer template_name = 'forum/detail.html' context_object_name = 'answers' def get_queryset(self): quest = Question.objects.get(id=1) return Answer.objects.filter(question=quest) templates/detail.html {% for answer in answers %} <div class="col-11"> <p>{{ answer.detail }}</p> <p><a href="#" class="mr-3">BigBossData</a><span>5 комментариев</span></p> </div> {% endfor %} -
viewing UserDetail template causes user to switch
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) In the DetailView for every Group other Users have the ability to see who has joined and also to check out the User's profile: {% extends 'base.html' %} <ul> {% for member in group.joined.all %} <li><a href="{% url 'user_detail' member.id %}">{{ member }}</a></li> {% endfor %} </ul> This works but with a slight catch. When I click on the link and go to that User's DetailView, suddenly I'm signed in as them. But only on that page it seems because when I go back to my home page, I'm suddenly signed back in as the original User. To be more clear, when I (as the User 'admin') go and click on another User link, I'm brought to the correct UserDetail view: <h6>{{user.username}}</h6> <div>Username: {{user.username}}</div> <div>Email: {{user.email}}</div> <div>First: {{user.first_name}}</div> <div>Last: {{user.last_name}}</div> <div>Groups Joined: {% for group in user.account.joined_group.all %} <a href="{% url 'group_detail' group.pk %}">{{group}}</a> {% endfor %} </div> <div>Groups Created: {% for group in user.account.created_groups.all %} <a href="{% url 'group_detail' group.pk %}">{{group}}</a> {% endfor %} </div> {% if user.is_authenticated and user.id == user.account.id %} <a href="{% url 'update_user' … -
Django whitenoise is fine for production but gives 404 for debug mode
I use django white noise and it works when DEBUG = False; however when setting DEBUG = True, I cannot load the image anymore and get 404 response. Note: I am aware of hard-refresh. I already used static collection and django migrations. Here is my code: django-admin startproject mysite python3 manage.py makemigrations python3 manage.py migrate python3 manage.py startapp polls python3 manage.py collectstatic pip show whitenoise|grep Version Version: 6.2.0 mysite/mysite/wsgi.py import os from whitenoise import WhiteNoise from django.core.wsgi import get_wsgi_application from mysite.settings import BASE_DIR os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() application = WhiteNoise(application, root=os.path.join(BASE_DIR, "staticfiles") ) mysite/mysite/asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_asgi_application() mysite/mysite/urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('polls.urls')), ] mysite/mysite/settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-u5pg-ef=-o0zzi16fk)xf1p8dsz7t$$vayc$3x1y(r01kb0rkg' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION … -
Django 'POST" returning 'Subscriber' object has no attribute 'title'
I am attempting to send a POST Request to add a 'Subscriber' to my database. The POST Request goes through without error. I am Posting this { "email":"email@app.com","campaign":1 } and it returns { "id": 2, "email": "email@app.com", "created_at": "2022-08-02T19:49:55.509018Z", "updated_at": "2022-08-02T19:49:55.509018Z", "campaign": 1 } The ID is 2 because it is the second POST I have made This is my Subscriber Class class Subscriber(models.Model): campaign = models.ForeignKey(to = Campaign, on_delete=models.CASCADE) email = models.EmailField(max_length=254) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering=('-created_at',) def __str__(self): return self.title() This is my Campaign Class class Campaign(models.Model): title = models.CharField(max_length=200) description = models.TextField() slug = models.SlugField(max_length=255, null = True, blank = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) logo = CloudinaryField('Image', overwrite=True, format="jpg") class Meta: ordering=('-created_at',) def __str__(self): return self.title def save(self, *args, **kwargs): to_assign=slugify(self.title) if Campaign.objects.filter(slug=to_assign).exists: to_assign = to_assign + str(Campaign.objects.all().count()) self.slug = to_assign super().save(*args, **kwargs) And These are my current Serializers.py class CampaignSerializer(serializers.ModelSerializer): class Meta: model = Campaign fields = "__all__" class SubscriberSerializer(serializers.ModelSerializer): class Meta: model = Subscriber fields = "__all__" My Views.py class CampaignListAPIView(generics.ListAPIView): serializer_class=CampaignSerializer def get_queryset(self): return Campaign.objects.all() class CampaignDetailAPIView(generics.GenericAPIView): serializer_class=CampaignSerializer def get(self, request, slug): #serialize the below python object! query_set = Campaign.objects.filter(slug=slug).first() if query_set: # If you're serializng more … -
ModuleNotFound Error when trying to import variable from script
I have a python script named "WhatsApp_to_Excel.py". There is a variable there that I need to use for a Django project I'm making. So I'm trying to import the module to the models.py file. This is my folder hierarchy- Then I make my import like this- But even though pycharm auto-completed the module's name, when I run the server I get the no module found error. I'm running my code from a virtual environment, but I don't see how this can be the problem. I've tried to import the module in an absolute way, but it didn't work and it's rather weird that pycharm DOES recognize the module. Does anybody Have any ideas on how to solve the problem? Would appreciate any help :-) -
How to get or show every object from newest to latest in Django
I'm pretty new to python and django. I was able to create an simple CRUD logic with template, but i'm getting a small problem. When i update a specific task and then querrying all object from a model, the one that was updated is now querried on the last position (views.py below): def create_task(request): tasks = Task.objects.all() if request.method == 'POST': task_id_update = request.POST.get('task_id_update') task_id_delete = request.POST.get('task_id_delete') if task_id_update: task = Task.objects.filter(id=task_id_update).first() task.finished = True task.save() elif task_id_delete: task = Task.objects.filter(id=task_id_delete).first() task.delete() else: form = TaskForm(request.POST) if form.is_valid(): task = form.save(commit=False) task.author = request.user task.save() return redirect('/create_task') form = TaskForm() return render(request, 'main/create_task.html', {'form': form, 'tasks': tasks}) And i want to render it on a ONE-PAGE like template, and this is what i did in my html: <table class="table table-hover"> <thead> <tr> <th scope="col">Title</th> </tr> </thead> <tbody> {% for task in tasks %} {% if task.finished == False %} <tr> <td>{{task.title}}</td> <td> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-warning" name= "task_id_update" value="{{task.id}}">Mark as finished</button> </form> </td> <td> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-danger" name= "task_id_delete" value="{{task.id}}">Delete</button> </form> </td> </tr> {% else %} <tr class="table-success"> <td>{{task.title}}</td> <td> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-danger" … -
Forcing evaluation of prefetched results in django queries
I'm trying to use select_related/prefetch_related to optimize some queries. However I have issues in "forcing" the queries to be evaluated all at once. Say I'm doing the following: fp_query = Fourprod.objects.filter(choisi=True).select_related("fk_fournis") pf = Prefetch("fourprod", queryset=fp_query) # products = Products.objects.filter(id__in=fp_query).prefetch_related(pf) With models: class Fourprod(models.Model): fk_produit = models.ForeignKey(to=Produit, related_name="fourprod") fk_fournis = models.ForeignKey(to=Fournis,related_name="fourprod") choisi = models.BooleanField(...) class Produit(models.Model): ... ordinary fields... class Fournis(models.Model): ... ordinary fields... So essentially, Fourprod has a fk to Fournis, Produit, and I want to prefetch those when I build the Produits queryset. I've checked in debug that the prefetch actually occurs and it does. I have a bunch of fields from different models I need to use to compute results. I don't really control the table structure, so I have to work with this. I can't come up with a reasonable query to do it all with the queries (or using raw), so I want to compute stuff python-side. It's a few 1000 objects, so reasonable to do in-memory. So I cast to a list to force the query evaluation: products = list(products) At this point, I would think that the Products and the related objects that I have pre-fetched should have been fetched from the DB. In … -
Linux / Django / Site not reachable
Something wrong. 2 months ago I was able to access my django server to this url/port http://212.47.245.79:8000/ Today I went back to this machine, as connection was down. I have restarted django, and I got ERR_CONNECTION_REFUSED in my browser With netstat -tulpn | grep LISTEN I can see the port is in LISTEN mode. What could be the cause ? -
Editable comments django blog
I'm having trouble making my comments editable. They work fine if I leave them uneditable, but I do want them editable. I think it has something to do with primary keys but I'm not quite getting the hang of it. I was able to edit comments earlier, but it would always edit the latest comment. Here is my code: models.py class Tee_times(models.Model): viable_courses = [ ("Eslövs GK","Eslövs GK"), ("Lunds Akademiska GK","Lunds Akademiska GK"), ("Söderåsens GK","Söderåsens GK") ] title = models.CharField(max_length=100, choices=viable_courses, default=1) content = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) player = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Comment(models.Model): text = models.CharField(max_length=200, default="Write a comment") tee_time = models.ForeignKey(Tee_times, related_name="comments", on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now_add=True) player = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ("pub_date",) def __str__(self): return f"{self.player} - {self.pub_date}" def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.tee_time.pk}) def set_time(self): self.pub_date = models.DateTimeField(auto_now_add=True) urls.py urlpatterns = [ path('', TeeListView.as_view(), name="index"), path('post/<int:pk>/', DetailTeeView.as_view(), name="post-detail"), path('post/<int:pk>/comment/new/', CommentCreateView.as_view(), name="comment-create"), path('post/<int:pk>/comment/<int:pkc>/update/', CommentUpdateView.as_view(), name="comment-update"), path('post/<int:pk>/comment/<int:pkc>/delete/', CommentDeleteView.as_view(), name="comment-delete"), path('post/new/', TeeCreateView.as_view(), name="post-create"), path('post/<int:pk>/update/', TeeUpdateView.as_view(), name="post-update"), path('post/<int:pk>/delete/', TeeDeleteView.as_view(), name="post-delete"), path("second/", views.second, name="second"), path("register/", user_views.register, name="Register") ] views.py ``` class TeeListView(ListView): model = Tee_times template_name = "testapp/index.html" context_object_name = "posts" ordering = ["-pub_date"] class DetailTeeView(DetailView): model = Tee_times … -
Django Template, how to parse items with symbols
I have an XML file that I've converted to a python dictionary and passed into a template. I am attempting to do something like this: <audio controls> <source src={{ episode.enclosure.@url }} type={{ episode.enclosure.@type }}> Your current browser does not support the audio player. </audio> The XML file uses @ at the beginning of the key for URL and TYPE. The problem is, this throws off the parser and crashes the site. How can I call a key with a symbol like @? -
State is being cleared on page reload
I am building a web site using Django and React and I just realized I've got this problem. Basically every time I log in to my page, while not refreshing everything is okay, my state is persistent and my user stays logged in. My logout functionality also works okay, whenever I need to log out the state is being cleared, the local storage is being cleared and everything is okay. The problem comes up when I reload my page. When I do that, my local storage persists but my state doesn't. I can't figure out a way to fix this issue. export const login = (email, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST, }); const config = { headers: { "Content-type": "application/json", }, }; const { data } = await axios.post( "/api/users/login/", { username: email, password: password }, config ); dispatch({ type: USER_LOGIN_SUCCESS, payload: data, }); localStorage.setItem("userInfo", JSON.stringify(data)); } catch (error) { dispatch({ type: USER_LOGIN_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }); } }; export const logout = () => (dispatch) => { localStorage.removeItem("userInfo"); dispatch({ type: USER_LOGOUT }); dispatch({ type: USER_DETAILS_RESET }); dispatch({ type: ORDER_LIST_MY_RESET }); dispatch({ type: USER_LIST_RESET }); }; These are my … -
Django Rest CORS with Vue JS
I have a django rest framework api running on http://127.0.0.1:8000/ and a Vue JS app running on http://127.0.0.1:5173/. When I make a request from the vue app I get the origin has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response. I have installed django cores and below are the setting in my settings.py Installed Apps "corsheaders", Middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And allowed CORS_ORIGIN_ALLOW_ALL = True Vue JS Code axios.defaults.baseURL = 'http://127.0.0.1:8000/'; # In axios.js async login() { const response = await axios.get('users', { username: this.username, password: this.password }); console.log(response) }, -
Django - Filtering String Between Two Values
I have a model like so: class Model(...): code = models.CharField(...) My model table is populated like so: ID | CODE -----|------------ 1 | c-AB-xyz 2 | c-AC-edf 3 | c-BB-mng 4 | c-BC-lmp 5 | c-CB-qrs 6 | c-CC-tuv I want to filter for instances based off what their code string starts with. I also want to specifiy a start and stop. For example, how can I filter instances that have a starting code value between c-BB and c-CB? Something like: Model.objects.filter( code__startswith__between = ['c-BB', 'c-CB'] ) Which should return instances 3, 4, and 5. -
How should I be storing query parameters for saved searches in web app? (best practices)
I have a web app that displays articles and each article has several fields all searchable with parameters and they have many to many and many to one relationships . There are several places in my database that store these parameters for something like a saved search or permissions to allow a user to only view certain articles. These parameters are stored as strings, or python query objects, or json objects. The problem is that when one of the names of the parameters changes, the query object, json object, or string isn't updated. So for example, if a article is published by 'U.S. Department of Justice', then a user saves a search with that agency, when we change the name of the agency (lets say there's a misspelling in the name), the search will not find that agency unless we go in an update the stored string object manually. This seems incorrect, but I'm not sure what the correct way is. Is there a best practices for something like this? Should the parameters be stored in a table with object references so that things like name changes are unaffected? OR do I just have to go into these strings and … -
Django positive validation not checking python
But with my below code it is not checking the validation rule and allowing the positive start and positive end values in the conjunction. my code in django form.py d=[] b=[] my_tuple = [] for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) d.append((start_new,start_old)) b.append((end_new,end_old)) my_tuple.append((d[0],b[0])) for i in my_tuple[0]: my_result = [sub for sub in i if all(element >= 0 for element in sub)] if len(my_result)>2: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
Django: How to stop a value from incrementing when i refresh a page in Django?
I have two some fields in my Profile model called: class Profile(models.Model): ... main_all_earning = models.IntegerField(default=0) earning_point = models.IntegerField(default=0) referral_point = models.IntegerField(default=0) indirect_sign_up = models.IntegerField(default=0) and i also have the logic in views.py def profile(request): ... user = request.user profile = request.user.profile my_count = Profile.objects.filter(recommended_by__profile__recommended_by=user).count() profile.indirect_sign_up = my_count * signup_point.ind_signup_point profile.main_all_earning = profile.main_all_earning + profile.indirect_sign_up profile.save() Now whenever i call this profile view, the main_all_earning add whatever is in the indirect_sign_up and give the new value and so on... How do i stop this? what i want is for the main_all_earning to add whatever that is in the indirect_sign_up only once and till there is a new value in the indirect_sign_up and not whenever i refresh the page -
Model using many models (Django)
I have a project where a Monster can have many Actions, but I don't want to relate the Action to any particular Monster. How can I do that? The code is as follows: Monsters(I divided that way so I can expand and create a Character Sheet based o the BaseSheet as well): from django.db import models from actions.models import Action # Create your models here. from django.utils.text import slugify class BaseSheet(models.Model): name: str = models.CharField(max_length=50) race: str = models.CharField(max_length=30) size: str = models.CharField(max_length=30) ac: int = models.IntegerField() ac_type: str = models.CharField(max_length=20) hp: int = models.IntegerField() hp_dices: str = models.CharField(max_length=10) movement: str = models.CharField(max_length=30) strength: int = models.IntegerField() dexterity: int = models.IntegerField() constitution: int = models.IntegerField() intelligence: int = models.IntegerField() wisdom: int = models.IntegerField() charisma: int = models.IntegerField() languages: str = models.CharField(max_length=100, default="None") slug: str = models.SlugField(blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(f'{self.name}-{self.id}') return super().save() class Monster(BaseSheet): challenge: str = models.CharField(default="0", max_length=3) description: str = models.TextField(default="") actions = models.ForeignKey(Action, on_delete=models.DO_NOTHING) Action: from django.db import models # Create your models here. class Action(models.Model): name: str = models.CharField(max_length=30) description: str = models.TextField() is_attack: bool = models.BooleanField(default=False) weapon_type: str = models.CharField(max_length=50, blank=True, null=True) attack: int … -
Reset PeriodicTask's interval timer to 0
I have a very simple problem: kick off a new periodic task (with 30 minutes interval) after the first model instance is created and reset the task's timer every time a new model is created. If no model is being created just let the scheduler keep firing the task every 30 minutes. Do I need to delete the previous task and create a new one, or is there another way of just having one task and keep postponing it? -
syntax error: unexpected end of file (expecting "then")
I have an entrypoint.sh file, and I try command docker-compose run web python manage.py runserver. But I get this error: : not found.sh: line 2: /entrypoint.sh: line 25: syntax error: unexpected end of file (expecting "then") ERROR: 2 My entrypoint.sh file: #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi if [ "$DEBUG" = "FALSE" ] then echo "run migrations and static" python manage.py migrate python manage.py collectstatic --no-input fi rm -f /app/web/app/celerybeat.pid # you can run celery worker and celery beat from here, all in one container exec "$@"* I use Windows -
django project cloned from github
Here am providing the error I am facing during run the project, firstly am cloned this project from Github and further add the .env file after that run the program and I get this error, please tell me the complete steps for cloning the project from Github and also the steps to run that project /*****************************************************************************/ Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\apps\config.py", line 245, in create app_module = import_module(app_name) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\its … -
how can I put image from list in template
I'm studying django and i would like to show an image of a list in the template views.py data = [ { "titulo": "image card 1", "imagem": img/image2.png", }, { "titulo": "image card 2", "imagem": "img/image1.png", }, ] return render(request, 'projects/dev.html',{'data':data}) template = index.html <div class="pb-5 container"> <div class="row"> {%for item in data%} <div class="card-deck col-md-6 pt-4 mx-auto"> <div class="card"> <a href="#"> <img class="card-img-top" src="{{item.imagem}}" alt=""> </a> <div class="card-body"> <h5 class="card-title"> {{item.titulo}}<br> </h5> </div> </div> </div> {%endfor%} </div> </div> </div> obs: I'm using static files