Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to use Proxy model without hitting the database?
I'm using proxy model to extend functionality (getters etc) of Product model. Usually I use it the proper way. ProxyProduct.objects.filter()... But there is a situation when I need to use proxy model inside the Product method because ProxyModel has method get__export_price() which I want to use in the Product.get_export_price. class Product(models.Model...): def get_export_price(self): ExportAdapter = self.get_export_adapter_class() # gets Proxy model # I can do ExportAdapter.objects.get(pk=self.pk) but it's a redundant db query return ExportAdapter(self).get__export_price() Unfortunately, I can't create fully functional Proxy objects this way: ExportAdapter(self) Is there a way to do that and avoid hitting the database the second time? EXPLANATION I have files with different Proxy models for different users. Every user has its own way to get export prices and other attributes. -
Django/Wagtail: How to check if the user has permissions to access a given Page?
I'm new to Wagtail and it has been an awesome experience so far! I am trying to solve the following problem: The user can see a list of all courses available and, depending if he has permissions in that Page or not, it will show a locker icon, as in the attached picture. Wireframe/sketch Basically, I have the following piece of code: {% for course in page.get_children %} <h2> <a href="{{ course.url }} "> {{ course.title }} </a> </h2> {% endfor %} Is there any property I can check to know if the user has or hasn't permissions for each course inside my loop? -
Django Foreign Key Reverse Filtering
I am still relatively new to Django and still struggle somewhat with ForeignKey filtering and I'd appreciate any help with my problem. I have 2 models below and in my PositionUpdateForm I need the 'candidate' field choices to be only the applicants to that position. class Position(models.Model): title = models.CharField(max_length=128) candidate = models.ForeignKey('careers.Applicant', on_delete=models.SET_NULL, related_name='candidates', blank=True, null=True ) class Applicant(models.Model): first_name = models.CharField(max_length=128) blank=False, ) position = models.ManyToManyField(Position, related_name='applicants', blank=True ) In my form I was trying each of the following: class PositionUpdateForm(forms.ModelForm): candidate = forms.ModelChoiceField(queryset=Applicant.objects.filter(???)) def __init__(self, *args, **kwargs): super(PositionUpdateForm, self).__init__(*args, **kwargs) self.fields['candidate'].queryset = Applicant.objects.filter(???) Thank you for any assistance. -
how to password confirm validation?
This code doesn't work with me. I want to check if password field is equal to confilrm_password field. now this code moves across by (if only) and when I use (else) it doesn't work what I understand here that (check_password) produce (False) always so, the question is: why this code runs with (if) only not (else) too and How to run the code by (if and else)? views.py class UserRegister(View): form_class = EditForm template_name = 'account/register.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data['password'] confirm_password = form.cleaned_data['password'] user.set_password(password) user.set_password(confirm_password) if not check_password(confirm_password, password): # Not true form.password = '' form.confirm_password = '' message_error = 'confirm your password again' return render(request, self.template_name, {'form': form, 'message_error': message_error}) else: user.save() return redirect('account:home') return render(request, self.template_name, {'form': form}) register.html {% extends 'base.html' %} {% block title %} Register {% endblock %} {% block body %} <div class="register"> <div class="container"> <h1>Register</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Registier</button> </form> </div> </div> {% if message_error %} {{ message_error }}<br> {% endif %} {% endblock %} forms.py from django.contrib.auth.forms import User from django import forms class UserForm(forms.ModelForm): … -
Django ckeditor image upload - Error 403 when trying to upload images
I've looked through all the questions regarding image upload with django ckeditor but I can't find the solution to my problem. I'm trying to enable image upload for my posts with django ckeditor but it seems I've got a problem, as I'm getting a 403 error when trying to upload them. Also, if I click on see server I get a 404 error, see screenshot screenshot 1screenshot 2 This is my code: urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('pages.urls')), url(r'', include('blog.urls')), url(r'', include('staticpages.urls')), url(r'', include('shop.urls')), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ] settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'blog', 'pages', 'shop', 'staticpages', 'ckeditor', 'ckeditor_uploader', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) STATIC_ROOT = "/home/username/myweb/static" # Media config MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #################################### ## CKEDITOR CONFIGURATION ## #################################### CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } models.py from django.db import models from django.utils.timezone import now from django.urls import reverse from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class StaticPage(models.Model): title = models.CharField(max_length=300, verbose_name="Title tag") description = models.CharField(max_length=300, blank=True, verbose_name="Description … -
django url ignoring slug argument on request
Django (1.11) app where users can make purchases. trying to give an individual user a purchase view tied to their specific purchase (if purchase[s] exist). However req'ing the purchase view redirects back to the user profile view. model: from autoslug import AutoSlugField class Purchase(models.Model): purchase_id = models.IntegerField(editable=False) amount = models.IntegerField() user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='purchases') slug = AutoSlugField(populate_from='purchase_id', default='', unique_with='user', max_length=255) date_purchased = models.DateTimeField(auto_now_add=True) def __str__(self): return 'Purchase #{}, user: {}'.format(self.purchase_id, self.user) def save(self, *args, **kwargs): if not self.purchase_id: purchase_id = str(uuid.uuid4().int) self.purchase_id = int(purchase_id[-9:]) if not self.slug: self.slug = self.purchase_id return super(Purchase, self).save(*args, **kwargs) urls: # base profile view url(r'^user/(?P<username>[0-9a-zA-Z_]*)$', views.user_profile, name="user_profile"), # purchase view url(r'^user/(?P<username>[0-9a-zA-Z_]*)/purchase/(?P<slug>[-\w]+)$', views.user_purchase, name="user_purchase"), purchase view: from .models import User, Purchase def user_purchase(request, username, slug): user = get_object_or_404(User, username=username) purchase = get_object_or_404(Purchase, slug=slug, user=user) context = { 'user': user, 'purchase': purchase } # also confirmed this html file exists in the correct folder return render(request, 'users/user_purchase.html', context) in the base profile template my url is: {% if purchases %} {% for p in purchases %} <a href="{% url 'user_purchase' user.username p.slug %}">View purchase</a> {% endfor %} {% endif %} running localhost (local server) on profile view, I can see my dummy purchase and hovering on … -
How to get django form errors as text instead of html?
I have a toast for displaying errors. $.toast({ text: '{{ form.non_field_errors }}' }) But it is returning a html format. so i am getting an error. But i would like to get text only from {{ form.non_field_errors }}. How do i do that? -
how to avoid regenerating token in activation account?
I am trying to avoid to regenerate token after the end-user click the link or expire its link for activation account via Gmail, but however, my actual status after a user clicks on the links. it works as indeed, but it regenerates. how can I avoid this? class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(pre_save, sender='account.User') def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') -
How to return both html template and string in Python Flask
I need to pass a string as well as to return a template during execution. I have tried passing variable to html page, but the test case is failing because it counts tags in output. My test condition is to pass template called quotes.html and also to return a string.(List shown in code) (May or maynot in quote.html> My Code: @app.route("/quotes/") def display_quotes(): return render_template("quotes.html",ans="<h1>Famous Quotes</h1>"+"""<ul> <li>Only two things are infinite, the universe and human stupidity, and I am not sure about the former.</li> <li>Give me six hours to chop down a tree and I will spend the first four sharpening the axe.</li> <li>Tell me and I forget. Teach me and I remember. Involve me and I learn.</li> <li>Listen to many, speak to a few.</li> <li>Only when the tide goes out do you discover who has been swimming naked.</li> </ul>""") In quotes.html: {{ans|safe}} Error Message: def test_response_nquotes(self): response = self.client.get('/quotes/') print(response.data) nquotes = sum([ 1 for quote in self.quotes if quote in response.data ]) > assert nquotes == 5 E AssertionError: assert 3 == 5 helloapp/tests.py:84: AssertionError ----------------------------- Captured stdout call ----------------------------- b'<h1>Famous Quotes</h1>\n <ul>\n <li>Only two things are infinite, the universe and human stupidity, and I am not sure … -
Go back to active sub tab after page reload
I have nav_tabs on my web page as shown in the following image. In every sub-tab, there is form-data that can be updated and once a user updates the form, I am going a page reload. So, if a user updates a form in "Primary 2 tab", after a page refresh, the selection is going to the "Primary 1 tab". Can someone please suggest how to get back to Primary 2 tab after updating the form in that sub-tab. I am using AJAX JQUERY POST method to send accross the data to the backend(which is written in python). $.ajax({ type: "POST", url: "/update_form_data_tab2", data: {'lvl_id' : lvl_id}, dataType : "json", success: function(data) { location.reload(); // suggest something here to get back to the active tab after page refresh (or) without. }, -
Django tables - Column relation to populate data
So I have these models. class Domains(models.Model): '''Domain listing for ISO''' domain_id = models.CharField(max_length=10) domain_title = models.TextField() def __str__(self): return self.domain_id #sample data output would be id title A5 A5 title A6 A6 title class SubDomain(models.Model): '''Sub-domain listing for ISO. Relationship with Domain''' domain_key = models.ForeignKey(Domains, on_delete=models.CASCADE) subDomain_id = models.CharField(max_length=10) subDomain_title = models.TextField() subDomain_objective = models.TextField() def __str__(self): return self.subDomain_id #sample data output would be id title objective A5.1 A5.1 title A5.1 objective A6.1 A6.1 title A6.1 objective My views currently are simple queries that use objects.all or objects.filter to store the list in a variable. This view is not complete but i am just testing at this point. That variable is then looped in my template tags as so: table class="table table-sm"> <tr> <th>Domain ID</th> <th>Sub Domain ID</th> <th>Sub domain Title</th> <th>Sub domain objective</th> </tr> {% for record in a6titles %} <tr> <td colspan=1>A6</td> <td>{{ record.subDomain_id }}</td> <td>titles: {{ record }}</td> </tr> {% endfor %} Now, as you can imagine. When the table populates. The domain Id loops and populates its results. Same with the sub domains. How do I generate the table such that it looks at the domain Id. Sees A5 and then only populates the subdomain … -
How to upload image in user profile model while has one to one relationship with user model in django rest framework?
I have a UserProfile model which has one to one relationship with User model. I am facing problem in uploading image by rest-framework API endpoint to nested model. Problem is: Though I am explicitly using @action() decorator, then also it is calling inbuilt create() method for saving image by POST. Then I have explicitly mentioned which method to call in urls.py. Now it shows errors. There are errors in the implementation in serializer.py and views.py. So if possible then please correct my mistakes and direct me in the correct direction. Its more than two days but still I am struck. In models.py: def user_image_upload_file_path(instance, filename): """Generates file path for uploading user images""" extension = filename.split('.')[-1] file_name = f'{uuid.uuid4()}.{extension}' date = datetime.date.today() initial_path = f'pictures/uploads/user/{date.year}/{date.month}/{date.day}/' full_path = os.path.join(initial_path, file_name) return full_path class UserManager(BaseUserManager): def create_user(self, email, password, username, **extra_kwargs): """Creates and saves a new user""" if not email: raise ValueError(_('Email cannot be empty')) user = self.model(email=self.normalize_email(email), **extra_kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, username, **extra_kwargs): """Creates and saves a new user with superuser permission""" user = self.create_user( email, password, username, **extra_kwargs) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Creates user model that supports using … -
Filter foreign key objects in model field
class ValueForService(models.Model): desk = models.ForeignKey(Desk, on_delete=models.CASCADE) price = models.PositiveIntegerField(default=4, validators=[MinValueValidator(4), MaxValueValidator(3000)]) class Order(models.Model): desk = models.ForeignKey(Desk, on_delete=models.CASCADE) buyer = models.ForeignKey(User, on_delete=models.CASCADE) ... value_for_service = models.ForeignKey(ValueForService, on_delete=models.CASCADE) What I want to do is to only show value_for_service for the selected desk. Something like value_for_service = models.ForeignKey(ValueForService.objects.filter(desk=current_desk), on_delete=models.CASCADE) -
How to ignore migrations but __init_.py?
I've been thinking about this. See here: Should I be adding the Django migration files in the .gitignore file? I agree with Robert L, that says that we should't commit our migrations. My questions is: 1) How to ignore all migrations except for the init.py file that is inside the migrations folder? 2) How to remove migrations that were already commited? I'm looking to avoid any conflicts between developers. app structure example: |_roles |__pycache__ |___init__.cpython-37.pyc |_admin.cpython-37.pyc |_forms.cpython-37.pyc |_models.cpython-37.pyc |_urls.cpython-37.pyc |_views.cpython-37.pyc |_migrations |__pycache__ |___init__.cypthon-37.pyc |___0001_initial.cpython-37.pyc |___0002_auto_20200111_1307.cpython-37.pyc |___0003_auto_20200111_1418.cpython-37.pyc |__init_.py |_0001_initial.py |_0002_auto_20200111_1307.py |_0003_auto_20200111_1418.py |__init_.py |_admin.py |_apps.py etc.. .gitignore: I'm thinking on: *./migrations/ But this would exclude the hole folder. -
django templateView compare permission
I am trying to check if account settings view, and username is a superuser then render the html. if not goes to error 403 , but how can I do this using templateview class AccountSettingsView(LoginRequiredMixin, TemplateView): template_name = 'profile/account-settings.html' if request.user.is_superuser: # error 403 else: template_name -
How to use Node.js / koa Authentication inside a django app
I recently inherited a project that is written entirely in node.js on the koa web framework. I want to write a mini app in django that talks to koa's authentication backend, and uses that token to run through certain tasks in the new django app. I've looked at the django.contrib.auth.backends.RemoteUserBackend but from what it looks like, it seems to only apply to FreeIPA/IdM, Active Directory, LDAP servers. Can this be used to authenticate with an external node.js server? Or is there another authentication backend i should be looking at? -
Retrieving id field in views.py in a POST request
HTML file: <form enctype="multipart/form-data" method="POST" action="#"> {% csrf_token %} {% for field in form %} <label for="{{ field.id_for_label }}" class="label" style="padding: 5px"> {{ field.label }} </label> {{ field }} <input type="hidden" name="photo_id" value="{{ field.auto_id }}"> {% endfor %} <input type="submit" value="Upload" class="button is-dark"> </form> models.py file: from django.db import models # Create your models here. class Gallery(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=10) photo = models.ImageField(upload_to='images/', blank=False) username = models.CharField(max_length=10) forms.py file from xml.dom.minidom import Text from django import forms from . models import * from django.core import validators class ImageForm(forms.ModelForm): class Meta: model = Gallery fields = ('id', 'name', 'photo', 'username') labels = { 'name': 'Name', 'photo': 'Photo', 'username': 'Username' } views.py file def upload(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() #I have tried both the methods but neither of them are giving me the output keyword = request.POST.get("photo_id") keyword = form.cleaned_data.get("photo_id") print(keyword) return redirect('dashboard') else: form = ImageForm() return render(request, 'upload.html', {'form': form}) The HTML code is used to upload an image and store in the database. Uploading of image is working fine. The data is being sent in a POST request. So, when I upload a particular image, the id of the … -
How to post comments using Ajax in Django?
Hello I am working on blog project for practice. I have made a function to post comment on a blog but it is posted after reloading the page.I want to post comments without reloading the page. Here is my comment form <form class='my-4' id='comment' action='/main/comment/' method='post'>{% csrf_token %} <div class="form-group"> <input type='hidden' id='id' name='id' value='{{blog.blog_id}}'> <label for="text"><b>POST YOUR Comments HERE</b></label> <textarea class="form-control" id="text" name='text' rows="3"></textarea> </div> <button type="submit" class='btn btn-primary '>POST COMMENT</button> </form> Here is my function if request.method=="POST": text=request.POST['text'] id=request.POST['id'] user=request.user comment=Comment(text=text,user=user,blog_id=id) comment.save() return redirect('/main/blogs/'+ id+'/') URL path('comment/',views.comment,name='comment') Kindly help me with this. I am a beginner. -
How can retrieve brands based on specific category?
Here are my product and category models Category Model class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ('name',) verbose_name = ('category') verbose_name_plural = ('categories') def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_list_by_category', args=[self.slug]) Product Model class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='brands') retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE, related_name='suppliers') title = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, db_index=True) url = models.URLField() description = models.TextField() color = models.CharField(max_length=255, blank=True) material = models.CharField(max_length=255, blank=True) weight = models.CharField(max_length=255, blank=True) dimensions = models.CharField(max_length=255, blank=True) available = models.BooleanField(default=True) price = models.DecimalField(max_digits=10, decimal_places=2) cost_price = models.DecimalField(max_digits=10, decimal_places=2) image_1 = models.ImageField(upload_to='product_images/') image_2 = models.ImageField(upload_to='product_images/') image_3 = models.ImageField(upload_to='product_images/') created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) class Meta: ordering = ('?',) verbose_name = ('product') verbose_name_plural = ('products') index_together = (('id', 'slug'),) def __str__(self): return self.title def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) Here is the views.py from django.shortcuts import render, get_object_or_404 from .models import Product, Category, Brand # Create your views here. def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'product_list.html', {'category': category, 'categories': categories, 'products': products}) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, … -
Django DEBUG=False getting server 500 error
I'm getting server error(500) after I set DEBUG to False, both in local and after deploying to Heroku. Everything is Ok when DEBUG mode is True. Thanks for help -
How to embed a jupyter notebook into a django app?
We have our internal wiki system based on django. Our team does a lot of analysis in jupyter notebooks and then we report the results on our wiki. Currently I am looking for ways to embed notebooks in our wiki: We have our Django website which authorises users, manages content, etc. We want to make some pages with analysis interactive, so a reader can change the code, run it, and look at the output. We want to have our own UI (our wiki page with footer, header, etc). Actually from Jupyter’s UI we need only cells and their output. At the same time we want to keep most of the features of the Jupyter Notebook related to graphics, for example, widgest, extensions, etc. We want to change as little Jupyter code as possible. It seems we can do a lot through plugins / services / extensions, there is nice JupyterHub for authentication, spawning notebooks, etc. But I have not found how I can integrate (embed) a notebook inside my django app? -
PATCH is not working django rest framework
I am performing CRUD,all endpoints are working except update(patch).Getting KeyError at /apponboarding/app/1/ 'email' if I am passing only the field which I want to update. Any help is highly appreciated. viewset class AppOnboardingView(viewsets.ModelViewSet): queryset = AppOnboarding.objects.all() serializer_class = AppOnboardingSerializer lookup_field='id' authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated,IsMaintainer] serializer class AppOnboardingSerializer(serializers.ModelSerializer): class Meta: model = AppOnboarding fields = ['id', 'email', 'product_name', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): app_onboard = AppOnboarding( email=self.validated_data['email'], product_name=self.validated_data['product_name'] ) password = self.validated_data['password'] app_onboard.set_password(password) app_onboard.save() def save(self): app_onboard = AppOnboarding( email=self.validated_data['email'], product_name=self.validated_data['product_name'] ) password = self.validated_data['password'] app_onboard.set_password(password) app_onboard.save() -
Unable to redirect Django urls
Given below is my html, which I am using to redirect based upon the username. {% extends "base.html" %} {% block content %} <div class="container"> <h1>You are now logged in!</h1> {% if user.username == "Dhruv" %} <h2><a href="{% url 'profiles:adminHome'%}">Go to Home Page</a></h2> {% else %} <h2><a href="{% url 'profiles:userHome'%}">Go to Home Page</a></h2> {% endif %} </div> {% endblock %} The html page it is redirected to: {% extends "base.html" %} {% load bootstrap4 %} {% block content %} <div class="container"> <br> <br> <h1 style="margin: auto; text-align:center; border-radius: 2px; border: 2px dotted black; padding: 20px;">Welcome to your home page, {{ user.username }}!</h1> <br> {% if y %} <h3>Balance amount is {{ y.balance }}</h3> {% endif %} <h3>Select vendor to pay!</h3> <br> <form method="POST" action="/profiles/updatingBalance"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" value="1" id="defaultUnchecked" name="defaultRadios"> <label class="custom-control-label" for="defaultUnchecked">Vendor 1</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" value="2" id="defaultUnchecked" name="defaultRadios"> <label class="custom-control-label" for="defaultUnchecked">Vendor 2</label> </div> <input type="" class="form-control" id="amount1" name="amt" aria-describedby="emailHelp" placeholder="Enter amount"> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {% endblock %} Views.py: def updatingBalance(request): if request.method=="POST": ven_id = request.POST["defaultRadios"] amount = request.POST["amt"] x = employee.objects.filter(id = request.User.id) x.balance = x.balance - amount p = transaction(vendor_id =ven_id.value, emp_id = request.User.id, debit=amount, credit=0) … -
Nginx + Gunicorn problem with Let's Encrypt certificate
I have a problem with a Django application served by Nginx + Gunicorn: configured in HTTP it works correctly; after installing and requesting an SSL certificate with Let's Encrypt and changing the configuration, the request to the application times out. This is the configurations I'm using: Socket: [Unit] Description=Gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Systemd service: [Unit] Description=Gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=user WorkingDirectory=/var/www/application ExecStart=/var/www/application/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ DjangoApp.wsgi:application [Install] WantedBy=multi-user.target Nginx configuration: upstream app_server { server unix:/run/gunicorn.sock fail_timeout=0; } server { listen 443 ssl; server_name example.com; access_log /var/log/nginx/example.access.log; error_log /var/log/nginx/example.error.log; location /static { alias /var/www/application/static; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; } server { listen 80; server_name example.com; return 301 https://$host$request_uri; } I also tried to disable the firewall, thinking it might be a network problem, but it keeps giving me the same error. I have read several other answers, but none has succeeded in giving me a solution. Any help is more than appreciated. Thank you. -
Django ManyToMany Relationship with Through model filtering
Suppose I have the following setup (models.py) class Person(models.Model): name = models.CharField(....) class EventInfo(models.Model): attending = models.BooleanField(default=True) event = models.ForeignKey('Event') person = models.ForeignKey('Person') class Event(models.Model): start = models.DateTimeField(....) .... participants = models.ManyToManyField(Person, through=EventInfo) I am aware of the fact that participants is in fact an object of type RelatedManager, and i can query it like that: e = Event.objects.get(...) e.participants.filter(name="John") #gives me the Person named 'John' But what I am missing is an intuitive way to (e.G.) filter for all persons that are attending my Event, by making use of the specified through-model. I know I can do one of the following things: e = Event.objects.get(...) # would give me a queryset of EventInfo objects, but theres no easy way to get all persons from that: qs = EventInfo.objects.filter(event=e, attending=True) # would give me in fact all persons, but seems rather unintuitive: qs = Person.objects.filter(eventinfo__event=e, eventinfo__attending=True) # same thing, quite unintuitive having to query from "the other side" e.participants.filter(eventinfo__attending=True) What I would like to write: e = Event.objects.get(...) e.participants.filter(attending=True) which would give me a list of persons. This is not possible because participants filters on Person and not on EventInfo Am I missing something here?