Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
For-loop implementation of a key for an object HTML
I have a queryset full of weather objects and I need to loop through a custom array to extract specific weather metrics in each of the weather objects in an HTML template for a Django application. detail.html <table> <tr> {% for weather_object in weather_objects %} {% for variable in variable_list %} ## variable_list = ['temp', 'humidity'] <td>{{weather_object.variable}}</td> {% endfor %} {% endfor %} </tr> </table> Views.py context = {'weather_objects': weather_objects, 'variable_list': variable_list} return render( request, 'webapp/detail.html', context=context ) There could be better ways to do this, but honestly, I'm really stumped here. Why can't I loop through the variable list and extract data from weather_object? It's specifically 'weather_object.variable' that just acts nonexistent. I can do it manually, I can write specifically <td>{{weather_objects.temp}}</td> or <td>{{weather_objects.humidity}}</td> but I can't automate it in a for a loop. Why?? I have verified that the variables in the variable list are correct and should work. Could it be because the variable is only a string substitute? -
How to run docker image on local server
I am so new in Docker and i need to run a dokcerized django project which is already writen by another developer , this is Dockerfile.dev: FROM python:alpine RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && apk add jpeg-dev zlib-dev libjpeg ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt COPY entrypoint.sh /app/ ENTRYPOINT [ "./entrypoint.sh" ] EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and dcoker-compose.yml : services: event: build: context: . dockerfile: Dockerfile.dev volumes: - ./:/app env_file: - ./envs/development.env command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - "8000:8000" depends_on: - event-database event-database: image: postgres:alpine env_file: - ./envs/development.db.env networks: default: name: mizban when i create an image with docker build --tag and then run it with docker run imageid it does not run CMD part to run project on the 0.0.0.0:8000 port any suggestions? -
How to write health check for graphql apis without http
I have a K8s cluster in which there is a pod which has Gjango + Graphql apis. I need to write a health check job which makes sure that my apis are up and running. I do not want to use http style request to check the health. Rather I would like to use Django. Please guide me how can I do that? -
Is there a way to preserve html checkbox state after reload in Django?
Sample code is below. I would like to keep the checkbox checked after page reload once submit button has been pressed <td><input type="checkbox" value="{{ item }}" name="selectedcheckbox"/></td> -
login_oculto() takes 1 positional argument but 2 were given
mi codigo parece funcionar, cuando pongo mal el usuario o la contraseña me funciona el mensaje de error, sin embargo cuando quiero ingresar realmente a la pagina oculta, me arroja lo siguiente: TypeError at /administracion/ingreso login_oculto() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://localhost:8000/administracion/ingreso?next=/oculto Django Version: 3.2.8 Exception Type: TypeError Exception Value: login_oculto() takes 1 positional argument but 2 were given Exception Location: C:\Users\OGT\Museum\mu2\views.py, line 48, in login_oculto Python Executable: C:\Users\OGT\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\OGT\Museum', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib\site-packages'] login.html <div class="contenedor_formulario"> {% if error %} <p style="color: black;">{{ error }}</p> {% endif %} <form action="" method="POST" style="text-align: center;"> {% csrf_token %} <table class="tabla_formulario"> <form method="POST" action="{% url 'anyname' %}"></form> <input type="text" placeholder="Usuario" name="username" /> <input type="password" placeholder="contraseña" name="password" /> </table> <input class="boton_formulario" type="submit" value="Ingresar"> </form> </div> urls.py urlpatterns = [ path('administracion/ingreso', views.login_oculto, name='anyname'), path('oculto', views.oculto,name='oculto') ] views.py def login_oculto(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') usuario = authenticate(request, username = username, password = password) if usuario: login_oculto(request, usuario) return redirect('oculto') else: return render (request, 'mu2/login.html', {'error': 'usuario o contraseña incorrecta'}) return render(request, 'mu2/login.html') -
DoesNotExist - matching query does not exist
I have this django class-based view where i am trying to overwrite the get_queryset function because i want get to the inserted values from the frontend to search in my database after the subject with that name and then get the id. but when i call the view it gives me a "Subject matching query does not exist." because the subject_val is None. That makes sense because the user has not submitted the values jet.. so how do i get it to wait until a user have choosen "submit class AttendanceList(LoginRequiredMixin, ListView): model = AttendanceLog template_name = "./attendancecode/showattendance.html" def get_queryset(self): class_val = self.request.GET.get('class') subject_val = self.request.GET.get('subject') sub = Subject.objects.get(name=subject_val).id new_context = get_statstic(class_val, sub) return new_context def get_context_data(self, **kwargs): context = super(AttendanceList, self).get_context_data(**kwargs) context['class'] = self.request.GET.get('class') context['subject'] = self.request.GET.get('subject') return context -
Why Bokeh radioButtonGroup doesn't work in my django application?
i'm trying to develope a webapp for my master thesis. I used Bokeh to do interactive plot, and i embedded it in a django app. The problem is that i don't manage to do something with js_on_change or js_on_click of radiobuttongroup. This is my view: def DTA_webAPP(request): context={} result = None imps = pd.DataFrame(columns=["1","2","3","4","5"]) # i need this to avoid problem in create_grid in plotting.py dta = pd.DataFrame(columns = ["3","4"]) fig = myfig(imps,dta) script,div = components(fig.layout) form = DTAselection(request.POST,request.FILES) if request.method == 'POST' and "Compute" in request.POST: if form.is_valid(): data = pd.read_csv(request.FILES["ImportData"],sep = "\t", skiprows = [1,2]) imps, dta = main(data, form['method_of_discretization'].value(),float(form['regularization_parameter'].value()), int(form['regularization_order'].value()), int(form['number_of_point'].value()), form['col_selection'].value()) fig = myfig(imps, dta) script, div = components(fig.layout) imps.to_csv("result_imps.csv", index = False) dta.to_csv("result_dta.csv", index = False) result = "Ok, boy" context = {'form': form, 'script':script, 'div':div, "result":result} return HttpResponse(render(request, "dta_webapp.html", context)) the figure is created in the class myfig. This is my class myfig: LABELS = ["IMPS","REAL RESIDUALS", "IMAG RESIDUALS"] class myfig(object): def __init__(self, df_data, df_dta): self.df_data = df_data self.df_dta = df_dta self.radio_button_group = RadioButtonGroup(labels=LABELS, active=0) self.source = None self.plot = self.create_grid() self.radio_button_group.js_on_change('active', CustomJS(args= dict(s=self.source, p = self.plot.children[0], x = self.df_data.columns[1], y = self.df_data.columns[2], ), code=""" console.log('radio_button_group: active=' + this.active, this.toString()); const s1 = new … -
No Module named <module_name> but i have the module correctly linked
My actual folder structure is the next one >django_app/ >django_models/ >Model_1 >django_views/ >View_1 >models.py >views.py Inside 'models.py' i have this: from django_app.django_models.Model_1 import Model_1(This is the class name) but when i try to run server i get this error: from django_app.django_models.Model_1 import Model_1 ImportError: No module named django_models.Model_1 i have done this before in django 3.2 and restframework, but rn isn't working as expected *Python == 2.7 *Django == 1.6.5 this is an old project from my company and we dont have time to uptade it to newer versions. -
MPTT Django how to get children with user_id = some_user_id. NOT ALL children
def get_queryset(self): if not self.request.user.is_authenticated: # for swagger generation only return CannedAnswer.objects.none() if self.action in ['list']: return CannedAnswer.objects.filter( Q(agent=self.request.user) | Q(agent__isnull=True) | Q(group__in=self.request.user.groups.all())).get_cached_trees() else: return CannedAnswer.objects.filter(agent=self.request.user) This code returns me all children, but I want to get children who have agent = self.request.user -
wagtail api how to expose snippets and serialize nested data
the problem is this, i've created a snippet and i want to expose it but i don't know how to serialize nested data. here my code: models.py @register_snippet class TeamMember(ClusterableModel): name = models.CharField(max_length=80) description = models.CharField(max_length=80) panels = [ FieldPanel('name'), InlinePanel('tasks', label=('Tasks')), ] class Task(Orderable): team_member = ParentalKey('adm.TeamMember', related_name="tasks") task_name = models.CharField(max_length=80) endpoints.py class TeamMemberAPIEndpoint(BaseAPIViewSet): model = TeamMember body_fields = BaseAPIViewSet.body_fields + [ 'name', 'description', 'tasks', ] listing_default_fields = BaseAPIViewSet.listing_default_fields = [ 'name', 'description', 'tasks', ] the result is: "items": [ { "name": "python team", "description": "", "tasks": [ { "id": 1, "meta": { "type": "adm.Task" } }, { "id": 2, "meta": { "type": "adm.Task" } } ] } how can i resolve this problem? -
Select latest record in the group with ordering
I am having trouble writing a query using Django ORM, I want to find the latest record in each group. I am putting chat messages in the model and I want to find the latest chat of each user and show chats latest chat of each user and with the latest user's chat on the home screen just like in WhatsApp, Skype or similar apps. Currently, I am using the following query, Chats.objects.all().order_by('user_id', '-date').distinct('user_id') Using this I am able to get the latest chat of each user but I am not able to get the sequence correct. The result of the query is in the order of which the users were created in the database which I understand is correct, but I want to show the user who sent the latest chat at the top. My Models.py class Chats(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) chat = models.CharField(max_length=1023, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) Thank you so much, Please let me know if any other information is required. -
Deleting and creating in CreateView django
Hello I am making django to-do list and I have a question. Am i able to delete and create elements in one view? Personally I would not use CreateView for that and make it like in 'def post' and ignore 'get_success_url' but is it good and djangonic practice? views.py class Home(CreateView): model = Item template_name = 'home/todo.html' form_class = itemCreationForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['items'] = Item.objects.all() return context def get_success_url(self): return reverse('home-page') def post(self, request): form = itemCreationForm() if 'delete' in self.request.POST: print('deleted') return redirect('home-page') if 'add' in self.request.POST and form.is_valid(): form.save() return HttpResponse('home-page') HTML <div class="card__items-list"> {% for item in items %} <div class="card__item-row"> <p class="card__item">{{ item.name }}</p> <form action="{% url 'home-page' %}" class="card__delete" method="POST"> {% csrf_token %} <button class="card__delete__button" name="delete" type="submit">&#10008</button> </form> </div> {% endfor %} </div> <form name="add" method="POST"> {% csrf_token %} {{ form }} <button name="add" class="submit-button" type="submit">Submit</button> </form> </div> -
psql query returns blank rows
I store data from django in a postgreSQL database. My data is a huge nested list of floats with about 3 thousand rows. It looks like this: [[0.1, 0.2, 0.3], [0.3, 0.5, 0.6], [0.7, 0.8 0.9]] I tried to query it in pgAdmin 4, but it gives an output with a huuge delay. Now I am trying to query it with psql and it gives out only blank rows. my query: SELECT * FROM public."abc" LIMIT 1; what I get: id | and then a lot of blank rows. -
How to (de)serialize float list into models using Django REST Framework model serializer?
TL; DR How to create both serializers.Patient and serializers.Temperature in such way that: models.Patient has one-to-many relationship with models.Temperatures serializers.Patient is a subclass of serializers.ModelSerializer serializers.Patient (de)serialize temperatures as a list of floats Details Given a quick-dirty patient medical records RESTful API implemented with Django framework. Patient is defined at models.Patient as: class Patient(models.Model): created_at = models.DateField() name = models.CharField(max_length=200) updated_at = models.DateField() and the models.Temperature: class Temperature(models.Model): created_at = models.DateField() patient = models.ForeignKey( Patient, db_column='patient', related_name='temperatures', on_delete=models.CASCADE, ) updated_at = models.DateField() CRUD operations at /patients (de)serialized models.Temperature as float lists, thus a POST should only require: { "name": "John Connor", "temperatures": [36.7, 40, 35.9] } while a GET operation { "created_at": "1985-03-25", "name": "John Connor", "temperatures": [36.7, 40, 35.9], "updated_at": "2021-08-29" } However operations at /patients/<id>/temperatures/ endpoint should return all properties: { "created_at": "1985-03-25", "name": "John Connor", "temperatures": [36.7, 40, 35.9], "updated_at": "2021-08-29" } Can this feature be implemented subclassing standards DRF serializers or does it require a customized serializers.Serializer subclass? -
Browser keeps adding path in request in Django+Docker setup
I'm not sure how this is happening, but the browser keeps adding the path (/code) where the Django app is stored in the container. If I make a curl request to the same url, it works fine. This is my Dockerfile: FROM python:3.10 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . . and this is my docker-compose version: '3.8' services: backend: build: context: ./backend dockerfile: Dockerfile.dev command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend:/code ports: - 8000:8000 env_file: - ./backend/.env.dev -
Fetch: Authentication credentials were not provided
Im a beginner in Javascript and I dont know how can I send to the API that the user is authenticated and has a token. Js const api = 'http://127.0.0.1:8000/player_stats/api/players/' const get_players = async()=>{ const response = await fetch(api,{ method:'GET', headers:{ 'Content-Type' : 'application/json', } }) 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) Settings.py CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:3030',] CORS_ALLOWED_ORIGIN_REGEXES = [ 'http://localhost:3030',]