Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The current path, accounts/<int:id>/, didn’t match any of these ( for django application)
This is a book exchange system I'm trying to create. The challlenge I'm having is trying to redirect the user to a dynamic url consisting of there personal details after log in. Here is my urs.py for my project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('exchange/',include('exchange.urls')), path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] Here is my urs.py for my app from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('', views.base, name='base'), path('register/', views.register_request, name='register'), path('accounts/<int:id>/', views.user_view, name='userview'), #path('login/', views.login_request, name='login'), path('login/', auth_views.LoginView.as_view(template_name='exchange/login.html', redirect_field_name='user_view')), ] Here is my views.py for my app from django.shortcuts import render, redirect from exchange.forms import user_login_form, user_register_form from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.contrib import messages # Create your views here. #Base index view def base(request): return render(request, 'exchange/base.html',{}) #registration view def register_request(request): if request.method=='POST': form = user_register_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('login') else: messages.error(request, 'Invalid form') render(request, 'exchange/register.html',{'form':form}) else: form = user_register_form() return render(request, 'exchange/register.html',{'form':form}) #login view def login_request(request): if request.method=='POST': form = user_login_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user … -
I want to build table like this format in datatable
I want to build table like this format in datatable. enter image description here -
Django - models field join to django-table2
I have a django-tables2 table created with data from model Data. Model Data is linked to model Kategorie with "jmeno" (name of Category). And I would like to link field "jmeno" to my table PuDetailTable as category field. Table definition: class PuDetailTable(tables.Table): class Meta: model = Data fields = ("datum", "doklad", "cislo", "popis", "amount", "partner", "zakazka", "stredisko", "ucet", "company", "category") sequence = ("datum", "doklad", "cislo", "popis", "partner", "zakazka", "stredisko", "ucet", "category", "company", "amount") attrs = {'a': {"class": "a2"}, 'th': {'class': 'headline'}} ... category = tables.Column(verbose_name="Kategorie", accessor="ucet__mustek__kategorie__jmeno", attrs = {"td": {'class': 'text-center'}}) Models: class Data(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE, null=True, blank=True) class Ucty(models.Model): cislo = models.IntegerField("Účet", blank=True, null=True) class Mustek(models.Model): ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE) kategorie = models.ForeignKey(Kategorie, on_delete=models.CASCADE) class Kategorie(models.Model): jmeno = models.CharField("Kategorie", max_length=20, blank=True, null=True) And I need help with correct accessor to get "jmeno" (category name) to the table as the accessor accessor="ucet__mustek__kategorie__jmeno" is not working. I have tried different variants like accessor="ucet_ucty__mustek__kategorie__jmeno", but this is also not working. So any idea what should be the correct accessor? -
Quick method to view formatted html in a variable or property during debugging
I am debugging a Django app. During debugging, I've set a breakpoint so I can see a rendered html string stored in a variable. The variable has a property called content and within is a html string which is enclose din b''. I know I can copy the value from the debugger and open a text window and paste it in. Then I can formatted so I can read it. This is time-consuming though and I wonder if there is a simple trick or alternative that will allow me to quickly view the formatted html? -
how to access chield model from parent model (using Multi-table inheritance)
I have this model from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) how to accsees serves_pizza from parent moddel (Place) my use case , i need to access serves_pizza from parent serilizer (PlaceSerializer) class PlaceSerializer(serializers.ModelSerializer): serves_pizza = serializers.SerializerMethodField() class Meta: model = Place fields = '__all__' def get_serves_pizza (self, obj): serves_pizza = Restaurant.objects.get(**???**) return serves_pizza -
How to push data in a model whose one column is a forign key Django Rest Framework?
I'm trying to assign data against specific user using DRF but getting some strange errors. I want your help/ guidance. I'm a beginner but I searched this problem a lot but not able to find any solution. model.py class Category(TrackingModels): name =models.CharField(default='Learning',max_length=150,unique=True,null=False) person=models.ForeignKey(to=User,on_delete=models.CASCADE) def __str__(self): return self.name serializer.py class CategorySerializer(ModelSerializer): person = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model=Category fields=('id','name','person') views.py class CategoryAPIView(CreateAPIView): serializer_class=CategorySerializer permission_classes=(IsAuthenticated,) def post(self,request): data={ "person":request.user.id, "name":request.data.get('category') } serializer=CategorySerializer(data=data) if serializer.is_valid(): serializer.save() return Response({"message":"Category is created sucessfully!"},status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) Here is Postman request: Asking help here is the only option for me now. I will really appreciate your answers. regards, I followed this solution but that didn't fixed. I searched a lot on medium and other platforms but all in vein. -
how to send frontend error to a django view for getting log?
I want to implement logging system with django but in my front i have some errors: $.ajax({ method: 'post', processData: false, contentType: false, cache: false, data: data, enctype: 'multipart/form-data', url: endpoint, success: function (response) { if (response.track_code !== null) { redirectToRRRDetailPage(response.track_code); } if (response.general_error) { showErrorMessage(response.general_error); hideGeneralLoader(); } else { showFieldErrorMessages(response.input_errors); hideGeneralLoader(); } }, error: function (error) { showErrorMessage("خطایی در ارتباط با سرور به وجود آماده است. لطفا جهت بررسی با پشتیبان تماس حاصل فرمائید.") hideGeneralLoader(); } }); } how can i send this erros detail to an end point for logging with this error detail? -
Django How to Load Static and Media files
I am unable to load both static and media images at the same time. My static/images/ folder contains a default profile picture and my media folder contains images uploaded by users. Currently, i am getting the image from the user model and my media folder is working where any uploaded profile images from a user is displayed correctly. However, loading the default profile picture does not work. I have tried setting the default for the imagefield to include the static/images directory and this still does not work. I had a look in the admin panel and found that it returns "http://127.0.0.1:8000/media/static/images/default_profile_picture.jpg". What should happen is something like "http://127.0.0.1:8000/static/images/default_profile_picture.jpg". When loading the default picture it should go straight to the static folder then the images folder and if it is not looking for the default profile picture, it should look in the media folder (which is what it is currently doing). However, it is going straight to the media folder looking for the default profile picture. Any ideas on how to go straight to the static folder to look for the default profile picture whilst also be able to view user uploaded images in the media folder? It is also important … -
Django python: no such column:
I used a form to create a django post with a single "text" field. Then I modified the post model. Now there are three forms "author", "body" and "title". Also changed the mentions in home.html and other files. Logically, it should work, but it gives an error in the file home.html there is no such column: pages_posts.title error in line 5 Some files from my project: views.py from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views.generic import TemplateView, CreateView, DetailView from django.views.generic import ListView from .models import Posts class HomePageView(ListView): model = Posts template_name = 'home.html' # post_list = Posts.title # context_object_name = 'all_posts_list' class AboutPageView(TemplateView): template_name = 'about.html' class SignUpView(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class NewPostUpView(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class BlogDetailView(DetailView): model = Posts template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Posts template_name = 'post_new.html' fields = ['title', 'author', 'body'] models.py from django.db import models class Posts(models.Model): title = models.CharField(max_length=200, default='False') author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() def __str__(self): return self.title class Meta: verbose_name = 'Пост' verbose_name_plural = 'Посты' home.html {% extends 'base.html' %} {% block content %} {% for post in object_list %} … -
How to count values for a key inside a dictionary
i´m new here and in python. I think my problem is very simple, but I can´t solve it. I have a form with a checkbox. I send 4 selected options, and the querydict recognizes them. But when I ask it to print the 4 values, it only brings me the last one. This is my html: I send the form and it goes to def dietPlan in views.py: def dietPlan(request): # Obtengo los datos que vienen del formulario querydict=request.POST print((querydict)) print((querydict['opcionesCena'])) print(len(querydict['opcionesCena'])) But, the prints are: <QueryDict: {'csrfmiddlewaretoken': ['qNAKsaNlPOO3UY7X76sNy1bEuidxd4WDvUlwJXD6BYxA1JTkyra0A86eYMHJfJ3B'], 'opcionesCena': ['AlimentoID352', 'AlimentoID356', 'AlimentoID360', 'AlimentoID364']}> AlimentoID364 13 Only recognize AlimentoID364 (the last one of the 4) and it takes the number of characters in AlimentoID364. I need to count how many values are for the key 'opcionesCena': if there are 4, or 5, or whatever. Could you help me? Thanks in advance -
Schedule emails to be sent based on the time provided by the user django
I am trying to schedule emails to send based on the date and time user will provide. I looked into celery beat but I didn't find any thing that can help with dynamic time. I also looked into this post: Gmail Schedule Send Email in Django Can anyone please guide me on how can I send schedule emails based on the time user will provide to the system instead of checking into the system again and again like every five minutes or so to send email. -
Google OAUTH 2.0 doesn't show anything in Microsoft Edge (works fine in Chrome)
When clicking on the Continue With Google button, a popup appears (on my website that I created using Django in Python) as expected in Google Chrome asking which account to continue with etc... By doing the same thing in Microsoft Edge, the popup is blank, there is no content. I'm not sure if it's a problem with my code, my OAUTH account or Microsoft Edge itself. This is the popup in Google Chrome (working as normally) This is the popup in Microsoft Edge (not working at all) I expect the top image to be happening in both browsers. Does anyone have any idea why this isn't working in Microsoft Edge? -
How django process the model fields into form inputs
I would like to understand the lifecycle of how Django identifies my model fields and render them as form fields with the whole metadata that the field needs it to process the user input and also the display of that field. -
i tried to clone a django project from github,i have problem with installing requirements.txt ,when i do this command :pip install -r requirements.txt
while executing this command on terminal :"pip install -r requirements.txt" i get this error: error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [25 lines of output] C:\Users\faouz\OneDrive\Bureau\essalmigarage.venv\Lib\site-packages\setuptools\config\setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) running egg_info creating C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info writing C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
Email Verification Fail in Django webapp hosted on Elastic Beanstalk with nginx
I was making a web app on Django. I tried to send an email verification link to any new user who registers on my website. The thing works fine when I am hosting it on localhost but not upon hosting on AWS Elastic Beanstalk. The verification link generated fine. And I found a very similar issue. Email Verification Fail in Django webapp hosted on Elastic Beanstalk That answers to the case of appach. But I use nginx instead of appach. settings.py ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True LOGIN_REDIRECT_URL = 'timeline:index' ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login' ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_SUBJECT_PREFIX = '' ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' ACCOUNT_UNIQUE_EMAIL = True DEFAULT_FROM_EMAIL = 'tnajun@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ACCOUNT_EMAIL_VERIFICATION = "mandatory" DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' urls.py from django.contrib import admin from django.urls import path, re_path, include from django.contrib.staticfiles.urls import static from . import settings from django.views.generic import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('', include('timeline.urls')), path('contact/', include('contact_form.urls')), path('accounts/email/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/inactive/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/password/change/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/confirm-email/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/', include('allauth.urls')), path('accounts/', include('accounts.urls')), re_path(r'^accounts/confirm-email/[^/]+/', RedirectView.as_view(pattern_name='timeline:index'), kwargs=None), ] python3.7 Django==3.2.4 django-allauth==0.44.0 I tied ACCOUNT_EMAIL_VERIFICATION = "none" on EB and it works fine but that is not what I want. -
Permissions to edit only one field in a Model. Django
I am developing an app which will have different types of users, and the objective is that in a specific Model, it is completed in a community way. Example: 3 types of users: UserTotal, UserParcial, UserBase. Class object name ModelFamily, has 10 fields defined (int,char,date) I need all users to be able to see the class in the admin panel, but depending on which one I can only edit some fields. How could I solve it? I don't have views at the moment, I'm managing everything from the Django Admin panel. Thank you very much for your time! I tried to change the permissions from admin but it is at Object level, not object field. -
redirect Django not working blank response
I tried using reverse, no issues there are in django and when i see the response it is simply blank from django.shortcuts import render from django.http import HttpRequest from django.http import HttpResponse from django.http import JsonResponse from django.shortcuts import redirect def Aviation (request): return render(request, 'Aviation/Aviationtest.html') def SendInformations (request): #a lot of uninteresting code return redirect(reverse("Aviation")) here's my urls.py file from django.urls import path from . import views urlpatterns = [ path("", views.Aviation, name="Aviation"), path("let_me_send_informations", views.let_me_send_informations, name="let_me_send_informations"), path("Informations", views.Informations, name="Informations"), path("SendInformations", views.SendInformations, name="SendInformations") ] I tried using reverse, the complete path, not using reverse and i am sure the directories are set well -
why is django-dbbackup in .psql.bin format? Can I decode it?
I just installed django-dbbackup.. All working as per the doc (linked). One thing slightly puzzles me. Why does it dump into a binary format which I don't know how to read? (.psql.bin). Is there a Postgres command to de-bin it? I found by Googling, that it's possible to get a text dump by adding to settings.py DBBACKUP_CONNECTOR_MAPPING = { 'django.db.backends.postgresql': 'dbbackup.db.postgresql.PgDumpConnector', } This is about 4x bigger as output, but after gzip'ping the file it's about 0.7x the size of the binary and after bzip2, about 0.5x However, this appears to be undocumented, and I don't like using undocumented for backups! (same reason I want to be able to look at the file :-) -
Loading static files in template(background-image: url())-Django
I'm building a template and I want to set an image as background with "background-image: url()". Can anyone help me how can I load the image in the url()? Directory: HTML file(template): <div class="card-inner card-started active" id="home-card"> <!-- Started Background --> <div class="slide" style="background: url('/static/images/bg.jpg');"></div> <!--Where background is gonna load--> <div class="centrize full-width"> <div class="vertical-center"> <!-- Started titles --> <div class="title"><span>Daniel</span>Johansson</div> <div class="subtitle"> I am <div class="typing-title"> <p>a <strong>web developer.</strong></p> <p>a <strong>blogger.</strong></p> <p>a <strong>freelancer.</strong></p> <p>a <strong>photographer.</strong></p> </div> <span class="typed-title"></span> </div> </div> </div> </div> CSS file(layout.html): .card-inner.card-started { text-align: center; } .card-inner.card-started .slide { position: absolute; overflow: hidden; left: 0; top: 0; width: 100%; height: 100%; background-color: #262628; background-repeat: no-repeat; background-position: center center; background-size: cover; } .card-inner.card-started .slide:after { content: ''; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: #181818; opacity: 0.6; } Setting.py: STATIC_URL = 'static/' STATICFILES_DIR = [ path.join(BASE_DIR, 'static'), ] STATIC_ROOT = path.join(BASE_DIR, 'static') homepage_app/urls.py: urlpatterns = [ path('', views.home) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) POV: This code had a pre loader that I deleted It, I thought that maybe the problem is there. pre loader HTML: <div class="preloader"> <div class="centrize full-width"> <div class="vertical-center"> <div class="spinner"> <div class="double-bounce1"></div> <div class="double-bounce2"></div> </div> </div> </div> </div> I tried … -
I'm struggling to resolve 2 seemingly ireconsilable dependancy clashes
I have 2 libraries which a code base I'm trying to load and run locally use: django-storages==1.10.1 django-pyodbc-azure==2.1.0.0 The problem I have is I either get this error: django-storages 1.13.2 requires Django>=3.2, but you have django 2.2 which is incompatible., or this one if I try to resolve the first error: django-pyodbc-azure 2.1.0.0 requires Django<2.2,>=2.1.0, but you have django 2.2.1 which is incompatible. Resolving one causes a upgrade or downgrade of Django which triggers either one or the other of the above errors. How do I resolve this? Thanks! -
How to count posts that each hashtag has in django queryset
class Post(models.Model): post_uuid=models.UUIDField( default=uuid.uuid4, editable=False) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_language = models.BooleanField(default=True) description = models.CharField(max_length=400, null=True, blank=True) hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return '{}'.format(self.post.id) class HashtagName(models.Model): Hashtagname = models.UUIDField(default=uuid.uuid4, editable=False) hashtag_name = models.CharField(max_length=150, null=False, unique=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return self.hashtag_name class Hashtag(models.Model): hashtag_uuid = models.UUIDField(default=uuid.uuid4, editable=False) tag_name = models.ForeignKey(HashtagName,on_delete=models.CASCADE) posts = models.ForeignKey(Post, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return self.hashtag_uuid I have these classes. Im making one api to get the list of trending hashtag What im trying to do is when someone type #planet And i have list of these below hashtag #planetearth Used in 7 posts #planetjuypiter used in 5 posts #planetmercury used in 3 posts Etc That starts with the keyword i have passed from frontend. So i want to get the list of top 10 hashtag that starts with the keyword I passed from front end and based on in how many posts they are used. -
Django not parsing Unity WWWForm multipart/form-data
I have a django backend (3.2.15) with django rest framework (3.13.1) and I have an endpoint where I post a string and a file. When I use postman, it works fine, but using Unity WWWForm library, it doesn't. The problem that I see, is that when I receive the post from Unity, for some reason, is not parse correctly, for instance, if I send only the string value, the request.POST value is set as <QueryDict: {'personal_account': ['13123123123\r\n--e2FxgWvU1dzZvTibOpwyxx07RvZnbNzj2BhnBpUY--\r\n']}> instead of <QueryDict: {'personal_account': ['13123123123']}> as it works with postman. When I include the file in the form, request.POST and request.FILE are simply empty. Here is my code: Unity: List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add(new MultipartFormFileSection("file", file, AccountsManager.Instance.uiTransferNotificationsBuy.fileName, "image/jpeg")); formData.Add(new MultipartFormDataSection("string", string)); UnityWebRequest www = UnityWebRequest.Post(url, formData); byte[] boundary = UnityWebRequest.GenerateBoundary(); www.SetRequestHeader("Content-Type", "multipart/form-data; boundary = " + System.Text.Encoding.UTF8.GetString(boundary)); www.SetRequestHeader("x-api-key", apiKey); www.SetRequestHeader("Authorization", PlayerPrefs.GetString("IdToken")); www.downloadHandler = new DownloadHandlerBuffer(); yield return www.SendWebRequest(); Django is a default create method from ModelViewSet Couldn't find any reported issues in both projects. Any idea what might be the issue? Thanks -
I need to make this time task for my advertisement website
I have created_at in django table. How can I gather a week with recent datetime. I need to do it + 7 days. Just tell me how can I do it. I need to get 7 days -
GSMA mobile money api integration for mobile payment
I want to integrate GSMA mobile money with my python code. Didn't find any github repo for the same, also there is no SDK for python on GSMA developer portal. Can anyone help ? -
Permisos para editar unicamente un campo en un Modelo. Django
estoy desarrollando una app la cual va a tener distintos tipos de usuarios, y el objetivo es que en un Modelo puntual, se complete de manera comunitaria. Ej: Tengo una app que tiene creados 3 tipos de usuarios: UsuarioTotal, UsuarioParcial, UsuarioMinimo. Una clase que es ModeloFamilia, que consta de 10 campos (int, char, date, etc) Puedo hacer que UsuarioParcial vea todo el modelo, pero unicamente pueda editar los 4 primeros campos del mismo? UsuarioTotal pueda ver/editar todo. Y UsuarioMinimo, solo pueda editar 1 campo que coincide con uno de los de UsuarioParcial? Como podria resolverlo? de momento no tengo vistas, estoy manejando todo desde el panel de Admin de Django. Muchas gracias por su tiempo! Probé cambiar los permisos desde admin pero es a nivel Objeto, no campo de objeto.