Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
504 Gateway Time-out django mail
I use nginx. I get this error when I try to send an email. The SMTP data is completely correct. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.yandex.ru' EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = "123@yandex.ru" EMAIL_HOST_PASSWORD = "1234" DEFAULT_FROM_EMAIL = "123@yandex.ru" send email message = render_to_string('user/email_confirmation.html', context=context) email = EmailMessage( '124', message, to=[user.email], ) email.send() On the other server, everything is exactly the same and everything works. But here there is an error. -
How do I ensure validation of my django form?
I am attempting to create a form in which a user can enter two dates to specify a block. However if there already exists a block with dates that overlap the ones the user enters then an error message should be displayed. Additionally I want to ensure that the start date of the block is before the end date. However every time I run my view method, the user is allowed to defy both constraints with no error message displayed. This is my views.py method def set_block_dates(request): if request.method == 'POST': form = BlockForm(request.POST) if form.is_valid(): if (form.check_overlap and form.check_time): form.save() return redirect('home') else: messages.add_message(request, messages.ERROR, "The dates cannot overlap and start date must be before end date!") else: form = BlockForm() return render(request, 'setBlockDates.html', {'form': form}) This is my forms.py class class BlockForm(forms.ModelForm): class Meta: model = Block fields = ['start', 'end'] def check_time(self): return True if self.cleaned_data.get('start') < self.cleaned_data.get('end') else false def check_overlap(self, *args, **kwargs): overlapping_start_dates = Block.objects.filter(start__gte=self.cleaned_data.get('start'), start__lte=self.cleaned_data.get('end')).count() overlapping_end_dates = Block.objects.filter(end__gte=self.cleaned_data.get('start'), end__lte=self.cleaned_data.get('end')).count() overlapping_dates = overlapping_start_dates > 0 or overlapping_end_dates > 0 if overlapping_dates: return False else: return True def save(self): super().save(commit=False) block = Block.objects.create( start_date = self.cleaned_data.get('start'), end_date = self.cleaned_data.get('end'), ) The user is allowed to submit … -
I can't add a value to this user model field
I'm trying to do a system where an user gains points if he asks a question but the points field isn't increasing when a user does that. my model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='post') category = models.ForeignKey(Category, on_delete=models.PROTECT) type = models.CharField(max_length=30, choices=TYPE, default='Question') title = models.CharField(max_length=100, unique=True) content = models.TextField() views = models.IntegerField(default=0) votes = models.ManyToManyField(User, blank=True, related_name='vote') featured = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) my view: class PostCreateView(LoginRequiredMixin, CreateView): model = Post success_url = '/' fields = ['title', 'content', 'category'] def form_valid(self, form): form.instance.author = self.request.user form.instance.author.points + 15 return super().form_valid(form) When I go to the current user in the admin page the value doesn't change. -
Using 'group()' got "No result backend is configured." error in Django
With the code below, I use Celery 5.2.7 and django-celery-results in Django: # "core/celery.py" import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') # "core/settings.py" INSTALLED_APPS = [ # ... 'django_celery_results' ] CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' # "store/tasks.py" from celery import shared_task @shared_task def add(x, y): return x + y Then, I ran Celery with the command below: celery -A core worker --pool=solo -l info Then, called add.delay(3, 4) in test() as shown below: # "store/views.py" from .tasks import add from django.http import HttpResponse def test(request): add.delay(3, 4) # Here return HttpResponse("Test") Then, I could properly get the result below: Task store.tasks.add[...] succeeded in 0.04s: 7 # Here But, when calling group(add.delay(i, i) for i in range(10))().get() in test() as shown below: # "store/views.py" from celery import group from django.http import HttpResponse def test(request): group(add.delay(i, i) for i in range(10))().get() # Here return HttpResponse("Test") I got the error below: NotImplementedError: No result backend is configured. Please see the documentation for more information. So, I tried si() as shown below: # "store/views.py" from celery import group from django.http import HttpResponse def call_test(request): # ↓ Here group(add.si(i, i) for i … -
Websocket does not receive any message from django channels
I am currently building an application with django channels. I have a websocket connected to a server. Looking at my terminal, it seems like the websocket is successfully connected to the server. HTTP GET / 200 [0.01, 127.0.0.1:62087] HTTP GET /static/video/js/websocket.js 200 [0.00, 127.0.0.1:62087] WebSocket HANDSHAKING /ws/video [127.0.0.1:62089] WebSocket CONNECT /ws/video [127.0.0.1:62089] However, the websocket does not receive the message sent from the server. Here are my codes: consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class VideoConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(json.dumps({'message': 'you are connected!'})) websocket.js const address = 'ws://' + window.location.host + '/ws/video' const websocket = new WebSocket(address) const btn = document.getElementById('myButton') websocket.onopen = (event) => { console.log('websocket connected!!!') } websocket.onmessage = (event) => { console.log(event.data) } I would like to receive the message "you are connected!" on my browser's console. I looked into the official django channels document and google searched for a solution but I failed to solve my issue. What am I missing here? -
ValueError at /create_post/
When I click the Create New Post button, I get this error. The service.views.create_post view did not return an HttpResponse object. Instead, it returned None. view.py @login_required @permission_required("service.add_post") def create_post(req): form = PostForm() if req.method == "POST": form = PostForm(req.POST) if form.is_valid(): form.save() title = form.cleaned_data.get("title") if title != "POST": messages.error(req, f"Something went wrong") return redirect('index') id = form.cleaned_data.get("pk") messages.success(req, f"Post {title} was created successfully") return redirect('index') return render(req, "create_post.html", {"form":form}) Nothing because I don't understand the error -
Django Category LIst
I want to show all categories in sidebar can you help me !!! how to list all category pls help my models.py categories = models.ManyToManyField('Category', verbose_name=_('Categories'), blank=True) class Category(models.Model): display = models.CharField(_('Category'), max_length=100) slug = models.SlugField(_('Slug'), unique=True) def __str__(self): return self.display @property def get_absolute_url(self): return reverse_lazy('category_list', args=[self.slug]) class Meta: verbose_name_plural = _('Categories') my views.py class CategoryList(BaseListView): def get_queryset(self): posts = ( Post.objects.filter(is_published=True) .filter(categories__slug=self.kwargs.get("cat")) .order_by("-modified_date") ) term = self.request.GET.get("search") if term: posts = posts.filter(title__icontains=term) return posts def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["list_term"] = Category.objects.get(slug=self.kwargs.get("cat")).display context["list_type"] = "category" return context I've tried but I'm not sure I can do it -
Django annotate with
How can i use average_ndvi and field_count variables into annotate, i need change 0.14 to F"average_ndvi", 5 to F"field_count". commune = ( Commune.objects.annotate( year=SearchVector("field__fieldattribute__date__year"), month=SearchVector(Cast("field__fieldattribute__date__month", CharField())), size=Sum(F("field__fieldattribute__planted_area")), average_ndvi=Avg(F("field__fieldattribute__ndvi")), field_count=Count("field"), standart_deviation=Sum( ((F("field__fieldattribute__ndvi") - 0.14) ** 2) / 5, output_field=FloatField(), ), ) .filter(year=year, month=str(month)) .only("id", "name") ) -
How to order a combined queryset by annotated field?
The weight for our objects is composed of 2 fields. One field is the weight unit (kilogram, tonne and pound) and the other field is the weight (number). I have tried making a queryset which annotates all the weights into one universal unit field. The problem is that once I order_by that annotated (unit) field, it still orders by largest number and not by largest weight. For example 100kg is less than 50t, but the ordering system just sorts by the largest number. This is the code inside the filters.py: ` class AircraftFilter(FilterSet): tail_number = CharFilter(field_name="tail_number", lookup_expr="startswith") by_weight = CharFilter(method="filter_by_weight") class Meta: model = Aircraft fields = ("tail_number", "by_weight") def filter_by_weight(self, qs: QuerySet, value, *args, **kwargs): if value != None: qs = ( qs.filter(max_takeoff_weight_unit=2).annotate( mtw_lb=F("max_takeoff_weight") * 2200 ) | qs.filter(max_takeoff_weight_unit=1).annotate( mtw_lb=F("max_takeoff_weight") * 2.2 ) | qs.filter(max_takeoff_weight_unit=3).annotate( mtw_lb=F("max_takeoff_weight") ) ) qs = qs.order_by("mtw_lb") return qs ` The query: `qs = (Aircraft.objects.all().filter(max_takeoff_weight_unit=2).annotate(mtw_lb=F("max_takeoff_weight")*2200) | Aircraft.objects.all().filter(max_takeoff_weight_unit=1).annotate(mtw_lb=F("max_takeoff_weight") * 2.2) | Aircraft.objects.all().filter(max_takeoff_weight_unit=3).annotate(mtw_lb=F("max_takeoff_weight"))).order_by("mtw_lb")` and the output: `<IsActiveModelQuerySet [ID: 5 | weight: 0.05 - (t) , ID: 4 | weight: 0.20 - (t) , ID: 8 | weight: 2.00 - (t) , ID: 7 | weight: 50.00 - (lbs) , ID: 6 | weight: 100.00 - (kg) ]>` -
i get an error while i use 'is none' in DJANGO [closed]
If there is no row in the Duyuru table registered to the database, I want the h5 tag to be displayed on the screen. But the h5 tag does not appear on the screen. This is my html file: (https://i.stack.imgur.com/K6Pte.png) and this is views: (https://i.stack.imgur.com/V7OWg.png) Can you help me? -
I try to be able to load an image in the django admin, but I can't see it when I click
I don't know how to solve it. It's really frustrating. If you managed to help, I would be very grateful. settings: ``` ``` STATIC_URL = '/static/' MEDIA_URL='Proyectoweb/media/' MEDIA_ROOT=BASE_DIR / 'Proyecto/media' ``` ``` url: ``` ``` from django.urls import path from ProyectoApp import views from django.conf import settings from django.conf.urls.static import static ``` ``` urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` ``` models: ``` from django.db import models # Create your models here. class Servicio(models.Model): titulo=models.CharField(max_length=50) contenido=models.CharField(max_length=50) imagen=models.ImageField(upload_to='servicios') created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='servicio' verbose_name_plural='servicios' def __str__(self): return self.titulo ``` admin: ``` from django.contrib import admin from .models import Servicio # Register your models here. class ServicioAdmin(admin.ModelAdmin): readonly_fields=('created', 'updated') admin.site.register(Servicio, ServicioAdmin) ``` For some reason, this page asks me for more details, when I think I have already given enough. I try to be able to load an image in the django admin, but I can't see it when I click.... -
How can I set a variable width in my CSS or Tailwind class?
I am getting the width from my Django View, but I do not know if I can make it variable in CSS. I’ve been trying to set the Tailwind, but I imagine that it is not the right thing to do: {% for movie in movies %} <div id="bar" class="w-[{movie.score}]" style="transition: 1s"> {{movie.score}} </div> {% endfor %} However, I am also trying to do it directly in CSS, but the style does not accept a variable as: {% for movie in movies %} <div id="bar" style="transition: 1s; width: {{movie.score}}; "> {{movie.score}} </div> {% endfor %} I’ve also tried to change it using JavaScript, but I have to select multiple elements because there will be various bars. So, this just not worked. I receive messages that the movies were declared before if I use let, but using var nothing changes. def get_context_data(self, **kwargs): context = super(MoviesRatePage, self).get_context_data(**kwargs) context['movies'] = movies return context {% block javascript %} <script type="text/javascript"> var movies = "{{movies}}"; for (let i = 0; i < movies.length; i++) { document.querySelectorAll("#bar")[i].style.width = `${movies[i].score}%`; } </script> {% endblock javascript %} Thus, I want to make the bar width the same as the movie’s score. -
Is there a way to type the elements of the dictionary that is returned by a serializer?
I use the serializers that come from django-rest-framework to validate many of the request on my app end. I have found thhat is very useful to get the objects on the serializer, but the dictionary the serializer returns with the serializer.validated_data is not typed This is how I perform the validation: On views.py def post(self, request): body_serializer = ExampleSerializer(data=request.data) body_serializer.is_valid(raise_exception=True) body_data = body_serializer.validated_data # to get the object object_one = body_data['object_one'] On the serializers.py class ExampleSerializer(serializers.Serializer): field_one = serializers.CharField(required=True, help_text='field_one') field_two = serializers.CharField(required=True, help_text='field_two') field_three = serializers.CharField(required=True, help_text='field_three') def validate(self, attrs): object_one:ObjectOne = ObjectExample.objects.get(field=field_one) attrs['object_one'] = object_one return attrs Is there a way I can type the return dictionary? -
How to import my views from user in my urls.py file
I am using Pycharm for my Django Project. It says that it is a unresolved reference. In Startup/urls.py I have following code: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('vereinsapp/', include('vereinsapp.urls')), path('', include('vereinsapp.urls')), #Users path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('delete_user/', user_views.deleteuser, name='delete_user'), path('profile_confirm_delete/', user_views.profile_confirm_delete, name='profile_confirm_delete'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I also tried startup.users but then I get the error Message "no module named..": -
bootstrap alert-dismissable not working in django
here is my html code <div class="msg"> {% if messages %} {% for message in messages %} <div class="alert alert-dismissible alert-success"> <button type="button" class="close" data-dismiss="alert"> × </button> <strong>{{message}}</strong> </div> {% endfor %} {% endif %} </div> message is showing after form submission, but x button not working of collapse, how to resolve it, please help me. -
Django Model form is showing invalid with initialized values and file
I have a model like this: ` class Cohortpdfs(models.Model): id = models.AutoField(primary_key=True,editable=True) title= models.CharField(max_length=200,validators=[MaxLengthValidator(100)]) content=models.FileField() cohort_id=models.ForeignKey(Cohort,on_delete=models.CASCADE,default=0,db_constraint=False) ` I want to initialize and save data from views. views.py: ` if requests.method == 'POST': initialvalue={ 'cohort_id':id, 'title':requests.POST.get('title'), 'content':requests.FILES['content'], } if contentform.is_valid(): print("form valid") else: print("FORM ERROR") ` Forms.py class CohortpdfsForm(forms.ModelForm): class Meta: model = Cohortpdfs fields = [ "title","content","cohort_id", ] widgets={ 'title' : forms.TextInput(attrs={'class': 'form-control','max_length':20}), 'content': forms.FileInput(attrs={'class': 'form-control'}), 'cohort_id': forms.TextInput(attrs={'type': 'hidden'}), } ` This is showing my form is not valid. How can I initialize the form with uploaded file(PDF) and save it into the model database. This is showing my form is not valid. How can I initialize the form with uploaded file(PDF) and save it into the model database. -
What is the correct way to end a Watchdog observer without a sleep loop?
I am relatively new to python and programing in general. This is my first question on Stack Overflow so thank you for any responses in advance! My question is this. I have a Python web application that is using the django framework. A new feature of that web application requires the use of a locally installed command line tool on the server, that tool dumps an output file to a directory previously created. I want to watch that directory and when a file is created in it that ends in .json call a parsing function. Enter the Watchdog library. I have followed a number of tutorials/checked on here for how to correctly setup an observer. They all have the observer being started and then immediately going into a time.sleep(1) loop while waiting for something to happen. However since this is a django webapp I don't want to sit and wait while the watchdog observer is looking for the file to be created. Here is an example code from Geeks for Geeks: if __name__ == "__main__": # Set the format for logging info logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # Set format for displaying path path = sys.argv[1] if len(sys.argv) > … -
No module named 'manage_db.tools'; 'manage_db' is not a package
I have a Package that works with the Django Framework. I'm trying to import two packages that are outside the Django package, so that I can work with their Python files. In order for Django to recognize the packages, I added the following lines to the Django settings file: manage_db = os.path.join(BASE_DIR.parent.parent, "manage_db") g = os.path.join(BASE_DIR.parent.parent, "g") sys.path.append(manage_db) sys.path.append(g) And in the views.py file I wrote: from g.globals import Globals from manage_db.tools import Tools The error I got is: For the first package - No module named 'manage_db.tools'; 'manage_db' is not a package For the second package - No module named 'g' . I read from people who had similar problems that they changed the names of the directories, and it worked for them, I tried, and I change the name to "g", but it didn't work. Note: I created the packages, they are not packs that require pip install Thanks in advance to all the helpers. -
How to receive the value of an html attribute through the submitted form DJANGO
How can I get the value of the "data" attribute of this select's options? With request.POST.get() <select name="installments" id="installments"> <option value="1" data="239.8">239,80</option> <option value="2" data="125.31">125,31</option> <option value="3" data="84.76">84,76</option> <option value="4" data="64.5">64,50</option> <option value="5" data="52.35">52,35</option> <option value="6" data="44.25">44,25</option> </select> I tried this: installments = request.POST.get('installments.attrs=["data"]') -
create new objects from list only if its not in django database
I am having a list of python objects. suppose py_objs_list = [...data...] Model is Card I want to create a new object in django database only if database already dont have object My solution is to do objects.all() on my Card and run a for loop on py_objs_list and check if py_obj in objects.all(). If not present im taking that py_obj into seperate list. Finally creating objects using bulk_create py_objs_list = [...data...] cards = list(Card.objects.al()) <--- i know db hits here ---> emails = [card.email for card in cards] <--- does db hit here also everytime in a loop ---> empty_list = [] for py_obj in py_objs_list: if py_obj[some_data] not in emails: empty_list.append(py_obj) ---bulk_create--- Is this the best way to tackle this problem? pls tell me if not (want the best one). thnks:) Now my doubt is does db hit everytime in list comprehension as mentioned above my solution for this problem -
'Category' object is not subscriptable Django
I am learning Django. I wrote a simple model and some views method in Django rest framework so that I can modify some particular attributes when needed to all the records that need that. Here is the model: from django.db import models class Category(models.Model): name = models.CharField(max_length=255) isActive = models.BooleanField(default=True) def __str__(self): return self.name Then, I created this view to modify the isActive session when I call it: class CategoriesChangeActiveView(views.APIView): def post(self, request, format=None): try: categories = request.data.get('categories') for category in categories: category = Category.objects.get(id=category['id']) category.isActive = category['isActive'] category.save() except Exception as e: return Response({'error': 'Bad request'}, status=status.HTTP_400_BAD_REQUEST) return Response({'success': 'Active changed'}, status=status.HTTP_200_OK) Even when the format of my request is correct ( I debugged each line ) when it comes to the line category.isActive = category['isActive']it throws the error that'Category' object is not subscriptable`. I don't know why or how to fix it. I saw in the official documentation, on older StackOverflow questions that this is doable, but I don't understand why I can't. Can someone please suggest what I am doing wrong? Thank you -
How to improve search faster inside json file?
Here I have a sample JSON file with size more than 10MB(which will increase eventually). I have a python function which will try to match the entire json object from the json file and if matches it returns the next json object. This is my current implemention.It does the work but not sure it is the right way. I want some suggestions so that I can make this function much faster and scalable since this function is going to be used in several rest apis. { "all_checks": [ { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, { "key":"value", "key2": { "key": "val" } }, ] } python func import os import json from django.conf import settings def get_value(value): with open(os.path.join(settings.BASE_DIR, "my_json.json")) as file: data = json.load(file) # for i,v in enumerate(data["all_checks"]): # if json.dumps(value) == json.dumps(v): # return data["all_checks"][i + 1] ls = [data["all_checks"][i + 1] for i, v in enumerate(data["all_checks"]) \ if json.dumps(value) == json.dumps(v)] return dict(ls[0]) This function will be used in several apis -
502 bad gateway error pointing django model.py to other database
i'v setup a wagtail website. I altered models.py from my home-page model. In this models.py i try to acces a database running on another external server. Before i altered models.py the website was running fine, but after altering models.py i get a 502 bad-gateway error. I'm using Nging and gunicorn to serve the website. I followed this tutorial to set it up: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 I noticed this error in gunicorn: Dec 05 22:36:50 ip-172-31-30-62 gunicorn[1853]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Start request repeated too quickly. Dec 05 22:36:50 ip-172-31-30-62 systemd[1]: gunicorn.service: Failed with result 'exit-code'. This is my models.py for accessing the external database. (With help of @Richard Allen) class CasPage(Page): .... @property def plot(self): try: conn = psycopg2.connect( database="xxxx", user="xxxx", password="xxxx", host="xxxxxxxxxxxxx", port=xxxxx, ) cursor = conn.cursor() strquery = (f'''SELECT t.datum, t.grwaarde - LAG(t.grwaarde,1) OVER (ORDER BY datum) AS gebruiktgas FROM XXX''') data = pd.read_sql(strquery, conn) fig1 = go.Figure( data = data, layout=go.Layout( title="Gas-verbruik", yaxis_title="aantal M3") ) return plotly.plot(fig1, output_type='div', include_plotlyjs=False) except Exception as e: print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}") return None I can acces the external database (no … -
how to call kedro pipline or nodes in Django framework
I have to call Kedro nodes or pipelines in Django API, and need to use Kedro pipelines or nodes output as input in Django API. Not getting any solution. Please suggest some solution for this. How to call Kedro pipeline or nodes in Django APIs? -
how to create a time limit object in django
In this project I create some objects and I want to filter only objects that are created 120 seconds ago . I tried this Line : Model.objects.filter(start_time__gte=Now() - timedelta(minutes=2) , user = request.user , code = data['code']) But It does not work for me . any other solution? (and django timezone is set on Asia/china)