Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i get access to a db, so i can get the organizations id?
I am working on creating notices for a particular app. And I need to make the API for this dynamic as I am collecting information from the db, not the models.py file. Right now, I'm using dummy data so it works, but I need to get the organizations id from the db so it is dynamic. Any ideas how? ANY help would be appreciated! class CreateNoticeAPIView(views.APIView): def post(self,request): serializer = CreateNotice(data=request.data) if serializer.is_valid(): db.save("noticeboard", "613a1a3b59842c7444fb0220", serializer.data) return Response( { "success":True, "data":serializer.data, "message":"Successfully created" }, status=status.HTTP_201_CREATED) return Response( { "success":False, "message":"Try again!" }, status=status.HTTP_400_BAD_REQUEST) That's the view in the views.py file for creating the notices. The second parameter in db.save is the dummy data for organization id (i.e "613a1a3b59842c7444fb0220"). Thanks in advance! -
Refrain Django from translating dates
I have a django app where I'm using translations. My problem is that django is translating the dates as well, and I want to keep the dates in the same format for all languages. Is there a solution to this? It is making other problems for me, forms are not validating dates because of this. I'm getting the date picker in english as shown in the following image, whereas I need it in French if the language is set to french. Here are my language settings USE_I18N = True # use internationalization USE_L10N = True # use localization from django.utils.translation import gettext_lazy as _ LANGUAGES =[ ('en', _('English')), ('fr', _('French')), ('ar', _('Arabic')),] Thank you. -
Django why is this code blocking http requests
Here is the module: import threading import time import pandas as pd from binance.client import Client import json from api_create_alert.models import Alerts from service_get_data.get_api_secret import get_secret alerts = Alerts.objects.all().values() df = pd.DataFrame(alerts) data = get_secret() data = json.loads(data) client = Client(data['BINANCE_PUBLIC_API'], data['BINANCE_SECRET_API']) def price_watch(): interval = 10 while True: coins = client.get_all_tickers() for coin in coins: symbol = coin['symbol'] price = float(coin['price']) rows = df[((df.symbol == symbol) & (df.direction == 'ABOVE') & (price > df.price)) | ((df.symbol == symbol) & (df.direction == 'BELOW') & (price < df.price))] if len(rows) > 0: print(rows) time.sleep(interval) thread = threading.Thread(target=price_watch) thread.start() Importing it from apps.py: def ready(self): if os.environ.get("RUN_MAIN") == "true": import service_price_watch.price_watch So it's a loop that runs every 10 seconds, each time the loop starts running the Django app is blocked no response is received until the loop is done, now why is that happening when I'm using the threading module, isn't the purpose of threading module is to make Async operations? -
Deploy Django app on AWS EC2 behind firewall
This article here shows how to deploy a Django app on AWS EC2 on a public domain (i.e. having a public IPv4 DNS) I am trying to deploy a Django app within a confined network of AWS behind a firewall, where each AWS account only has a private IPv4 DNS and not a public one. The article above only works for an AWS EC2 that has public access (and hence a public IPv4 DNS). Specifically, this paragraph of instruction: Note: Add instance’s DNS name/IP to “Allowed Hosts” in settings.py ALLOWED_HOSTS=['EC2_DNS_NAME'] ... In a browser, navigate to public DNS of the instance, make sure to append port “8000” at the end and if everything was properly configured, it will show the index page of the application. For example: www.ec2dnsname.com:8000 If I follow all the steps in that article up the paragraph above, when I do this in my EC2: curl http://xxx.xxx.xx.xxx:8000 I am able to get the HTTP request of the standard Django index page in HTML form. This means that my app is successfully deployed. But where exactly ? What should be the address to enter in a browser to access this index page? Accessing the following address in a … -
Sending emails through django SMTP without form data being sent through on refresh?
Hi I'm trying to build a contact form where the user submits the form and then it is sent via email to the client. Everything is working fine but I noticed that the form data is sent through to the email even by refreshing the page. Any ideas on how to fix this? //views.py file def contact(request): if request.method == "POST": name = request.POST.get('full-name') email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') data = { "name": name, "email": email, "subject": subject, "message": message, } message = ''' New message: {} From: {} '''.format(data['message'], data['email']) send_mail(data["subject"], message, '', ['email@gmail.com']) return render(request, "contact.html", {}) /// settings.py file env = environ.Env() environ.Env.read_env() EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = env('EMAIL_HOST') EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False -
NoReverseMatch in Django, i can't access to details of the order each customers
I am trying to see the orders of each customer, but I get this error views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import OrderForm def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request): form_value = OrderForm() if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form_value = OrderForm(instance=order) if request.method == 'POST': form_value = OrderForm(request.POST, instance=order) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method == 'POST': order.delete() return redirect('/') context={'item':order} return render (request, 'accounts/delete.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/', views.createOrder, name='create_order'), … -
Django-apscheduer - Error getting due jobs from job store 'default': connection already closed
I use django-apscheduler and Postgresql in my project. After several hours of running, I start to get this error "Error getting due jobs from job store 'default': connection already closed". I'm new to django, so if anyone who faced the same issue could share with a solution or ideas, I would be extremely grateful. I have seen people had the same problem, but with no solution. -
How to link two models with one being a question and the other the answers
I have a model Poller that contains a question and two related answer options (poller_choice_one and two) and another model Vote for checking if a user voted for choice one or two. So here is the problem: How can I best structure and render the forms/logic so any user can vote Foo or Bar for a certain question? Right now I tried to render a Poller object with its choice fields as div. But how would I then enable a user to vote for one of the two choices? (simple submit button or via a form?) And does it make sense to separate the Models as I did or could I even build this logic using a single model? Poller model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(Account, on_delete=models.CASCADE) # Shall the choices be isolated as well into the Vote model? poller_choice_one = models.CharField(max_length=30) poller_choice_two = models.CharField(max_length=30) Vote Model class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='user') poller_choice_one_vote = models.BooleanField(default=False) poller_choice_two_vote = models.BooleanField(default=False) -
'Meal' object is not iterable django rest framework
I'm making an api with the ability to add a product to the cart, when I receive an empty basket, everything works, but as soon as the product gets into the basket, it gives me an error 'Meal' object is not iterable It's models.py class Meal(models.Model): """Meal""" title = models.CharField(max_length=255) description = models.TextField(default='The description will be later') price = models.DecimalField(max_digits=9, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True) slug = models.SlugField() class CartMeal(models.Model): """Cart Meal""" user = models.ForeignKey('Customer', on_delete=models.CASCADE) cart = models.ForeignKey('Cart', verbose_name='Cart', on_delete=models.CASCADE, related_name='related_meals') meal = models.ForeignKey(Meal, verbose_name='Meal', on_delete=models.CASCADE) qty = models.IntegerField(default=1) final_price = models.DecimalField(max_digits=9, decimal_places=2) class Cart(models.Model): """Cart""" owner = models.ForeignKey('Customer', on_delete=models.CASCADE) meals = models.ManyToManyField(CartMeal, related_name='related_cart', blank=True) total_products = models.PositiveIntegerField(default=0) final_price = models.DecimalField(max_digits=9, decimal_places=2, default=0) in_orders = models.BooleanField(default=False) for_anonymous_user = models.BooleanField(default=False) It's serializers.py class CartMealSerializer(serializers.ModelSerializer): meal = MealSerializer(many=True) class Meta: model = CartMeal fields = ['id', 'meal', 'qty', 'final_price'] class CustomerSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = Customer fields = '__all__' class CartSerializer(serializers.ModelSerializer): meals = CartMealSerializer(many=True) owner = CustomerSerializer() class Meta: model = Cart fields = '__all__' It's views.py Here I call the get method, after which I get an error class CartViewSet(viewsets.ModelViewSet): serializer_class = CartSerializer queryset = Cart.objects.all() @staticmethod def get_cart(user): if user.is_authenticated: return Cart.objects.get(owner=user.customer, for_anonymous_user=False) return Cart.objects.get(for_anonymous_user=True) … -
UniqueConstraint throwing an IntegrityError on the deleted row
I have a model with UniqueContraint class UserChallenge(models.Model): id = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4) member = models.ForeignKey('people.Person', on_delete=models.PROTECT, related_name='challenges', null=False) challenge = models.ForeignKey(Challenge, on_delete=models.PROTECT, related_name='user_challenges', null=False) recurring = models.BooleanField(default=False) class Meta: constraints = [ models.UniqueConstraint(fields=['member', 'challenge'], condition=Q(recurring=False), name='unique_member_and_challenge') ] By this I want to prevent of row dublications with the same challenge and member and it works fine. However, when I am trying to create a UserChallenge after a deletion of one existing, it still throws an IntegrityError. What I mean is that I deleted a row of UserChallenge with certain member and challenge, and when I am trying to add new record with this data, it still throws an error. File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/modelcluster/forms.py", line 348, in save instance = super(ClusterForm, self).save(commit=(commit and not save_m2m_now)) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/forms/models.py", line 468, in save self.instance.save() File "/Users/islom/projects/pyHomebase/homebase/challenges/models.py", line 258, in save super().save(*args, **kwargs) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 1270, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/Users/islom/projects/pyHomebase/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1416, in execute_sql … -
Django: How to access model fields via a OneToOne relationship in views.py?
in models.py i have tow models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='static/images/account/avatar', default='/static/images/default-avatar.png') bio = models.CharField(max_length=300, blank=True, null=True) class Author(models.Model): user = OneToOneField(Profile, on_delete=models.CASCADE) in views.py in want to access username (it is in User model) the code in views.py: def author(request, username): authors = ... context = { 'authors': authors } return render(request, 'account/profile.html', context) what should be placed instead of three points in front of the authors=? for example authors = Author.user.user.get(username=username) but it don't work. -
How to structure Django question model having two possible answer options
I am currently trying to figure out the best way to structure a couple of model relationships in my Django project. There are four models: Account Model which handles registered users Poller Model which handles questions raised by users including two options two answer it Vote Model which handles the answers by users made to a question/poller Comment Model which handles the comments made by users to a question/poller I don't think that having two choice fields as boolean in the Vote model will work in a convenient way. So how to best handle such case when having two options for a question when a user can only vote for Foo or Bar? Also should the user fields directly link to the user model via a OneToOne field? Poller model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.CharField(max_length=100) # replace this with OneToOne relationship to the user model? poller_text = models.CharField(max_length=250) # Populated at post by user who publishes the poller poller_choice_one = models.CharField(max_length=30) poller_choice_two = models.CharField(max_length=30) # Poller votes made by community // create new model for these? poller_choice_one_votes = models.IntegerField(default=0) poller_choice_two_votes = models.IntegerField(default=0) Vote Model class Vote(models.Model): poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='votes') user = models.ForeignKey(Account, on_delete=models.CASCADE, … -
How to get DRF-api in OpenAPI using drf-yasg?
I'm building a simply API using Django Rest Framework. This API does not store anything, but functions as a proxy to another API to query whether a store has milk. So I made a simple serializer and view: class HasMilkSerializer(serializers.Serializer): store = serializers.CharField(min_length=6, max_length=6) passage_at = serializers.DateTimeField() class HasMilkView(CsrfExemptMixin, APIView): http_method_names = ['post'] authentication_classes = [BasicAuthWithKeys] serializer_classes = [HasMilkSerializer] def post(self, request): store = request.data['store'] visit_at = parser.parse(request.data['visit_at']) return Response({'store': store, 'has_milk': has_milk(store, visit_at)}) This works great, so now I want to document this in OpenAPI specs using drf-yasg. I've installed it and swagger shows some info, but it doesn't show any specs on parameters or responses (see screenshot below). What do I need to do to get swagger to properly document my endpoint? Do I need to define it further in swagger, or do I need to change the endpoint so that swagger can properly document it? -
Hello, what's the best way to create an ordering for model based on it's group category
I'm in a bit of a situation, I have Two models class Category(models.Model): title = models.CharFiels(max_length=200) def __str__(self): return self.title class Question(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) order = models.PositiveSmallIntegerField(default=0, editable=False) def __str__(self): return self.title ##Tried solution. For the above I decided to try using signals @receiver(pre_save, sender=Question) def pre_save_order_field(sender, instance, **kwargs): # get object before save, and +1 to the order field before save pass My problem is how to increment order field with respect to the current question group I'm doing input with django admin page. -
I can't load a Django template partial from a JQuery ajax call
I need to send a list from an ajax call using JQuery, and send a response with Django {{ variables }} inside them, I tried everything, but the JQuery always loads the entire current page instead of loading the html file that contains the template partial, which is just <!-- city_dropdown_list_options.html --> <option value="">----city list----</option> {% for city in cities %} <option value="{{ city.pk }}">{{ city.name }}</option> {% endfor %} Here's the template where the JQuery is located person_form.html {% extends 'base.html' %} {% load i18n %} {% load static %} {# NOTE: templates must be defined into a folder having the same name than the application, like here countries/person_list.html, because Django automatically search from <template_folder_in_app_folder/app_name/template.html #} {% block content %} <h2>{% trans "Person Form" %}</h2> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save</button> <a href="{% url 'person_changelist' %}">Nevermind</a> </form> <div id="test"></div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> {# <script src="{% static 'js/test.js' %}"></script> #} <script> $("#id_country").change(function (){ // getting the url of the load_cities view var url = $("#personForm").attr("data-cities-url"); // get the selected country id from the html element var countryId = $(this).val(); $.ajax({ url: url, data: { // adding the countryId to GET parameters 'country': countryId }, … -
Get image from django rest framework into react-native
I have an api in django that i use to get data into my react native application. I need to get the image for every article which only shows its id. like this { "id": 5, "title": "sdadasd", "author_name": "ibtsam", "image": [ 2 ], "author": 2, "published": "2021-09-13", "modified_on": "2021-09-13", "excerpt": "asdasda", "content": "dasdasdas", "status": "published" }, I need to know how can i get the image path in my react native application. My serializers.py class is as follow: from rest_framework import serializers from blog.models import Post from blog.models import Image from versatileimagefield.serializers import VersatileImageFieldSerializer from rest_flex_fields import FlexFieldsModelSerializer class ImageSerializer(FlexFieldsModelSerializer): image = VersatileImageFieldSerializer( sizes=[ ('full_size', 'url'), ('thumbnail', 'thumbnail__100x100'), ] ) class Meta: model = Image fields = ['pk', 'name', 'image', 'full_size'] class PostSerializer(FlexFieldsModelSerializer): author_name = serializers.CharField( source='author.username', read_only=True) class Meta: model = Post fields = ('id', 'title', 'author_name', 'image', 'author', 'published', 'modified_on', 'excerpt', 'content', 'status') expandable_fields = { 'image': (ImageSerializer, {'many': True}), } -
AWS w/nginx redirect to docker containers; getting bad gateway 502
The setup is a RHEL AWS instance. On this instance, nginx is installed and working. That means if I go to http://[root] I get the html in the nginx folder like I'm supposed to. If I go to http://[root]/[sub1] I also get the other html in the nginx folder like I'm supposed to. Now, http://[root]/[sub2] is a django server in a docker container. When runserver, the django app is listening on http://127.0.0.1:8000. My docker container translates :38000->:8000 via docker-compose.yml. My nginx.conf file looks like this: server { listen 80; root /usr/share/nginx/html; location / {} location /test { index text.html; alias /usr/share/nginx/html; } location /mod { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://127.0.0.1:38000; } } While the root and /test (sub1) locations work, whenever I go to /mod (sub2), I get a 502 Bad Gateway. My docker-compose.yml (version 2) contains ports: 38000:8000. When I create the container, I use docker-compose run --name mod mod. Any suggestions? -
Problems with Django when trying to show error message when form insn't valid
Description In my applicattion i have a user registration form, but, when simulating not following the recommendations for form validation, i get an httpresponse error. But, what i'm trying to do is display an error message using the message framework from django Error page Code My template {% block body %} {% if messages %} {% for message in messages %} <div class="text-center alert alert-{{ message.tags }}"> {{ message|safe }} </div> {% endfor %} {% endif %} {% load crispy_forms_tags %} <form class = "" method="post" action="{% url 'registro' %}"> {% csrf_token %} {{registro_form|crispy}} <button class = "btn btn-primary" type="submit">Registrar</button> </form> {% endblock body %} My Form class NovoUsuarioForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] def save(self, commit = True): user = super(NovoUsuarioForm, self).save(commit=False) user.username = self.cleaned_data['first_name'] user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user My View class RegistroView(generic.View): def get(self,request, *args, **kwargs): return render(request, 'main/registro.html', {'registro_form': NovoUsuarioForm()}) def post(self,request, *args, **kwargs): form = NovoUsuarioForm(request.POST) if form.is_valid(): user = form.save() login(request,user) messages.success(request, "Registration successful." ) return HttpResponseRedirect(reverse('pesquisa')) messages.error(request, "Unsuccessful registration. Invalid information.") Other Info When i go back to the form page, from the error page after the post method, … -
GraphQL Variables 3 level
mutation CreateArticle( $id: ID!, $p: [AuthorInput] ) { article( id: $uuid p: $p ) { id } } Variable: { "id":1, "p": [{ "id":5, "x": [ { "id": 5 "text": "Text 1" }, { "id": 7 "text": "Text 2" }, ] }] } I still have an attachment in AuthorInput how do I write annotation in attachments? Arguments AuthorInput id ID! question [QuestionInput] Arguments QuestionInput id ID! text String -
Using Mask-RCNN with Flask and TF 2.5.0 rc3
Minimal repro with Flask. # app.py # run with: flask run from flask import Flask app = Flask(__name__) import tensorflow as tf import numpy as np from mrcnn import model as modellib from mrcnn.config import Config import cv2 class BaseConfig(Config): # give the configuration a recognizable name NAME = "IMGs" # set the number of GPUs to use training along with the number of # images per GPU (which may have to be tuned depending on how # much memory your GPU has) GPU_COUNT = 1 IMAGES_PER_GPU = 2 # number of classes (+1 for the background) NUM_CLASSES = 1 + 1 # Most objects possible in an image TRAIN_ROIS_PER_IMAGE = 100 class InferenceConfig(BaseConfig): GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Most objects possible in an image DETECTION_MAX_INSTANCES = 200 DETECTION_MIN_CONFIDENCE = 0.7 def load_model_for_inference(weights_path): """Initialize a Mask R-CNN model with our InferenceConfig and the specified weights""" inference_config = InferenceConfig() model = modellib.MaskRCNN(mode="inference", config=inference_config, model_dir=".") model.load_weights(weights_path, by_name=True) # model.keras_model._make_predict_function() return model detection_model = load_model_for_inference("mask_rcnn_0427.h5") @app.route('/detect') def ic_model_endpoint(): image = cv2.imread('img.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = detection_model.detect([image], verbose=1) print(results) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" Using the fork at https://github.com/sabderra/Mask_RCNN, but you can't post issues there, so I figured I … -
How to enable https in Django using already exist key
For generating certificates i using openssl command. I'm run my django app on docker using nginx proxy.I'm new with this, therefore i read some article for lunching my app . This my defaulf.conf: upstream rancher { server api_django:8080; } map $http_upgrade $connection_upgrade { default Upgrade; '' close; } server { listen 443 ssl http2; server_name <my domain name> www.<my domain name>; ssl_certificate /etc/ssl/private/cert.pem; ssl_certificate_key /etc/ssl/private/key.pem; location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://rancher; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 900s; } } server { listen 80; server_name <my domain name> www.<my domain name>; return 301 https://$server_name$request_uri; } In seting.py i set such parameters: CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') My docker-compose.yml version: '3.7' services: api_django: volumes: - static:/static env_file: - .env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static - /root/docker_ssl_proxy:/etc/ssl/private ports: - "80:80" - "443:443" depends_on: - api_django volumes: static: When i running my docker-compose nothing is changed -
OperationalError at /admin/my_app/users/- Django
i'm adding a picture of the error in django page (it happend after i put another line in models.py and did "pip install pillow", when i remove the line it works as usual) PLEASE TELL ME IF YOU WANT TO SEE MY CODE OR SOMETHING ELSE, BECAUSE THE REST WORKS FINE -
How to render foreignkey relationship in Django
I have a simple ManyToOne relationship where users can post comments to a poller object. Comments Model class Comments(models.Model): poller = models.ForeignKey(Pollers, on_delete=models.CASCADE, related_name='comments') created_on = models.DateTimeField(auto_now_add=True) comment = models.CharField(max_length=250) created_by = models.CharField(max_length=80) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) The View def single_poller(request, poller_id): """retrieves the item clicked by the user from DB and renders the single_poller template for further user interaction """ # Retrieve the item via get poller = Pollers.objects.get(poller_id=poller_id) # Increase the view field of the object by poller.poller_views += 1 # Save the changed instance and overwrite new view integer poller.save() # Get the form for comments form = CommentsForm context = { 'poller': poller, 'form': form } return render(request, 'pollboard/single_poller.html', context) Now I want to render the comments for each poller into my template like so <div id="comments-choice-one-wrapper" class="comments-wrapper"> {{ poller.comments.comment }} </div> Somehow it doesn't render the comment I created beforehand. I checked in Django admin if the comment is rly related to the poller and this looks just fine. -
Asking help for a user creation form validation
I'm working on a user creation form and I think I did everything right until I submit the form it does not save on the database. My views.py in creating the view and the user validation form. from journal.forms import CommentForm, CreateUserForm from django.contrib.auth.forms import UserCreationForm from .models import * def signup(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() context= {'form': form} return render(request, 'account/signup.html',context) forms.py the form handled with a widget connected to my static file, everything seems to be fine class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': TextInput(attrs={ 'class': 'form-control', }), 'email': TextInput(attrs={ 'class': 'form-control', }), 'password1': TextInput(attrs={ 'class': 'form-control', }), 'password2': TextInput(attrs={ 'class': 'form-control', }), } -
how do i get the current username in my vieuw?
i am trying to get the username of the current user in my vieuw.py it will has to replace the fake_cur_user. and should insert the username tryed a whole lot but i cant find the right way. pls help import datetime from django.urls import reverse from django.views.generic import CreateView from odin.actie.actie import Actie from odin.actie.actie_styleformfields import styleFormFields from odin.medewerker.medewerker import Medewerker # noqa from project.settings.base import fake_cur_user class CreateActie(CreateView): template_name = "odin/actie/actie_aanmaken_form.html" model = Actie fields = '__all__' def get_success_url(self, **kwargs): return reverse("create_inzetlijst", kwargs={'pk': self.object.pk}) cur_user_yf = 0 cur_user_team = "" initial_gespreksgroep = "" cur_user_yf = fake_cur_user # TODO: fake server val vervangen door LDAP waarde - staat nu opgeslagen in base.py if not cur_user_yf == 0: try: cur_user_team = Medewerker.objects.values_list('team', flat=True).get(youforce=cur_user_yf) except: