Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the users download directory
I'm on my linux server and I want to save something into the downloads folder from the user which is using the website, how do I get the downloads path from the user, when I try to save something in the downloads folder a folder named "downloads" gets created in my root directory, and not in my computers downloads folder. -
How to update user as an admin in djoser django?
My problem is that I want to change user status from admin panel. Admin should be able to change field "is_staff" from his panel. When I read the documentation, it says: User Use this endpoint to retrieve/update the authenticated user. Default URL: /users/me/ https://djoser.readthedocs.io/en/latest/base_endpoints.html#user Okay, and I am planning to use it to change user's password later, but it makes sense to change users password while being logged in as this user. But how to change another field ('is_staff') in another user while being logged in as admin? Does sending request to /users/me/ make sense? I will update this with any code needed. -
Creating endpoint fetch data from local json file using django rest
I am trying to create django application with a REST api endpoint. The application should be able to able to fetch a list of users from the json file The API should also allow the user to fetch a specific user from the json file. Json file {users:[ {"name":"Julia", "phone" :'+111454545' }, {"name":"Kenny" "phone":"+9911111111' }, ]} How do I do that ? -
reference a HTML tag with javascript that was generated from django json schema
i am trying to reference a HTML tag that is generated by a django's django_jsonforms link JSON Schema link via javascript to dynamically update the form. For example 2 dropdowns in a form, if you make a selection in the 1st dropdown the 2nd dropdown should update. I've done this for HTML selection tags that i manually typed out but i am trying to get this to work for HTML generated by JSON Schemas. Here is what i've tried: inspect HTML page and try to call the tag by name with var project_selection = document.getElementsByClassName("form[project]")[0]; this didnt work, which i was a little surprised by since i see when i inspect the page that the select tag has name="form[project]" then i thought maybe the JSON Schema renders the tag after the javascript runs so i tried adding defer into my <script defer> and that didnt work i tried using JSON Schema $id #anchor and $ref but none of those worked to reference the tag by ID I am sure someone has come across this before so i hope this is an easy answer. At the end of the day i know i need to use the following with the JSON … -
Django UUID Validation Error: Sometimes object, sometimes UUID
This page is supposed to show a post for a social media website. Within <div class="is-flex">, I have an if/else/endif block for showing a like/unlike button. As the code is right now, it successfully shows the like/unlike button on non-shared posts. I would like to have it so the like/unlike button appears on all posts as long as {user.is_authenticated} is true, but if I move the like/unlike code block anywhere else in the div, I get this error. Even adding the line for the button and commenting it out gives the error. No variables are being written, only read, so I don't know why Django would get the UUID in one instance and the entire post object in another instance. Lines with *NOTE* comments are lines I tried duplicating/moving the like/unlike code block to without success. {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% #header user=user %} {% /header %} {% load crispy_forms_tags %} {% load markdown_extras %} {% load url_check %} {% load comment_like %} {% load post_like %} <main> <div class="is-flex mt-3"> <small>Posted by: <a href="/author/{% valid_url_profile post.author.id %}">{{post.author.displayName}}</a></small> <small> &nbsp;• {% load tz %} {% localtime on %} <small>Created: {{post.published}}</small> … -
Show related item django
I have the following models: class Category(models.Model): name = models.CharField(max_length=255) class Element(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=255) class Topic(models.Model): category = models.ForeignKey(Category) element = models.ForeignKey(Element) name = models.CharField(max_length=255) I basically need to add New topic in catégory id =1 and get only a list of élément belongs to category 1 I have created a view New topic in category id =1, but for fields element in form i get all elements for all categories -
how do I align RadioSelect button?
For some reason this button comes with weird alignment, I want it aligned next to gender label but the ul element comes with pre existing "margin-block-start, margin-block-end and padding-inline-start" so how do I align it right? html <div class="block"> <label>Gender</label> <span class="placer">{{ form.gender }}</span> </div> css #id_gender li { list-style-type: none; display: inline-block; } forms.py gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect(), required=True) I want the radios(Male and Female) to be aligned next to Gender. Thnx in advance! -
Fetch : authentication credentials were not provided
When I request this, everything is ok and I get the data: const get_players = async()=>{ const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/') const data = await response.json() console.log(data) } But when I put permission_classes in views.py, I recive this in the console: {detail: 'Authentication credentials were not provided.} I am a beginner in Javascript so I wll hope you can understand. I dont know how to put the authentication credentials in my fech. Views.py class PlayersView(ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = PlayersSerializer queryset = Players.objects.all() def list(self, request): queryset = Players.objects.all() serializer = PlayersSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Players.objects.all() qs = get_object_or_404(queryset, pk=pk) serializer = PlayersSerializer(qs) return Response(serializer.data) Urls.py router = DefaultRouter() router.register('players',views.PlayersView,basename='players') app_name = 'main' urlpatterns = [ path('',include(router.urls)), ] Any idea? -
Constrain unique_together could have conflict with the unique_field in dajngo Class
Basically, I would like to know if there is any conflict using the constrain unique_together as well as the parameter unique=true in one of the fields that belong to the array of the unique_together. it´s because I can´t remove the parameter unique=true of my field because it´s used as a foreigner key in another model. class User(AbstractUser): # User information fiscal_number = models.CharField(max_length=30,unique=True) phone = models.CharField(max_length=15, null=True) email = models.EmailField(max_length=254, verbose_name='email address') class Meta: unique_together = ['fiscal_number', 'email'] As you can see the goal is to make the combination of the fields fiscal_number and email unique -
Why isn't Django Sitemap showing the URLs
I've been trying to make my django sitemaps work for a small blog application. After checking out multiple tutorials, I still can't get the sitemaps work properly. Here's my urls.py: from django.contrib import admin, sitemaps from django.urls import path from django.urls import include from rx import views from django.conf.urls.static import static from django.conf import settings from django.contrib.sitemaps.views import sitemap from rx.sitemaps import Static_Sitemap sitemaps = { 'static': Static_Sitemap, } urlpatterns = [ path('ckeditor/', include('ckeditor_uploader.urls')), path('admin/', admin.site.urls), path('', views.index, name='index'), path('blog/', views.blog, name='blog'), path('about/', views.about, name='about'), path('<slug:cat_slug_name>/', views.cat, name='cat'), path('<slug:cat_slug_name>/<slug:post_slug_name>/', views.blog_post, name='blog_post'), path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's my settings.py: """ Django settings for rankxero project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! … -
Django annotate queryset by predicate and count results
I have two models: class Game(models.Model): id = models.AutoField(primary_key=True) class Score(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game, related_name="score", on_delete=models.CASCADE) first_score = models.IntegerField(blank=True) second_score = models.IntegerField(blank=True) is_rusk = models.BooleanField(blank=True) And I got a queryset of Game objects: [ { "id": 314317035, "score": [ { "first_score": 5, "second_score": 1, "is_rusk": false } ] }, { "id": 311298177, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, { "id": 310278749, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, { "id": 309866238, "score": [ { "first_score": 5, "second_score": 0, "is_rusk": true } ] }, { "id": 307926664, "score": [ { "first_score": 5, "second_score": 0, "is_rusk": true } ] }, { "id": 306047964, "score": [ { "first_score": 4, "second_score": 5, "is_rusk": false } ] }, { "id": 304881611, "score": [ { "first_score": 5, "second_score": 3, "is_rusk": false } ] }, { "id": 304468136, "score": [ { "first_score": 5, "second_score": 2, "is_rusk": false } ] }, ] I want to annotate this queryset with rusks_cnt, it will be count of objects with is_rusk=True, If there is a way to not add this to every object, just as one field, that would be good too. I think easiest way to … -
Patch request not patching - 403 returned - django rest framework
I'm trying to test an API endpoint with a patch request to ensure it works. I'm using APILiveServerTestCase but can't seem to get the permissions required to patch the item. I created one user (adminuser) who is a superadmin with access to everything and all permissions. My test case looks like this: class FutureVehicleURLTest(APILiveServerTestCase): def setUp(self): # Setup users and some vehicle data we can query against management.call_command("create_users_and_vehicle_data", verbosity=0) self.user = UserFactory() self.admin_user = User.objects.get(username="adminuser") self.future_vehicle = f.FutureVehicleFactory( user=self.user, last_updated_by=self.user, ) self.vehicle = f.VehicleFactory( user=self.user, created_by=self.user, modified_by=self.user, ) self.url = reverse("FutureVehicles-list") self.full_url = self.live_server_url + self.url time = str(datetime.now()) self.form_data = { "signature": "TT", "purchasing": True, "confirmed_at": time, } I've tried this test a number of different ways - all giving the same result (403). I have setup the python debugger in the test, and I have tried actually going to http://localhost:xxxxx/admin/ in the browser and logging in manually with any user but the page just refreshes when I click to login and I never get 'logged in' to see the admin. I'm not sure if that's because it doesn't completely work from within a debugger like that or not. My test looks like this (using the Requests library): def … -
My pyrogram app don't start in Django framework view function, but in isolated module it works very well
When I create Client instance of Pyrogram library in single module (isolated .py file) and run that file my app works properly. app = Client("app", api_id=MY_ID, api_hash=MY_API_HASH) But in django view the exactly same code don't work. I create Client instance, but my project freezes after calling any methods (like start, stop, send_message ...). Are there any peculiarities when starting pyrogram app in Django framework? -
Returning queryset as json in Django
I wanted to get your advice. I have the below, which returns the data I want. However, so that I can use ajax to update the page without refresh, I need to be able to return the results as JSON. I keep getting erros that the query result is not serializable. Does anyone know how to do it? Thanks a lot! open_tasks = skills.objects.filter(creator=request.user).raw(''' SELECT *, round((closed_points/(open_points + closed_points)*100),2) as points_pct, round((closed_count/(open_count + closed_count)*100),2) as closed_pct from ( SELECT id, coalesce(sum(open_points),0) as open_points, coalesce(sum(closed_points),0) as closed_points, coalesce(sum(open_count),0) as open_count, coalesce(sum(closed_count),0) as closed_count from ( SELECT id, case when status = 'open' then sum(points) end as open_points, case when status <> 'open' then sum(points) end as closed_points, case when status = 'open' then sum(count) end as open_count, case when status <> 'open' then sum(count) end as closed_count from ( SELECT category as id, status, sum(cast(points as int)) as points, count(*) as count FROM voxi_skills WHERE creator = %s group by category, status)s group by id, status)p group by id)j ''', [request.user.username]) -
How to modify the pdf in the server, django
Good dat to all. I have a django project running in a linux server with apache2. What my code does is to replace a PDF file. When the user fills the form, it is received, then replace the corresponding fields in the file and save() it. Locally it works perfectly, but when I try it on the server, the pdf is not overwritten because it always displays the same PDF instead of the modified one. Since locally works correctly, I thought it would be maybe the routes, or the permissions. The first option i already checked the routes, they are correct, so it must not be that. The other thing that can be not letting to overwrite, are the permissions so what I did, was to give permissions chmod 777 to the PDF file to see if it works, but it didnt. It still the file doesn't change. This code is to add the corresponding fields to the pdf def generate_attached_standard_pdf(attachment_data): try: name=attachment_data['creditor'] w, h = letter # DEFINE PDF CONFIGURATIONS c = canvas.Canvas('anexoA.pdf', pagesize=letter) c.setTitle('Anexo {}'.format(name)) pdfmetrics.registerFont( TTFont('Lato', BASE_DIR +"/recursos/fonts/Lato-Regular.ttf"), ) pdfmetrics.registerFont( TTFont('Lato-Bold', BASE_DIR+"/recursos/fonts/Lato-Bold.ttf"), ) c.save() return { 'success': True, 'message': 'PDF CREADO' } except Exception as e: print(e) … -
Apache2 configurations with WSGIDaemonProcess use domain name not server ip
I deploy three projects Django on the same server each on must work on a subdirectory, they worked correctly this way WSGIDaemonProcess test.com/en threads=5 python-path=/home/api. WSGIProcessGroup test.com/en WSGIDaemonProcess test.com/fr threads=5 python-path=/home/apifr. WSGIProcessGroup test.com/fr WSGIDaemonProcess test.com/ru threads=5 python-path=/home/apiru. WSGIProcessGroup test.com/ru <VirtualHost *:80> ServerAdmin admin@test.com ServerName text.com ServerAlias {server_ip} ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #WSGIPythonHome /home/api/venv/ WSGIPassAuthorization On WSGIScriptAlias /en /home/api/server/wsgi.py process-group=test.com/en WSGIScriptAlias /tr /home/apifr/server/wsgi.py process-group=test.com/fr WSGIScriptAlias /ru /home/apiru/server/wsgi.py process-group=test.com/ru Alias /api /home/api/server/wsgi.py <Directory /home/api/server/> <Files wsgi.py> AllowOverride All Require all granted </Files> RewriteEngine On RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*) index.html [L] </Directory> I added three Alias for each subdirectory and directory like this one I want to change server_ip with domain name or subdomain to be api.test.com when I change it I get an error 400 , the apache2 log doesn’t show anything -
Display data on a dynamic page
Faced with such a problem, the exercise_new page does not display any form and does not display information from the DB. enter image description here #------------views.py-----------# def comment(request, pk): """Вывод полной статьи """ new = get_object_or_404(Exercise, pk=pk) comment = Comments.objects.filter(new=pk, moderation=True) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.new = new form.save() return redirect(exercise, pk) else: form = CommentForm() return render(request, "ProManager/exercise_new.html", {"new": new, "comments": comment, "form": form}) #---------models.py------------# class Comments(models.Model): """Ксласс комментариев к новостям """ user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name="Пользователь", on_delete=models.CASCADE) new = models.ForeignKey( Exercise, verbose_name="Новость", on_delete=models.CASCADE) text = models.TextField("Комментарий") created = models.DateTimeField("Дата добавления", auto_now_add=True, null=True) moderation = models.BooleanField("Модерация", default=False) class Meta: verbose_name = "Комментарий" verbose_name_plural = "Комментарии" def __str__(self): return "{}".format(self.user) #-----------------forms.py-------------# class CommentForm(ModelForm): """Форма комментариев к статьям """ class Meta: model = Comments fields = ('text', ) #----------------exercise_new.html----------------# <h4>Комментарии</h4> {% for comment in comments %} Пользователь - {{ comment.user }}<br> {{ comment.text }} <br> Добавлен - {{ comment.created }}<br><br> {% endfor %} {% if user.is_active %} <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Отправить</button> </form> {% else %} <h4>Что бы оставить комментарий авторизуйтесь</h4> {% endif %} ---------------------urls.py------------------ urlpatterns = [ path('exercise/<int:pk>/', ExerciseDetailView.as_view(), name='exercise-new'), path('project/<int:pk>/', ProjectDetailView.as_view(), name='project-new'), … -
CORS not working in specific app - Django
I have an existing app called auth, which lets new user create an accout or get an auth token after logging. Here everything seems allright. No CORS problems are present, but when I started a new app called Blog and tried to access its views troughtout an axios request i get CORS error - No access allow origin headers are present even when my CORS policy is initialized. Here is snippet of my settings.py Django settings for backend project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-3mr!aqng!tc!*ko7i!*&y9x8k-*y$@1pc+$g!_^-aol4!vd@tn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'django_rest_passwordreset', 'corsheaders', 'auth_app', 'blog' ] 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', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES … -
Fetch : authentication credentials were not provided
I am trying to send to the API that the user is authenticated, but I dont know how can I. Js const get_players = async()=>{ const response = await fetch('http://127.0.0.1:8000/player_stats/api/players/') const data = await response.json() console.log(data) } Views.py class PlayersView(ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = PlayersSerializer queryset = Players.objects.all() def list(self, request): queryset = Players.objects.all() serializer = PlayersSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = Players.objects.all() qs = get_object_or_404(queryset, pk=pk) serializer = PlayersSerializer(qs) return Response(serializer.data) -
How to pretty print Json initial Djnago
I am learning django and working on a project. How can I print the pretty nice format in django form in json field. I want to like this { "name":"hello" } in django form field. class BaseAdapterRegister(forms.Form): replay = forms.ChoiceField(initial=0, choices=((0, 0), (1, 1))) start_date = forms.fields.DateField(initial=datetime.datetime.strptime('1970-01-01', '%Y-%m-%d'), widget=forms.widgets.DateInput(attrs={'type': 'date', 'min': '1970-01-01', 'max': f'{datetime.date.today()}'})) trigger_pipeline = forms.ChoiceField(initial=False, choices=((True, True), (False, False))) adapter_config = forms.JSONField() # to have initial text in nice json format -
Highlighting the inner code blocks in Django Template Engine with django-pygmentify
I'm using django-pygmentify package in order to highlight my code blocks in my Django templates. The thing is that this package only supports code blocks as input. I have a model field that keeps markdown data. This markdown content might contain code blocks. (using ``` symbol) Now, how can I highlight itsinner code blocks?? Imagine I have a field that only contains source code. Like: print('Hey..!') In that case, this one works properly. {% load pygmentify_tags %} ... {% pygmentify %} {{post.code}} {% endpygmentify %} Imagine my field contains the following content. ## Hello This is my first step working with Python. ```python print('Hey..!') ``` In this case, how can I implement it?? I can render that whole markdown content with {{post.body|markdown|safe}}, but how can I highlight those code blocks?? I also want to give all those code blocks a class name .code-block for better styling. Should I create a custom template tag? -
How to show name instad of id in django ForeignKey?
I have a model with a ForeignKey to itself. models.py class Person(models.Model): name = models.CharField(max_length=20) important_name = models.ForeignKey('Person', on_delete=models.SET_NULL, blank=True, null=True, related_name='first') def __str__(self): return self.name And when i want to show my data with DetailView CBV in view it show id instead of name. views.py class DetailPerson(DetailView): model = Person template_name = 'panel/detail_person.html' detail_person.html <table class="table"> {% for label, value in object.get_fields %} <tr> <td>{{ label }}</td> <td>{{ value }}</td> </tr> {% endfor %} </table> How can i show name instead of id? -
Styling is different on the MacBook Pro 13in Retina display
I am trying to resolve this issue and that the below is what it looks like on a Windows 13in However, for the Macbook Pro 13in Retina display, the website looks different and the below is what it looks like How do I resolve this issue? I have the media query set as @media screen and (min-width: 1200px) -
How to SSH connection with Django?
How can I connect to a freebsd server and return commands using SSH in Django? I tried using the paramiko library but couldn't get it to work. Sorry for my level of English, I'm not very good. -
Creating migrations for a Django project that does not have any migrations already
I am working for a client with a 13 year old Django project. When they built the project migrations were not implemented so the project currently lacks migrations. I have tried creating migrations and then doing a datadump and loaddata into a new database to test them out. I am running into all sorts of errors and would like to start fresh. So my question is this. What steps should I take to implement migrations in the project so that we can move forward using migrations? The django version has been updated to 3.0.5 and there are a number of GenericForeignKeys used, which might make this extra tricky. When creating the migrations originally I was told to use the fake tag but don't completely understand what this means. Any help in the steps that I should take would be appreciated. For the sake of privacy/security for the client I don't want to just share a ton of their code but can share parts of it if it helps someone determine the steps that I should take.