Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, get the all posts from the Theme
Sorry for english. I have a Themes and there are posts in this themes. I need to get the posts from the current Theme I tried to get a theme via slug then check the theme id and display all posts under that id, but i dont know how template_name = 'site/themes.html' def get_context_data(self, **kwargs): context = super(MultipleModelView, self).get_context_data(**kwargs) context['modeltwo'] = Theme.objects.all() context['modelone'] = Subject.objects.all() context['modelthree'] = Theme.objects.filter(slug=self.kwargs.get('slug')) context['modelfour'] = Post.objects.filter(where_we_are_id = 1) return context Model Theme title = models.CharField(max_length=50,verbose_name="Название") subject = models.ForeignKey(Subject,on_delete=models.CASCADE,related_name='subject') slug = models.SlugField(null=True,verbose_name='ссылка на страницу') class Meta: ordering = ['title'] verbose_name_plural = 'Темы' verbose_name = 'Тема' def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) Model Post class Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True) title = models.CharField(max_length=50,verbose_name="Название") text = models.TextField(max_length=500,verbose_name="Текст") created_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') is_published = models.BooleanField(default=True) where_we_are = models.ForeignKey(Theme,on_delete=models.CASCADE,related_name='get_news',null=True,blank=True ) class Meta: ordering = ['created_at'] verbose_name_plural = 'Посты' verbose_name = 'Пост' def __str__(self): return self.title ``` -
Django: how to save model into different database tables depending on which ManyToOne relationship it belongs to?
I'm new to Django. My app have two models, Customer and Order, where each customer can have multiple orders. So what I did is to set up a ForeignKey(Cusotmer) relationship in Order model: name = models.CharField(max_length=20) phone = models.CharField(max_length=20) def __str__(self): return self.name class Order(models.Model): customer= models.ForeignKey(Customer,null=True, on_delete = models.SET_NULL) ordername = models.CharField(max_length=20) In this case, if I want to query the orders by a specific customer customer1, I can use Order.objects.filter(Customer=customer1). But I wonder if it is possible to save the order data for each customer in a separate database table? Right now all the orders are saved in the same table and misuse of filters can let customers view other customers' orders. -
Adding email in Django's admin user creation
I'm having trouble figuring out how to add the email field to the admin panel's create user page (Django 3.2). I've managed to get a custom field to show but keep running into errors when I attempt to add email in the same way. accounts/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser # Short list displayed on admin/accounts/customuser page list_display = ['email', 'username', 'company', 'is_staff'] fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('company',)}), ) add_fieldsets = UserAdmin.add_fieldsets + ( (None, {'fields': ('company',)}), ) admin.site.register(CustomUser, CustomUserAdmin) accounts/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields + ('company',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields -
Dependency references a non-existing parent node ('auth', '0012_alter_user_first_name_max_length')
I'm working on a Django project on PyCharm and it runs totally fine. I am using a venv and I had to send the project to a person. So I removed the venv folder and sent and they encountered this issue (see image). I deleted my migrations (except init.py) and executed manage.py makemigrations and manage.py migrate and the project runs fine on my end. The dependency is automatically created (so it isn't something I created manually) and still exists after deleting and reapplying migrations but I had no issue in running the server on my end. This is what is in my first migration file: class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ May I know what the issue might be for the other person? Is it because I deleted the venv folder? Can I just remove this dependency on my end? Will this make the server run fine on the other person's end without them having to make any changes? Any help is appreciated! -
How can I use StimulSoft Report in Python and Django?
I've got some Stimul Soft report files and I wanna use them in Django. But I don't have a clue about that. Please show me a suit way if it's possible. I've created them for using in a .Net project Thanks -
Django builtin logout redirect is not working _ MDN Tutorial Library
Kindly help me on getting django inbuilt logout page working. Login is working fine. When I go to logout page. It take me back to admin window, whereas it should go back to login.html page. So please help me out on sorting what is wrong in the code So far code is as per MDN tutorial on Local Library locallibrary/urls.py urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] mdntutorial/templates/registration/login.html directory for your reference is like this |_mdntutorial |_locallibrary |_templates (new) |_registration Login.html {% extends "catalog/base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost … -
React, Django: Build Files are not using STATIC_URL
I'm using React + Django. When I run it locally, everything works fine because my static files both from my Django-side and from React are loaded through /static/. When I run npm build run, the index.html in my React file does not change to the production setting's STATIC_URL. Instead, it still shows something like this: <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script src="/static/js/asdfasdf.chunk.js"></script> <script src="/static/js/asdfasd.chunk.js"></script> </body> Is there a way I can set the script's src attribute to something like {% static chunk.js %}? Or is there a better angle to do this? -
Django Rest Framework permission_classes not working
I have a problem using Django Rest Framework's permission_classes attribute. The view I want to protect is defined as: class Test(APIView): permission_classes = [IsLoggedIn] def get(self, request): return Response("aaa") I have also tried having the class inherit GenericAPIVIew. permissions.py from rest_framework import permissions class IsLoggedIn(permissions.BasePermission): def has_object_permission(self, request, view, obj): return False I'm trying to get the permission to at least always refuse the request, but it seems that the has_object_permission method is never getting called. -
How to change Date Format in a form field Django
I need to display the form in a different format => "%d%m%Y". but I tried everything but nothing works. In my forms.py class DateInput(forms.DateInput): input_type = 'date' class VendaForm(forms.ModelForm): class Meta(): model = Venda exclude = ['acertado', 'status', 'viagem', 'paid',] widgets = { 'sale_date': DateInput(), 'expiration_date': DateInput(), } -
Django 404 Error page not found...the current path matched the last one
I'm new to django and I'm playing around with my own variation of the polls tutorial. My app was working fine, every page loaded correctly. Then I made a single change; I created and then deleted a model. Now, many of urls seem broken. And I don't understand this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/pick/ Raised by: polls.views.pick Using the URLconf defined in mySite.urls, Django tried these URL patterns, in this order: polls/ [name='index'] polls/ <int:pk>/ [name='detail'] polls/ <int:pk>/results/ [name='results'] polls/ <int:question_id>/vote/ [name='vote'] polls/ <int:question_id>/tally/ [name='tally'] polls/ <int:question_id>/pick/ [name='pick'] The current path, polls/1/pick/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. So I don't understand why it says both that: The current path, polls/1/pick/, matched the last one. and also page not found? How does that work? And what could have caused this when the app was working fine previously? My urls.py: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), path('<int:question_id>/tally/', views.tally, name='tally'), path('<int:question_id>/pick/', … -
Nginx return 301 https://$server_name$request_uri; Too Many Redirects
My Ubuntu 20.10 server has Nginx + Gunicorn + Django Installed. An SSL Certificate has been installed and passes several online SSL/TLS testing assessments. It still displays as unlocked in browsers. Whynopadlock indicated that forcing HTTPS was required. The command return 301 https://$server_name$request_uri; breaks the site - infinite redirects. Might anyone offer suggestions? The sites-available configuration is posted below. Dozens of variations on the following have been tried but to no avail: #Have tried with and without this: upstream django { server 127.0.0.1:8000; keepalive 32; } #Have tried with and without this #server { # listen 80 default_server; # server_name www.example.com; # return 301 https://$server_name$request_uri; #This line breaks site if 1 or 2 server blocks are used #} server { listen 80; #Removed this for above server block listen 443 ssl; server_name www.example.com; #Removed www.* ssl_certificate /etc/nginx/ssl/certificate.crt; ssl_certificate_key /etc/nginx/ssl/private.key; ssl_protocols TLSv1.2 TLSv1.3; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/example/staticfiles/; } location / { #Tried many combinations of these: proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; #proxy_set_header Host $host; proxy_set_header Host $http_host; #Have tried $http and $http_host proxy_set_header Connection ""; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://unix:/run/gunicorn.sock; #Have tried variations on this … -
I would like to know how to take the create and modify option of a model in the Django-Admin
Can someone explain me how to hide this, even for superusers. I have searched on the internet, but none of the other posts explain about this I am using django3.2.2 lts -
DJANGO stdimage not resizeing the image size
Why image is not resizing? here is my code: #models.py from django.db import models from PIL import Image from stdimage import StdImageField class Contact(models.Model): name = models.CharField(max_length=200) image = StdImageField(upload_to="contact/images/",variations={'large':(640,480)}) #settings.py added 'stdimage' in my apps Suppose I am uploading an image size 1800px by 1000px from my admin panel and it's giving me the same output after finishing the upload. Why image size not reducing? -
Not able to pass initial data Modelformset in form wizard for editing
I can use the modelformset in form wizard normally, and am editing a the existing data, but not able to pass the data using get_form_instance. forms.py: class BaseHostFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseHostFormSet, self).__init__(*args, **kwargs) self.queryset = Host.objects.none() HostFormSet = modelformset_factory( model=Host, form=HostForm, extra=1, formset=BaseHostFormSet ) class HostForm(forms.ModelForm): class Meta: model = Host fields = ['name','ip','os','method','description'] widgets ={ 'name': forms.TextInput(attrs={'class':'form-control','style': 'width:400px;'}), 'ip': forms.TextInput(attrs={'class':'form-control','style': 'width:400px;'}), 'os': forms.TextInput(attrs={'class':'form-control','style': 'width:400px;'}), 'method': forms.Select(attrs={'class': 'form-control','style': 'width:400px;'}), 'description':forms.Textarea(attrs={'class': 'form-control','style': 'width:400px;'}) } urls.py path('create/demo',views.FormWizardView.as_view([HostFormSet,DemoForm,CredFormSet]),name='create_demo'), path('edit/demo/<int:dm_id>',views.FormWizardView.as_view([HostFormSet,DemoForm,CredFormSet]),name='edit_demo'), views.py def get_form_initial(self, step): if 'dm_id' in self.kwargs: return {} return self.initial_dict.get(step, {}) def get_form_instance(self, step): if not self.instance_dict: if 'dm_id' in self.kwargs and step=='0': print("get_form_instance_step0") dm_id = self.kwargs['dm_id'] demo=Demo.objects.get(id=dm_id) host_dict= (demo.host_set.all()[0]) # I can see host object normally here print(host_dict) return host_dict return self.instance_dict.get(step, None) According to the doc: https://django-formtools.readthedocs.io/en/latest/wizard.html I should be able to initialize the step data using get_form_instance, In step 0, I got only the empty values and default values in the model instead of the returned object value. Please help, thanks in advance. -
get() returned more than one HorseEquipment -- it returned 3! in Django RESTApi
I want to make a REST Api GET View in Django using serializers and raw query like this: class HorseEquipmentView(APIView): lookup_url_kwarg = 'horse' def get (self, request, format = None): horse = 1 if horse != None: equipment = HorseEquipment.objects.raw('SELECT H.horse_id, E.name FROM horse_equipment H JOIN equipment E ON H.equipment_id = E.id WHERE H.horse_id =' + str(horse)) serializer = HorseEquipmentSerializer(equipment, many = True) return Response(serializer.data) else: return Response(status = status.HTTP_400_BAD_REQUEST) but on my localhost is returning error "get() returned more than one HorseEquipment -- it returned 3!". What can I change to make it work? -
How to import current login user in to form by form.py Django
I want to automatically add the name of a logged in user to the form but i don't know how to import this varaible to the form FILES >>>> forms.py class CommentForm(forms.ModelForm): class Meta: model = ArticleComment fields = ('user_name', 'body') widgets = { 'user_name': forms.HiddenInput(attrs={'value': username }), 'body': forms.Textarea(attrs={'class': 'form-control'}) } models.py class ArticleComment(models.Model): post = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE) user_name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.user_name) def get_absolute_url(self): return reverse('article', args=(str(self.id))) views.py class AddCommentView(CreateView): model = ArticleComment form_class = CommentForm template_name = 'add_comment.html' # fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['category_id'] return super().form_valid(form) success_url = reverse_lazy('index') -
How can I return a downloadable file Django
I am currently working on a project where I generate both a csv file and a config file. I would like to know if there is a way to have a href in my template that would trigger a download of those files to the user? -
GitHub Actions - Build Docker Image From Latest Branch
I'm new to dev ops and am trying to figure out how to create an automated pipeline that is triggered when our team pushes to the staging branch of GitHub. Right now, I've almost got everything, in that, when we push to staging, we ssh into our server, pull the build, stop the running container, and then start a new one. My only issue right now is that I'm not exactly sure how to pull the docker image from a specific branch on GitHub. I want to do the equivalent of git pull and then restart the docker container. Right now, I've got: - name: Pull new image run: ssh staging 'sudo docker pull ${{ secrets.AWS_ECR_REGISTRY }}/simple-django:latest' - name: Stop running container run: ssh staging 'cd code_folder; sudo docker-compose down -v --remove-orphans' - name: Start new container run: ssh staging 'cd code_folder; sudo docker-compose -f docker-compose.prod.yml up -d --build' but I'm not sure exactly where ${{ secrets.AWS_ECR_REGISTRY }}/simple-django:latest is/what it corresponds to. Does this pull from some sort of GitHub branch? Or do I have to be able to log in as an admin to the AWS server to check out what this corresponds to. Thanks -
Django, React: Static Files with Elastic Beanstalk + S3
I have a standard Django project structure with a React app: main_app settings.py asgi.py etc... tickets models.py views.py etc... react-frontend public/ src/ etc... In react-frontend in the main template index.html, I am loading my static files like so: <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="utf-8" /> <link rel="icon" href="{% static 'favicon.ico' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="{% static 'favicon.svg %}" /> <link rel="manifest" href="{% static 'manifest.json' %}" /> <title>Main App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html> When this page appears on my production server, the {% static file/directory %} is loaded fine. However, the JavaScript chunks that npm run build creates is not; they're not loaded with the static path to the S3 bucket, instead being loaded with the standard /static/path/to.js. Is there a way I can have my JavaScript that's added in through npm run build be set to my S3 bucket just like I would with {% static dir/file %}? -
Error while creating an application for Blockchain
I've installed Python 3.6 and Django 2.2.6 used the following code to install virtual environment. ''' pip install virtualenv''' '''virtualenv venv''' '''venv\Scripts\activate ''' After that, I've installed django 2.2.6 and trying create a project and application for blockchain ''' pip install django==2.2.6''' '''django-admin startproject PyChain''' '''cd PyChain''' '''python manage.py createapp blockchain ''' I'm getting the error "No module name : django" -
Django Rest Framework Returns old Data after post_save Signal
I have game,genre and producer tables. User creates new games through admin panel. After user creates a new game i need to do something but i have a problem. After new game has been created django sends signal and runs game_changed method. Problem is when i send get request to /api/game/ (Django rest framework endpoint) after i got signal of new game has been created response doesn't have this new model. More interesting is first i get count of game table through Game.objects.count i get 3 (correct) after that i send get request to game endpoint and response has 2 games. What causes this? Models: class Game(models.Model): name=models.CharField(max_length=50) producer=models.ForeignKey("Producer",on_delete=models.CASCADE) genres=models.ManyToManyField("Genre") def __str__(self): return self.name class Producer(models.Model): name=models.CharField(max_length=50) def __str__(self): return self.name class Genre(models.Model): name=models.CharField(max_length=50) def __str__(self): return self.name Signals: from django.db.models import signals from django.dispatch import receiver from .models import Game @receiver(signals.post_save,sender=Game) def game_changed(sender,**kwargs): print(Game.objects.count())#Returns 3 import requests url="http://localhost:8000/api/game/" response=requests.get(url) print(response.json())# returns 2 games instead of 3 Views: from rest_framework.viewsets import ReadOnlyModelViewSet from .serializers import GenreSerializer,GameSerializer,ProducerSerializer from .models import Genre,Game,Producer class GenreViewSet(ReadOnlyModelViewSet): queryset=Genre.objects.all() serializer_class=GenreSerializer search_fields=("name",) class GameViewSet(ReadOnlyModelViewSet): queryset=Game.objects.all() serializer_class=GameSerializer filterset_fields=("genres","producer") search_fields=("name",) class ProducerViewSet(ReadOnlyModelViewSet): queryset=Producer.objects.all() serializer_class=ProducerSerializer search_fields=("name",) -
{"detail":"CSRF Failed: CSRF token missing or incorrect."} in DRF
I'm getting {"detail":"CSRF Failed: CSRF token missing or incorrect."} error while trying to post a change password API. I'm using postman and please let me know if any more details are needed in the comment section. Thanks in advance. Serializers.py class PasswordChangeSerializer(serializers.Serializer): password = serializers.CharField(max_length=128) Views.py class PasswordChange(APIView): permission_classes = (IsAuthenticated,) serializer_class = PasswordChangeSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user = request.user password = serializer.data['password'] user.set_password(password) user.save() content = {'success': _('Password changed.')} return Response(content, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Will subprocess.call wait for the entire shell command&function to be finished?
I have a subprocess thats using the call function to run some data collection function. When I run it without shell it will get stuck within a loop and never complete its task. With shell=True it completes its task and doesn't get stuck. Is this because it just waits on the shell command to execute or is the entire function that its supposed to run being run properly? subprocess.call(['python3', f'some_help_function.py', f'--domain=http://localhost:8000'], shell=True) -
Django Rest Framework - Filter by relationship hyperlink
I hope you are well. This is my first personal project with DRF and I had the following problem. I have two models: class Area(models.Model): name = models.CharField(max_length=100) ... and class SubArea(models.Model): area = models.ForeignKey("Area", on_delete=models.CASCADE, verbose_name='Area relacionada', related_name='subareas') name = models.CharField(max_length=100) ... I was able to do something similar to what I need using HyperlinkedRelatedField class SubareaSerializer(serializers.ModelSerializer): contents = ContentSerializer(many=True, read_only=True) quizzes = QuizSerializerAux(many=True, read_only=True) class Meta: model = SubArea fields = ['id', 'name', 'description', 'quizzes', 'contents'] class AreaSerializer(serializers.HyperlinkedModelSerializer): subareas = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='subarea-detail', ) class Meta: model = Area fields = ['url','id', 'name', 'description', 'subareas',] But this is what I get using the endpoint api/area/: { "url": "http://127.0.0.1:8000/rest-auth/quiz/area/1/", "id": 1, "name": "Area 1 de teste", "description": "Area 1 de teste - descrição", "subareas": [ "http://127.0.0.1:8000/rest-auth/quiz/subarea/1/", "http://127.0.0.1:8000/rest-auth/quiz/subarea/2/" ] }, I get a list with several links to Subareas, however I need only 1 link that lists all Subareas related to this Area, for example: /api/area/1/subarea endpoint that would list all subareas in area id = 1 { "url": "http://127.0.0.1:8000/rest-auth/quiz/area/1/", "id": 1, "name": "Area 1 de teste", "description": "Area 1 de teste - descrição", "subareas": [ "http://127.0.0.1:8000/rest-auth/quiz/area/1/subarea" ] }, how can i do this using the DRF? these are … -
No reverse match "error during template rendering"
Reverse for 'all_products' not found. 'all_products' is not a valid view function or pattern name. <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url "store:all_products" %}">All</a></li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected" {% endif %}> <a class="dropdown-item" href="{{ c.get_absolute_url }}">{{ c.name|title }}</a> </li> {% endfor %} </ul> here is my my def in views.py : def all_products(request): products = Product.products.all() return render(request, 'store/home.html', {'products': products}) my urls.py: from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.all_products, name = 'all products'), path('item/<slug:slug>/', views.product_detail, name='product_detail'), path('search/<slug:category_slug>/', views.category_list, name='category_list'), ]