Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf_yasg AttributeError: 'function' object has no attribute 'with_ui'
Trying to documenting API using drf_yasg according to their documentation but I got this error "AttributeError: 'function' object has no attribute 'with_ui'" here is my code in urls.py schema_view = get_schema_view( openapi.Info( title="Blog API", default_version='v1', description="A sample API for learning DRF", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="riajulkashem@gmail.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] -
My django smtp g-suite settings don't seem to be working
I am having issues connecting Django to google g-suite account: The settings are currently as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'noreply@mydomain.com' EMAIL_HOST_PASSWORD = '16CharacterAppPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER Setting I have tried: Note, comma separated the different settings I have tried in all possible combination EMAIL_HOST = 'smtp.gmail.com', 'smtp-relay.gmail.com', 'mail.mydomain.com' EMAIL_USE_TLS = True, False EMAIL_USE_SSL = False, True EMAIL_PORT = 587, 25, 465 EMAIL_HOST_USER = 'noreply@mydomain.com' EMAIL_HOST_PASSWORD = '16CharacterAppPassword', 'mynormalpassword' Other things I have tried: LessSecure settings: On/Off App Password: Tried 2 two different ones just incase the first one messed up Contact G-Suite support: They had a look at the settings and everything is fine from their end Tried CaptchaLink Tried verifying last login attempt as 'it was me' so it won't block the IP Tried the following tutorial: G-Suite Smtp More details if it might help: Server: Pythonanywhere Domain: Google registered domain Python: 3.8 Django: 3.1.1 django-allauth: 0.42.0 Error msg I get when trying to send an email: SMTPAuthenticationError: Username and Password not accepted learn more at ... Follow the link provided and tried all the trouble shoot methods. -
Django, How to repeat a single field multiple time
Imagine i have a class = SkillModel in model.py where can specify their skills, so a user can have multiple skills but i have single field in table ,,,so how can i repeat this to gain multiple values(skills) from user. here is have preference factors where user will put there preference such as hark working or any xyz so how can i made a model where can take multiple values ...like multiple skills SO HOW CAN I MODIFY THIS -
Django FormModel Validation
Background: Using the Django Admin framework, I'd like to run validation to make sure a record doesn't exist with the same values before saving. Using a form, I added a check in the "clean" method. That validation works exactly as I expect. I am successfully able to add NEW records and catch duplicates. THE PROBLEM: The form is also validating the TabularInlines. Since the "parent page" isn't changed/updated it's not being sent and it's not showing up in the "cleaned_data." Thus, when it's not checking to see if the parent record exists, it throws a KeyError. IE, "hey, you said to check these parent variables and they aren't in here, wth?" Question: Using forms, is there an elegant way to check the ModelAdmin (parent page) and the TabularInLines (child page) separately to avoid the key error? OR do I just hard code checks for the different chunks if they exist? Different forms for different inlines? I'm providing some PSEUDO CODE below that should help outline the issue. DISCLAIMER: The actual structure is more complicated. Yes, I realize in this EXAMPLE, there is a better way to handle this. However, I'm looking to solve the form validation issue. ########## # Models … -
2 POST query in same template Django and form does not show up in html file
I don t understand where is my 2 issues... first issue is that when I want to create a new entry on clicking on submit, it launches a search (q) variable (which is in layout.html below). so I have this error: MultiValueDictKeyError at /new 'q' on line 32 which is on views.py (in def search : title = request.POST['q']): from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django import forms from django.urls import reverse from . import util class NewEntryForm(forms.Form): title = forms.CharField(label="Entry title", widget=forms.TextInput(attrs={'class' : 'form-control col-md-8 col-lg-8'})) content = forms.CharField(widget=forms.Textarea(attrs={'class' : 'form-control col-md-8 col-lg-8', 'rows' : 10})) edit = forms.BooleanField(initial=False, widget=forms.HiddenInput(), required=False) def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def greet(request, title): if util.get_entry(title): return render(request, "encyclopedia/wiki.html", { "entry": util.get_entry(title), "title": title}) return render(request, "encyclopedia/404.html", { "entry": title}) def search(request): value = request.GET.get('q', '') if request.method == "POST": title = request.POST['q'] if util.get_entry(title): return render(request, "encyclopedia/wiki.html", { "entry": util.get_entry(title), "title": title}) if util.get_partial_entry(title): return render(request, "encyclopedia/search.html", { "entries": util.get_partial_entry(title) }) return render(request, "encyclopedia/404.html", { "entry": title}) return render(request,"encyclopedia/new.html") def new(request): if request.method == "POST": form1 = NewEntryForm(request.POST) if form1.is_valid(): title = form1.cleaned_data["title"] content = form1.cleaned_data["content"] if (util.get_entry(title) is None or form1.cleaned_data["edit"] is True): util.save_entry(title, … -
How to do a get request inside a Django Channels consumer connect method?
I'm trying to do a get request for a seperate django CRUD API app inside a Django Channels app connect method So inside the consumers.py I'm doing this class AssistantConsumer(AsyncWebsocketConsumer): async def connect(self): self.commands = requests.get('http://localhost:8000/api/commands') print(self.commands) Doing this results in the websocket getting stuck on WebSocket HANDSHAKING /ws/assistant/user/ [127.0.0.1:64374] Can anyone tell me why? The API is working on it's own, I'm posting to it from React, which also connects to the websocket. All that is working - I just need to fetch some data from the database in the consumer. Couldn't find anything anywhere about this situation. -
Sorting by Value of Object in Many to Many Field Django
I need some sorting help with django querysets that involve many to many relationships. I'm making a language-based conversation app and I've just finished writing a query that returns a queryset named possibleMatches containing the users someone might want to chat with. However, now I want to sort those users by the level of a specific language they have in their user languages table. I believe the solution lies in using Django's annotate() function for sorting querysets, but I've been having trouble finding the exact syntax to do it. I've also tried using filtered relations, but when running it, I got an error saying that filtered relations don't support nested conditions. Each user has an id and a list of user languages represented by a many to many field. Each user language corresponds to one user, one language, and one level. For clarity, here are my models: class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Language(models.Model): id = models.IntegerField(primary_key=True, choices=SUPPORTED_LANGUAGES) class UserLanguage(models.Model): language = models.ForeignKey(Language, on_delete=models.DO_NOTHING) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='languages', on_delete=models.DO_NOTHING) level = models.IntegerField(choices=LANGUAGE_PROFICIENCIES, null=False, blank=False) Anyway, I want to sort the users in possibleMatches in ascending order based on their level of language 1. This is the code and … -
How to add username in url django
New to Django, this is a simple blog post app. How do i include the name of a post's author in the url? urlpatterns = [ path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), ] post model class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank="true") content = models.CharField(max_length=400) views.py class PostDetailView(DetailView): model = Post -
AP Scheduler running twice
i have a django app that is live running with an nginx server and wsgi, i created some interval jobs that are meant to call some functions inside my app after some seconds. But for some weird reason the scheduler keeps getting executed twice at an instance, tho this does not happen everytime, sometimes it behaves well and other times it's executed twice. I want to know whether the issue is with nginx, gunicorn or something else. this is a sample of the job i created. Thank you from apscheduler.schedulers.background import BackgroundScheduler from .update_api import UpdateApi from datetime import datetime def start(): scheduler = BackgroundScheduler() scheduler.add_job(UpdateApi().end_today_game, 'interval', seconds=10) scheduler.add_job(UpdateApi().start_today_game, 'interval', seconds=10) scheduler.add_job(UpdateApi().alter_slip, 'interval', seconds=10) scheduler.add_job(UpdateApi().add_raffle_members, 'interval', seconds=10) scheduler.add_job(UpdateApi().end_raffle_draw, 'interval', seconds=10) scheduler.add_job(UpdateApi().init_game_setting, 'interval', hours=3) scheduler.add_job(UpdateApi().check_payments, 'interval', seconds=15) scheduler.add_job(UpdateApi().remove_limit, 'interval', hours=24, start_date='2020-07-15 00:00:00') scheduler.start()``` -
super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'attrs'
forms.py from django import forms from .models import Student class StudentRegistraion(forms.ModelForm): class Meta: model = Student fields = ['name', 'roll_num', 'email', 'password'] widgets = { 'name': forms.CharField(attrs={'class': 'form-control'}), 'roll_num': forms.IntegerField(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'}), } -
geodjango, leaflet document.getElementById(...) is null error
Im setting up a geodjango map project, and a js script to load features info, from elements on a leaflet map, when i click a feature only gives me back one value, the first, all the others appears to be null, the django serializer gives all the info, but the getElementById doesn't seem to recognize it code var map = L.map('map', { zoomControl:false, //dragging: false, doubleClickZoom: false }).setView([-23.50521, -69.362164],7); L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{ maxZoom: 10, subdomains:['mt0','mt1','mt2','mt3'] }).addTo(map); map.createPane("contorno") map.getPane('contorno').style.zIndex = 450; var cont = new L.GeoJSON.AJAX("{% url 'ser_reg' %}",{ pane: "contorno", style: { weight: 3, color: 'white', fillColor: "white", fillOpacity: 0.05, }, onEachFeature: function(feature, layer){ layer.bindPopup('<table style="width:450px;font-size:14px;"><tr><th scope="row">PROVINCIA</th><td>'+feature.properties.nom_prov+'</td></tr>'+ '<tr><th scope="row">COMUNA</th><td>'+feature.properties.nom_com+'</td></tr>', {minWidth:450}); }}).addTo(map); function style(feature){ if (feature.properties.nombre_evento){ return{ pane:"panegeojson", radius: 8, fillColor: "red", color: "#000", weight: 2, opacity: 1, fillOpacity: 1 }; } if (feature.properties.nombre_ini){ return{ pane:"panegeojson", radius: 8, fillColor: "#00FF00", color: "#000", weight: 2, opacity: 1, fillOpacity: 1 }; } if (feature.properties.denuncia){ return{ pane:"panegeojson", radius: 8, fillColor: "yellow", color: "#000", weight: 2, opacity: 1, fillOpacity: 1 }; } } var ultimoClick; function zoomToFeature(e) { if(ultimoClick){ sit_amb.resetStyle(ultimoClick); } var layer = e.target; layer.setStyle({ pane:"geojson", weight: 3, color: 'yellow', dashArray: '3', fillOpacity: 0.5 }); if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) { layer.bringToFront(); } ultimoClick = … -
Django Exchange
i'm trying to develop an exchange application for a project using djongo. When I try to add a new Order this is what django returns: image of the error The code I wrote is: from django.db import models from django.contrib.auth.models import User from djongo.models.fields import ObjectIdField class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Order(models.Model): _id = ObjectIdField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now_add=True) price = models.FloatField(default=0.0) quantity = models.FloatField(default=0.0) Sorry for the question but I can't understand why it shows me that error, when I try to add a new Profile everything works, but when I try to add a new Order it doesn't work. -
After migrate command, Django automatically creates sqlite3 but doesn't automatically create postgresql database
I'm using Windows 10 and Visual Studio Code IDE with python 3.8.5 . I'm developing a web app called tasksplanner and I want to use django for my backend and postgresql v12 for my database. By default django comes with sqlite3. In the file settings.py of my django project (called backend) by default I find this code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } If on the terminal I do: python manage.py migrate or python manage.py makemigrations tasksplanner django automatically creates an sqlite3 database called db.sqlite3 inside the backend project folder However, I want to use postgresql. So, following the instructions in here I modified my settings.py to look like: DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'tasks_planner_db.mkd', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': '127.0.0.1', 'PORT': '5432', } } And I'm getting the following error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: database "tasks-planner-db.mkd" does not exist My questions are: Why isn't django creating the postgresql database automatically like it did with sqlite3? What do I do to make it create the postgresql database automatically? Or do I have to create … -
Can we enter html code in a field in models in django?
I am making a small static website in which I have a template in which I tend to show the privacy policy terms of usage etc. I currently don't have any matter for it and tend to add it in future after deploying the site on server. I wanted to know that if I can in future add the matter on that page through a model i.e I create a model with two fields privacy policy , terms and in and pass it to the template as context in views.py . But I have a concern that the fields will have several headings which I will have to display in bold , so is there any way that I can pass html tags in model field and when I render it in my template as {{privacy}} the part I want in bold or any other style comes as that style. -
Heroku with Django migrations won't work for field with choices
Locally the code runs fine, in the Donation model I have the field status. When submitting to Heroku, however, I can't access the pages that use the Donation model (not even the admin page). This is the error shown when on Heroku: column website_donation.status does not exist LINE 1: ...tity", "website_donation"."volunteer_delivering", "website_d... ^ Request Method: GET Request URL: https://**********.herokuapp.com/admin/website/donation/ Django Version: 3.1.1 Exception Type: ProgrammingError Exception Value: column website_donation.status does not exist LINE 1: ...tity", "website_donation"."volunteer_delivering", "website_d... This is the model in models.py: class Donation(models.Model): STATUS = ( ('S', 'submitted'), ('D', 'delivered'), ('C', 'canceled'), ) volunteer = models.ForeignKey(Volunteer, on_delete=models.CASCADE, related_name="donations") establishment = models.ForeignKey(Establishment, on_delete=models.CASCADE, related_name="donations") quantity = models.PositiveIntegerField() volunteer_delivering = models.BooleanField() status = models.CharField(max_length=1, null=False, choices=STATUS, default='S') submission_time = models.DateTimeField(auto_now_add=True) estimated_time = models.DateTimeField() delivered_time = models.DateTimeField(null=True) I already tried running python manage.py makemigrations then python manage.py migrate but it didn't solve the issue. This is the Donation model in the current migration file in the Heroku deployment: migrations.CreateModel( name='Donation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('quantity', models.PositiveIntegerField()), ('volunteer_delivering', models.BooleanField()), ('status', models.CharField(choices=[('S', 'submitted'), ('D', 'delivered'), ('C', 'canceled')], default='S', max_length=1)), ('submission_time', models.DateTimeField(auto_now_add=True)), ('estimated_time', models.DateTimeField()), ('delivered_time', models.DateTimeField(null=True)), ('establishment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='donations', to='website.Establishment')), ('volunteer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='donations', to='website.Volunteer')), ], ), -
This site can’t be reached - Django
I am getting This site can’t be reached and pop up window python quit unexpectedly error when trying to run Django project. It is only one particular project getting me this error any other project works perfectly. So far I tried to all the possible solution you might think of such as running it as http://127.0.0.1:8000/, http://0.0.0.0:8000/, or http://localhost:8000/, changed ALLOWED_HOST = ['*'] and ['127.0.0.1'] but none of them seem like work here is my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bl*go6y!3xx3#h2aln(3!^$xq%l9vgw-z@^+up-$$@5p%lm#@k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] PROJECT_APPS = [ 'users', 'rooms', 'core', 'reviews', 'reservations', 'lists', 'conversations', ] THIRD_PARTY_APPS = [ 'django_countries',"django_seed"] INSTALLED_APPS = DJANGO_APPS + PROJECT_APPS + THIRD_PARTY_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', … -
Error when deleting a post with file stored on AWS S3 - NotImplementedError: This backend doesn't support absolute paths
I've deployed a small application to Heroku with AWS S3 configured to store post images. I've added two functions to delete image files whenever a post object is deleted. The functions work fine in a local dev environment. the images files get deleted if I delete a post from the admin screen. But after deployment, when I go to delete a post from admin, I get this error message in the logs: NotImplementedError: This backend doesn't support absolute paths After I search SO, I think this issue is caused by the last two lines in this function but not sure why. when I remove .path the function doesn't work in local development @receiver(models.signals.post_delete, sender=Post) def delete_image(sender, instance, **kwargs): """ Deletes image on post_delete. """ if instance.image: if os.path.isfile(instance.image.path): os.remove(instance.image.path) Here is the other function to delete image file if the post is updated: @receiver(models.signals.pre_save, sender=Post) def delete_image_on_change(sender, instance, **kwargs): """ Deletes old image file when Image object is updated with new file. """ if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).image except sender.DoesNotExist: return False new_file = instance.image if not old_file == new_file: if os.path.isfile(old_file.path): os.remove(old_file.path) This is the model: class Post(TimeStampedUUIDModel): creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") title = … -
More elegant way to replace all field equal to Null by the default value in django model objects
I'am looking on a more elegant way to replace all field of my model objects which are equals to Null by the default value defined in the model. Here is my current code : for buy in Buy.objects.all(): for f in Buy._meta.get_fields(): field = eval("buy." + f.name) if field is None: field = Buy._meta.get_field(f.name).get_default() buy.save() But i find the use of eval not elegant. If anyone have better way to do that Regards -
Django edit profile not saving
I have pre-filled forms for my user (the django user + my profile one with more informations) that just doesn't want to be saved. No error message, no redirection, I press the button "edit", and then... same page, with the modifications already written. But the database isn't changed. So, here is the code : forms.py : class UpdateUser(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('email', 'username') def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('Cette adresse email est déjà utilisée, veuillez en indiquer une autre') return email class UpdateProfil(forms.ModelForm): class Meta: model = Profil fields = ("society", "thingA", "thingB", "thingC", "thingD", "thingE") views.py : @login_required def edit_profile(request): user = User.objects.get(username = request.user) profile = Profil.objects.get(user = user) if request.method == 'POST': form1 = UpdateUser(request.POST, instance=user) form2 = UpdateProfil(request.POST, instance=profile) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() return HttpResponseRedirect('Register/view_profile.html') else: form1 = UpdateUser(initial={"email": user.email, "username": user.username}) form2 = UpdateProfil(initial={"society": profile.society, "thingA": profile.thingA, "thingB": profile.thingB, "thingC": profile.thingC, "thingD": profile.thingD, "thingE": profile.thingE}) return render(request, 'Register/edit_profile.html', locals()) and the template: <form action="" method="post"> {% csrf_token %} <p>Email : </p>{{ form1.email }} <p>Nom d'utilisateur : </p>{{ form1.username }} <p>Société (entreprise, association, établissement...") :</p> {{ form2.society }} <p>Si … -
Is it possible to add a Button to a Wagtail Settings page?
I am trying to customize a settings page so it has a button that I will assign to a certain action. (Let's assume for now I just want to log something into the console). Ideally it would be of something like this: @register_setting class ActionTriggeringSetting(BaseSetting): button = models.ButtonField( action=myLoggingFunc, help_text='Click here to log "Hello World" to the console' ) I tried looking into the site settings but found nothing really helpful there. Does anybody know if something of the sort exists? Thank you -
search form always called
There is an error in def search : The view encyclopedia.views.search didn't return an HttpResponse object. It returned None instead. Only when I call a create new Page. I don't understand why? My layout template with search bar: <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'new' %}">Create New Page</a> </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> My new template: {% extends "encyclopedia/layout.html" %} {% block title %} New Entry {% endblock %} {% block body %} <h1>New entry</h1> <form action="{% url 'new' %}" method="POST"> {% csrf_token %} {{ form }} <input type="submit"> </form> {% endblock %} views.py: def search(request): if request.method == "POST": title = request.POST['q'] if util.get_entry(title): return render(request, "encyclopedia/wiki.html", { "entry": util.get_entry(title), "title": title}) if util.get_partial_entry(title): return render(request, "encyclopedia/search.html", { "entries": util.get_partial_entry(title) }) return render(request, "encyclopedia/404.html", { "entry": title}) def new(request, method="GET"): return render(request, "encyclopedia/new.html", { "form": NewForm() }) I don t understand why I have only the error on new page … -
Django JsonResponse converts numbers to string
I'm using JsonResponse(status=200, data=<python_dict_with_data>) to return from my Django backend API. However, upon inspecting the result of this, all numbers get converted to strings. This creates a problem in the frontend receiving this response because now I have to parse them as integers to do formatting and lightweight calculations. Is there a way to prevent this conversion when returned from Django? Or is there a way the response is parsed correctly in the frontend? I'm using Axios library in React in the frontend. -
Im getting a 'NoReverseMatch' error during template rendering
Currently reading the Python Crash Course by Eric Matthes and im trying to code a simple learning lo using python and django , but i keep getting an error when i try to enter the topics url . The error seems to come from the base.html(the template) , it says that learning_logs is not a registered namespace , even tho i have written it as a variable named app_name and have included it in the urls. Heres the code: main urls.py: from django.contrib import admin from django.urls import path , include , re_path app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('' , include(("learning_logs.urls", app_name ) )) ] urls.py: from django.urls import path , re_path from . import views app_name = 'learning_logs' urlpatterns = [ #Home page path('', views.index, name='index'), path('topics/', views.topics , name='topics'), re_path(r'^topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'), re_path(r'^new_topic/$' , views.new_topic , name = 'new_topic'), re_path(r'^new_entry/(?P<topic_id>\d+)/$' , views.new_entry , name = 'new_entry'), ] base.html: <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> <a href="{% url 'learning_logs:topics' %}">Topics</a> </p> {% block content %} {% endblock content %} Error: Pic -
Django Taggit "Similar Objects" additional filter
My website is going to have data that has expiration date in the model field, my view will only show the active one by using filter list = Model.objects.filter(deadline__gte =timezone.now()) in the detail views of the model, i'm going to show the related post using django taggit with taggable manager for the models field and 'similar_objects' from the API detail = Model.objects.get(slug=slug, pk=pk) related = detail.tags.similar_objects()[:5] the only problem is that the 'related' will return a list instead of queryset (i can't filter it using django) and it's going to show the expired post too. My question is if there is a way i can show my related post and filter it so that it only shows the one that aren't expired -
What role does Redis serve in Django Channels
Recently I've been using django channels makes its support websocket protocol, I use a microservice way, other components through connection django channels, but I have to write a Consumer class for each connection for receiving and handling, for example class Consumer(AsyncWebsocketConsumer):, which still use the redis, pointed out that this part is the official document as a channel layer storage, so it is as a message queue, the cache or other commonly used functions exist? I write to find out if there is a Consumer for each connection, and whether I can think of it as acting as a message queue. However, I have not found relevant materials to support my point of view. Could you please tell me whether my understanding is correct or not? I sincerely hope that you can provide relevant materials for reference whether it is correct or not.