Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run single application from django project?
I have created three applications in a django project with three different database. I want to run one specific application from the project.How can I do this? Any idea -
How in Django admin create Groups with permissions for models programmatically?
I want to create two groups "Driver" and "Administrator". Each group should be have deference permissions for models. "Administrator" able to add, delete and view certain models. "Driver" able just add and view certain models. What is the best approach to make this done? -
Django - models.py - Does get_absolute_url function take conditions?
class Category(models.Model): '''Category for men's and women's items''' gender = models.IntegerField(choices=[ (1, 'Women'), (2, 'Men'), ], default=1) name = models.CharField(max_length=100) description = models.CharField(max_length=300, blank=True) uploaded_date = models.DateTimeField( auto_now_add=True, null=True, blank=True) class Meta(): verbose_name_plural = 'Categories' def __str__(self): return self.get_gender_display() + ' ' + self.name def get_absolute_url(self): if # condition: more than 1 value passed from url return reverse('boutique:category', kwargs={'gender': self.get_gender_display(), 'category_pk': self.pk}) else: return reverse('boutique:show-all', kwargs={'gender': self.get_gender_display()}) Question: how to work out the logic for get_absolute_url function to work more dynamically? Or is it not supposed to work dynamically? In the if statement above, I want to place a condition which checks how many values passed from url, so that it can decide which view to render. Is it possible? or should I just create get_FOO_url() function separately for rendering each view with different values passing in from url? -
Dockerize a Django app with a MySQL container
I have an app developed in Django (2.2.7) with python (3.8.0), Docker (19.03.5) and docker-compose (1.25.2) running in Windows 10 pro. I want to Dockerize it with changing the sqlite3 database for a MySQL database. I've already write this Dockerfile: FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code2 WORKDIR /code2 ADD . /code2/ RUN pip install --upgrade pip && pip install -r requirements.txt RUN pip install mysqlclient COPY . /code2/ And this docker-compose.yml file: version: '3' services: db: image: mysql:5.7 ports: - '3306:3306' environment: MYSQL_DATABASE: 'my-app-db' MYSQL_USER: 'root' MYSQL_PASSWORD: 'password' MYSQL_ROOT_PASSWORD: 'password' volumes: - .setup.sql:/docker-entrypoint-initbd.d/setup.sql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db Also I have change the default database configurations in settings.py for this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my-app-db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': 3306, } } After all of this the docker compose works and the app starts, but the problem is that the tables in the database are not created. I've tried with these How do I add a table in MySQL using docker-compose, Seeding a MySQL DB for a Dockerized Django App or this Seeding a MySQL DB … -
Accessing via www. will show Nginx welcome page [+ Gunicorn + Django]
Nginx + Ubuntu 18.04 + Django 2.2.10 Accessing directly via "www.examples.com" will show nginx welcome page, but accessing anything else--"examples.com", "https://examples.com", "https://www.examples.com"--will work as expected. On DigitalOcean, I have two A-type records [www.examples.com, examples.com] directing to the IP address--I believe they are correctly set up. On my Django project, I have ALLOWED_HOSTS = ['localhost', 'examples.com', '137.68.49.136', 'www.examples.com'] set. Here is my /etc/nginx/sites-available/project: server { server_name examples.com www.examples.com; charset UTF-8; error_log /home/jay/eco/nginx-error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/jay/eco/static; } location /media/ { alias /home/jay/eco/media/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/examples.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/examples.com/privkey.pem; # managed by Certb$ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = examples.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80; server_name examples.com; return 404; # managed by Certbot } I believed this was everything but apparently not. What am I missing? -
Upload multiple images at once django
How can I submit 3 images at once with a single input. class Image(models.Model): imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) image = models.FileField(upload_to ='pictsagram/') -
heroku crash after 60 seconds for my telegram bot
I create a telegram bot with pyTelegramBotAPI and deployed on the heroku , after this my bot working correctly but after 60 seconds my bot crashed and does't work anytime until restart app with heroku restart web.1 my bot working again. this is my bot file : from django.shortcuts import render from telebot import types import telebot import random TOKEN = 'My_BOT_TOKEN' def listener(messages): for m in messages: if m.content_type == 'text': print(str(m.chat.first_name) + " [" + str(m.chat.id) + "]: " + m.text) bot = telebot.TeleBot(TOKEN) bot.set_update_listener(listener) some other code for my commands bot.polling() and this is my Procfile: web: sh -c 'cd ./bot/ && python views.py' this is heroku logs : State changed from starting to crashed Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch Stopping process with SIGKILL Process exited with status 137 -
Django passing data to html
Ok, I'm stuck and I don't know what I'm doing wrong. I have database and i need to fetch data from it and render it in HTML. I've watched few tutorials and it doesn't seem hard but it's not working for me. this is my view: def get_all_subjects(request): all_subjects = Predmeti.objects.all() return render(request, 'home.html', {"Predmeti": all_subjects}) and this is home.html: {% block content %} {% if user.is_authenticated %} Hi {{ user.email }}! <p><a href="{% url 'logout' %}">logout</a></p> <table> {% for predmet in Predmeti %} <tr> <td>{{ predmet.ime }}</td> <td>{{ predmet.kod }}</td> <td>{{ predmet.bodovi }}</td> <td>{{ predmet.izborni }} </td> <td> <form method="POST" action="{% url 'upisni list' id=predmet.id %}"> {% csrf_token %} <button type="submit"> Dodaj</button> </form> </td> </tr> {% endfor %} </table> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> | <a href="{% url 'signup' %}">signup</a> {% endif %} {% endblock %} It just says hi to username. Any help is welcome -
How to create multiple model instances without duplicated writable nested serializer in Django REST Framework?
Please correct my title if it doesn't fit my problem. I have 2 related models: Product and ProductDescription. In 1 submit action user able to insert a new Product with multiple descriptions depend on the available languages. I use writable nested serializer to insert into Product and ProductDescription simultaneously. I do it by overriding create function in ProductDescriptionSerializer class, it works. However, I can only insert 1 ProductDescription at a time. Then I tried to use this answer to create multiple model instances at once. The problem is it also creates the same Product twice instead of using the newly created Product Id to insert the next ProductDescription. My models.py: class Product(models.Model, ProductStatus): product_code = models.CharField(max_length=6) color = models.ForeignKey(ColorParent, on_delete=models.SET_NULL, null=True) collection = models.ForeignKey(ProductCollection, on_delete=models.SET_NULL, null=True) video = models.URLField(verbose_name='Video URL', max_length=250, null=True, blank=True) status = models.CharField(max_length=20, choices=ProductStatus.status, default=ProductStatus.active) class ProductDescription(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.CASCADE) description = models.TextField(max_length=500, null=True, blank=True) def __str__(self): return '%s - %s' % (self.product, self.language) My serializers.py: class CustomRelatedField(serializers.RelatedField): def display_value(self, instance): return instance def to_representation(self, value): return str(value) def to_internal_value(self, data): model = self.queryset.model return model.objects.get(id=data) class ProductSerializer(serializers.ModelSerializer): collection = CustomRelatedField(queryset=ProductCollection.objects.all(), many=False) color = CustomRelatedField(queryset=ColorParent.objects.all(), many=False) class Meta: model = Product fields … -
How to inegrate R project with web apps
Now I have created a model using apriori algorithm and association rules for market basket analysis using R, And my project is a mobile application with flutter and django api’s, So I would like to know how to integrate my R project with this mobile app or how to start searching for a solution I habe tried using rpy2 to code my model with python but I couldn’t install it. Thanks in advance. -
iteration through nested Dictionary and printing in Django html page
I Have a Dictionary like this mainDict={'RA CROXE-16353': {'ENGINEER_NAME': 'Leela', 'DESCRIPTION': 'M5 Rainbow when it is conversation with external', 'BINARIES': 'SYM'}, 'RA CROXE-16344': {'ENGINEER_NAME': 'MARK', 'DESCRIPTION': 'M5 Network SIP ISDN TLS call with VPN_G729', 'BINARIES': 'TEL.1.so'} } I want to iterate through the dictionary so that I can print in the Table Format in Django. CR ENGINEER_NAME DESCRIPTION BINARIES RA CROXE-16353 Leela M5 Rainbow when it is conversation with external SYM RA CROXE-16344 MARK M5 Network SIP ISDN TLS call with VPN_G729 TEL.1.so Please, anyone, let me know how to proceed <table class="table"> <tr> <td>CR</td> <td>Engineer Name</td> <td>Description</td> <td>Binaries</td> </tr> {% for key,value in mainDict.items %} {% for k,val in value.items %} <tr> <td>{{key}}<td> <td> {{ value }} </td> </tr> {% endfor %} {% endfor %} </table> I have tried to loop over the code with keys and values but I am unable to print in the required format. -
How to configure Celery to run as systemd service with a Django application served by Gunicorn?
I followed the official Celery documentation regarding how to configure Celery to work with Django (python 3) and RabbitMQ. I already have a systemd service to start my Django Application using Gunicorn, NGINX is used as a reverse reverse-proxy. Now I need to daemonize Celery itself based on the offical documentation but my current settings doesn't seem to work properly as my application is not recognized, I get error below at Celery systemd service start: # systemctl start celery-my_project # journalctl -xe Error: Unable to load celery application The module celery-my_project.celery was not found Failed to start Celery daemon As a test, I got a rid of all the systemd/Gunicorn/NGINX and basically started my virtualenv/Django application & Celery worker manually: Celery tasks are properly detected by Celery worker: celery -A my_project worker -l debug How to properly configure systemd unit so that I can daemonize Celery? Application service (systemd unit) [Unit] Description=My Django Application After=network.target [Service] User=myuser Group=mygroup WorkingDirectory=/opt/my_project/ ExecStart=opt/my_project/venv/bin/gunicorn --workers 3 --log-level debug --bind unix:/opt/my_project/my_project/my_project.sock my_project.wsgi:application [Install] WantedBy=multi-user.target Celery service (systemd unit) [Unit] Description=Celery daemon After=network.target [Service] Type=forking User=celery Group=mygroup EnvironmentFile=/etc/celery/celery-my_project.conf WorkingDirectory=/opt/my_project ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait … -
Django Class Based Views handle multiple queries
I'm rewriting my django function view to class based views. I have this current function @login_required def settings(request, template_name="settings.html"): context = {} context['kcs'] = KlarnaProfile.objects.filter(user_profile__user=request.user) context['extends'] = ExtendProfile.objects.filter(user_profile__user=request.user) context['fortnoxs'] = FortnoxProfile.objects.filter(user_profile__user=request.user) return render(request, template_name, context) that confirms first if a user is logged in and then get's information linked to that user account here's what I've got as my class based view class SettingsView(TemplateView): template_name = "settings.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) how can I add the three filters that use the logged in user as a filter? -
customized sorting using search term in django
I am searching a term "john" in a list of dict , I have a list of dict like this : "response": [ { "name": "Alex T John" }, { "name": "Ajo John" }, { "name": "John", }] I am using : response_query = sorted(response, key = lambda i: i['name']) response_query return ascending order of result only but I need a result with first name as a priority. Expected result: { "name": "John" }, { "name": "Ajo John" }, { "name": "Alex T John", } -
Django: how to count disqus comment on a particular post in django
i want to count disqus comment on a particular post in django. could anybody help me to get best tutorial link for this? would be much appreciated. -
Raise JSON decode Error Expecting value: line 1 column 1 (char 0)
I am creating a website using Django . Below is my code: views.py: for i in range(0,len(userdata)): json_hall = requests.get( "https://www.onebookingsystem.com/API/Admin/booking_list_id.php?id=%s" % userdata[i]['bookid']) r = json_hall.json() hall_data = json.loads(json_hall.text) id_data[i]['bookid'] = hall_data[0]['bookid'] When i run i am getting the error like this. File "D:\KarthikWorkSpace\Projects\Python\obs_admin\Application\obs_app\views.py", line 1968, in bookings_owner hall_data = json.loads(json_hall.text) raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Any help would be appreciated. -
Django filter queryset on list of "lists"
Excuse the phrasing of the title, perhaps it's not the correct way of saying it but I can't come up with a better one. I have a model called People, and through some means of identifying a bunch of people I want to fetch from the database by knowing their Town, Street, and House, and then query the database for them. class People(models.Model): town = models.ForeignKey(Town, on_delete=models.CASCADE) street = models.ForeignKey(Street, on_delete=models.CASCADE) house = models.ForeignKey(House, on_delete=models.CASCADE) I could fetch them one by one as below using People.objects.get(...), however when I need to access many it puts a lag on due to the opening and closing of db connections. result = People.objects.get(town_id=tid, street_id=sid, house_id=hid) If I had a list of queries as given below, representing tid sid and hid, could I somehow do this all in one single database transaction? This list could easily grow to be 1000 entries or more. queries = [ [1, 1, 1] [1, 1, 2] [2, 1, 1] [5, 9, 1] [13, 40, 2] ] -
ConnectionRefusedError: [WinError 10061][WinError 10061] No connection could be made because the target machine actively refused it
What exactly does this error mean and how can i fix it, am running server on port 8000 of local host. ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it -
How can to test stripe api?
I have following function. It is a request to the stripe api (stripe.PaymentIntent.create, stripe.PaymentIntent.confirm, stripe.error). How can this be tested? def pay_and_update_model(self, stripe_token): quantity = self.quantity netto_price = self.product.amazon_item.original_selling_price brutto_price = self.product.amazon_item.selling_price amount_brutto = quantity * brutto_price amount_netto = quantity * netto_price payment_intent = '' try: if stripe_token.startswith('pm_'): intent = stripe.PaymentIntent.create(amount=int(amount_brutto * 100), currency="usd", description=self.uuid, payment_method=stripe_token ) payment_intent = stripe.PaymentIntent.confirm(intent.id) self.update_donation_after_payment(payment_intent, amount_brutto, amount_netto) elif stripe_token.startswith('pi_'): payment_intent = stripe.PaymentIntent.confirm(stripe_token) self.update_donation_after_payment(payment_intent) except stripe.error.CardError as error: self.custom_error_response(error, amount_brutto, amount_netto) except stripe.error.RateLimitError as error: self.custom_error_response(error, amount_brutto, amount_netto) except stripe.error.InvalidRequestError as error: self.custom_error_response(error, amount_brutto, amount_netto) except stripe.error.AuthenticationError as error: self.custom_error_response(error, amount_brutto, amount_netto) except stripe.error.APIConnectionError as error: self.custom_error_response(error, amount_brutto, amount_netto) except stripe.error.StripeError as error: self.custom_error_response(error, amount_brutto, amount_netto) if payment_intent: return self.generate_response(payment_intent) else: return -
How to make sub menus dynamic in the template?
Here I am creating sub_menu with custom template and displaying it on some particular template and which is working fine.I am providing the same template for each sub menus. When the user selects one of the sub menu from select element and it gives the template which I added.Which is working as I wanted but the issue is in the template now the sub menu disappears. How can i handle it.Any help would be appreciated. template <select class="custom-select" onchange="location = this.value;"> <option selected>Choose</option> {% show_sub_menu 1 None 0 "option_menu.html" %} </select> option_menu.html {% load menu_tags %} {% for child in children %} <option value="{{ child.attr.redirect_url|default:child.get_absolute_url }}"> {{ child.get_menu_title }}</option> {% endfor %} The same template where I have sub menu with this url http://127.0.0.1:8000/about-us/executive-boards The template which I assigned for the sub menu(which is same as the above template) http://127.0.0.1:8000/about-us/executive-boards/executive-boards-2017-2019/ Now here the sub menu disapperas -
Django form validation for dynamic form fields
I have sample form as shown below Date = ( ('Select', 'Select'), ('Between', 'Between'), ('On', 'On'), ('From', 'From')) required = forms.CharField(widget=forms.Select(choices=Date, attrs={"onchange": 'Hide(this.value)', 'style':'width:220px;'})) from_date = forms.DateField( widget=forms.DateInput(attrs={'type': 'date', 'style':'width:110px;'}), required=False, ) to_date = forms.DateField( widget = forms.DateInput(attrs={'type': 'date', 'style':'width:110px;'}), label = 'To Date', required = False, ) on_date = forms.DateField( widget = forms.DateInput(attrs={'type': 'date', 'style':'width:110px;'}), label = 'To Date', required = False, ) If i select 'from' it shows from_date and if select between both from date and to date display and if i select on Only on date is displayed Now If i select from date only from date should be validated and accordingly for other scenarios. How can I achieve this? -
Django Class Based View return view or redirect to another page
I'm rewriting my function to class based views, this is the function I currently have. @login_required def invoice(request, invoice_no, template_name="invoice.html"): context = {} invoice_exists = Invoice.objects.filter(invoice_no=invoice_no) if invoice_exists: context['invoice'] = invoice_exists.first() else: return HttpResponseRedirect(reverse('invoices')) return render(request, template_name, context) you have to be logged in, it filters using a filter named invoice_no path('invoice/<int:invoice_no>', views.InvoiceView.as_view(), name="invoice"), and if a match is found returns it, if not redirects you back to the invoices page. this is what I have as a class class InvoiceView(DetailView): queryset = Invoice.objects.all() context_object_name = 'invoice' pk_url_kwarg = 'invoice_no' template_name = "invoice.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_object(self): obj = super().get_object() return obj also the get object or 404 will do also since all it needs is a 404 page and it'll work. -
Django - Parse URL to get object and save it
let's assume we have a endpoint /user/{user_id}/posts/{post_id}. I would like Django to be able to automatically parse URL and save model object connected to user_id and post_id, which I define. In documentation I have found something like custom hyperlinked fields and method get_url. According to documentation: The get_url method is used to map the object instance to its URL representation. Is there some method that allows exactly opposite: The get_object_from_url method is used to map URL representation to its object instance. -
Django Rest Framework instancing serializers error
Hello I'm new in DRF Classes I'm tryng retrieve data from database to JSON in a API, but the data are in a lot of fields a many tables, linked by foreign keys. I Want pass a id from a data and the API will retrieve all related data with this field. Like a Join in SQL I'm doing it creating a serializers and views from my models. One of my models is: class ModelPer(ModelMMixin, SQLMixin): '''Model ''' descricao = models.CharField( verbose_name = _(u'Descrição'), max_length = 250, unique = False ) ativo = models.BooleanField( verbose_name= _(u'Ativo'), default = False ) slug = models.SlugField( max_length=150, unique=True, default=uuid.uuid4() ) My Serializers is: class PerSerializer(serializers.ModelSerializer): class Meta: model = ModelPer fields = ['id', 'descricao'] My View is: class PerView(APIView): """ View that return all forms in app """ def get(self, request): queryset = ModelPer.objects.all() serializer = PerSerializer(queryset) print(serializer.data) return Response(serializer.data) But i'm receiving a empty Json, so when i try debug in Django shell i received this: >>> from per.models import ModelPer >>> from api_form.serializers import PerSerializer >>> queryset = ModelPer.objects.all() >>> serializer = PerSerializer(queryset) >>> serialzaer.data ERROR The serializer field might be named incorrectly and not match any attribute or key on … -
Return dynamic relation based on date
I have two models, course and courseDate, for my courses i want to dynamically return a related object based on the next availabe date: next_course_date. This should return the next courseDate instance for each course. Do i have to create a relationfield for that and alter the value with a method? class Course(models.Model): class Meta: verbose_name = "Kurs" verbose_name_plural = "Kurse" uuid = models.UUIDField(default=uuid.uuid4, editable=False) owner = models.ForeignKey(Company, related_name='courses', on_delete=models.DO_NOTHING) name = models.CharField(max_length=60) categories = models.ManyToManyField(Category, related_name='courses') next_course_date = models.IntegerField(default=0) access_level = models.IntegerField(default=1) status = models.IntegerField(default=1) published = models.BooleanField(default=False) banner = models.URLField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CourseDate(models.Model): class Meta: verbose_name = "Kurstermin" verbose_name_plural = "Kursetermine" uuid = models.UUIDField(default=uuid.uuid4, editable=False) owner = models.ForeignKey(Company, related_name='course_dates', on_delete=models.DO_NOTHING) course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, related_name='course_dates') lecturers = models.ManyToManyField(User, related_name='main_lecturers') begin = models.DateTimeField()#not editable end = models.DateTimeField()#not editable date_details = models.DateTimeField(auto_now=True, auto_now_add=False) access_level = models.IntegerField(default=1) status = models.IntegerField(default=1) published = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)