Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models making with with multiple condition
I am developing a app for cinema show seat booking and going through a trouble to design my models this is my current models: from django.db import models from django.contrib.auth import get_user_model class Seats(models.Model): seat_choice = ( ('AA', 'AA'), ('AB', 'AB'), ('BA', 'BA'), ('BB', 'BB'), ('CA', 'CA'), ('CB', 'CB') ) name = models.CharField(choices=seat_choice, max_length=2) def __str__(self): return self.name class Show(models.Model): show_choice = ( ('MORNING', 'MORNING'), ('NIGHT', 'NIGHT'), ) show_schedule = models.CharField(choices=show_choice, max_length=10) movie = models.CharField(max_length=50) def __str__(self): return self.show_schedule class Booking(models.Model): seat = models.OneToOneField(Seats, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) show = models.ForeignKey(Show, on_delete=models.CASCADE) I am trying to achieve like If a seat booked of a show, it can't be booked again later but it can be booked by later for another show. But my current models problem is: If i book a seat for a show, i cant book the same seat for another show (which is i dont want) My Requirement is simpe: If i book a seat for a show, later i should able to book the same seat for another different show but it cant be booked again for the same show... I know i can achieve it removing the show and using created like below: class … -
Using custom mixins in serializers
I am kind of new to Django and currently I am working on an endpoint which aggregates data. I have the mixin which returns user ID, timestamp and token: import cent class CentMixin(object): def get_cent_data(self, user_id=''): cent_timestamp = calendar.timegm(datetime.now().timetuple()) token = cent.generate_token(settings.CENTRIFUGE_SECRET, str(user_id), str(int(cent_timestamp))) return user_id, cent_timestamp, token I have written a serializer: class CentEndpointSerializer(serializers.Serializer): cent_user_id = serializers.IntegerField() cent_timestamp = serializers.DateTimeField() cent_token = serializers.CharField() And now I am wondering how to write a View for the serializer. Any suggestions? -
How to get weekly data from database
Now I'm making django crm app and i have a question. My question may be related to datetime() class. I'm gonna to show all data according to the date. For example,when a user logged in the site,I want to show all leads (which saved in database) separately according to the date,weekly,monthly,yearly. So my question is how can i select the week,month or year which today in. -
How to define which input fields the form has by pressing different buttons?
I have a form and a few buttons as below: <form method="GET" novalidate id="my_form"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> </form> <input name="page" type="hidden" form="my_form" value="1" id="submit"> <button type="submit" class="btn btn-success" form="my_form">Submit</button> <input name="page" type="hidden" form="my_form" value="1" id="1"> <button form="my_form" role="button" class="btn btn-link">1</button> <input name="page" type="hidden" form="my_form" value="2" id="2"> <button form="my_form" role="button" class="btn btn-link">2</button> <input name="page" type="hidden" form="my_form" value="3" id="3"> <button form="my_form" role="button" class="btn btn-link">3</button> As you see, I have four submit buttons. What I need is that if I pressed the submit button, the form that contains the first name and last name and the input field that adds page=1 to the GET be submitted. If I pressed, as an example, the button 3 (the last one), the form and only the input that has page=3 be submitted not the other inputs with page=1, page=2, page=3 . I am using this to solve a pagination problem. How can I do this? I prefer not using JavaScript, or if I have to, only a very simple script be used in the solution. -
Scrolling index.html to #contact after form submission (django)
index.html <section id="contact"> <form id="contactForm" method="get" action="{% url 'contact-form' %}"> ... <button class="btn btn-common" id="submit" type="submit">Submit</button> </form> </section> where {% url 'contact-form' %} expands to contact-form/ After submitting this form, I want the page to scroll to #contact where the form is located(if there are form validation errors). I've tried $("#contactForm").submit( function() { $('html, body').animate({ scrollTop: $("#contact").offset().top }, 2000); return false; }); But the scroll doesn't work. -
Docker-compose cannot start my Django app
I am new from Docker and i would to run my Django app on it, so i do this: -My Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ My docker-compose.yml version: '3' networks: mynetwork: driver: bridge services: db: image: postgres ports: - "5432:5432" networks: - mynetwork environment: POSTGRES_USER: xxxxx POSTGRES_PASSWORD: xxxxx web: build: . networks: - mynetwork links: - db environment: SEQ_DB: cath_local SEQ_USER: xxxxx SEQ_PW: xxxxx PORT: 5432 DATABASE_URL: postgres://xxxxx:xxxxx@db:5432/cath_local command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db well on my docker shell i point to Dockerfile directory, if i run an ls command from y path i see the manage.py file, but if i run: docker-compose up i get this error: web_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory core_web_1 exited with code 2 Why my app don't find manage.py file that is in the same position as the "docker-compose up" command is? PS: No /code folder is created when i run docker-compose command. Is it correct? So many thanks in advance -
How to register Django 2.x
How to register, log in and log out on Django 2.x.In my country, little information on this topic, dogs don't read, because I already tried to do something on them and spent a lot of time .Sorry for bad english -
Django ORM: How can I sort by date and then select the best of the objects within a foreign key?
I realize my title is kind of complex, but please allow me to demonstrate. I'm on Django 2.2.5 with Python 3. Here are the models I'm currently working with: from django.db import models from django.db.models import F from django.contrib.postgres.indexes import GinIndex from django.contrib.postgres.search import SearchVectorField, SearchVector, SearchQuery, SearchRank class Thread(models.Model): title = models.CharField(max_length=100) last_update = models.DateTimeField(auto_now=True) class PostQuerySet(models.QuerySet): _search_vector = SearchVector('thread__type') + \ SearchVector('thread__title') + \ SearchVector('from_name') + \ SearchVector('from_email') + \ SearchVector('message') ### # There's code here that updates the `Post.search_vector` field for each `Post` object # using `PostQuerySet._search_vector`. ### def search(self, text): """ Search posts using the indexed `search_vector` field. I can, for example, call `Post.objects.search('influenza h1n1')`. """ search_query = SearchQuery(text) search_rank = SearchRank(F('search_vector'), search_query) return self.annotate(rank=search_rank).filter(search_vector=search_query).order_by('-rank') class Post(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) timestamp = models.DateTimeField() from_name = models.CharField(max_length=100) from_email = models.EmailField() message = models.TextField() in_response_to = models.ManyToManyField('self', symmetrical=False, blank=True) search_vector = SearchVectorField(null=True) objects = PostQuerySet().as_manager() class Meta: ordering = ['timestamp'] indexes = [ GinIndex(fields=['search_vector']) ] (There's some stuff in these models I've cut for brevity and what I believe is irrelevance, but if it becomes important later on, I'll add it in.) In English, I'm working with an app that represents the data in an email listserv. … -
Django Rest Framework: Serialize multiple images to one post in
I am trying to be able to serialize and upload multiple images to associate with each post. This is my models.py from django.conf import settings from django.db import models from django.db.models.signals import pre_save from .utils import unique_slug_generator class Painting(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default="", on_delete=models.CASCADE) title = models.CharField(blank=False, null=False, default="", max_length=255) slug = models.SlugField(blank=True, null=True) style = models.CharField(blank=True, null=True, default="", max_length=255) #need to figure out why there is problem when this is False description = models.TextField(blank=True, null=True, default="") size = models.CharField(blank=True, null=True, default="", max_length=255) artist = models.CharField(blank=True, null=True, default="", max_length=255) price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=20) available = models.BooleanField(default=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ["-timestamp", "-updated"] class PaintingPhotos(models.Model): title = models.ForeignKey(Painting, default="", on_delete=models.CASCADE) image = models.ImageField(upload_to='uploaded_paintings') def pre_save_painting_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(pre_save_painting_receiver, sender=Painting) my serializers.py from django.contrib.auth import get_user_model, authenticate, login, logout from django.db.models import Q from django.urls import reverse from django.utils import timezone from rest_framework import serializers from .models import Painting, PaintingPhotos User = get_user_model() class UserPublicSerializer(serializers.ModelSerializer): username = serializers.CharField(required=False, allow_blank=True, read_only=True) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', ] # # add PaintingImagesSerializer with the images model here … -
From where this models.Model coming from in django?
As I was creating Django project want to create Models for storing in database later. But in the video the person types : from django.db import models class Post(models.Model): title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User) Okay, I understand that we are inheriting models class so we can use its properties like CharField, TextField but why we are writing models.Model while inheriting. Can't we just write models? Why he is importing the class method -> Model? Am I missing something in OOPS? -
Error deploying app on google app engine - can't find information on error
I have a Django app which works just fine on my local server. I am now trying to deploy it on GAE, and I'm getting this error ERROR: (gcloud.app.deploy) Your application does not satisfy all of the requirements for a runtime of type [python3]. Please correct the errors and try again. Unfortunately I can't find much information on what the error message is referring to, or whether there is a log that I can look at? Any help would be MUCH appreciated! -
How to include validate_email package into django UserCreationForm?
I downloaded a email validator package from PyPI, link is: https://pypi.org/project/validate_email/ and using pip install validate email and pip install py3dns (since my python is version 3.6.7) into my django project. The problem is I cant seem to get the validate_email function to work on my django project, just wondering what code should I be writing on my django's forms.py and views.py. (not using models.py yet). Please tell me what did I do wrong and what changes should be made to my current code in forms.py. I included "from django.core.validators import validate_email" as seen in forms.py below to try to validate the email entered by any user but it seems that the validate_email works differently from the validate_email from "from validate_email import validate_email". The validation that I need is from PyPI as it is more accurate in validation (e.g. can check if an email is existent or not) whereas the validate_email form django.validators only checks for invalid format and thats it. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import validate_email from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', … -
App Crashed on my Django app using Heroku
These are all of the error messages: 2019-09-17T01:27:59.832820+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=ab1e197e-ab72-4d03-bec2-8ba06c3db870 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:28:00.339514+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=cad19ccd-31d0-46d1-a31a-891068cc7c87 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:44.241612+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=43785608-8070-4b01-8543-fb7bc84c985e fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:44.744082+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=70e0e3a6-fe27-41fb-924d-c99960303953 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:46.607921+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fast-bayou-25474.herokuapp.com request_id=52842cc3-1869-411a-936c-92b3cae86329 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https 2019-09-17T01:30:47.003348+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fast-bayou-25474.herokuapp.com request_id=1253c722-5c0e-42f3-8679-f51dad8622e9 fwd="146.115.146.105" dyno= connect= service= status=503 bytes= protocol=https Could Somebody please help me? -
In my django app, how to show all posts of similar category if that category is selected?
I'm new to Django so bear with me please. I'm creating an app for posting jobs, and it's based on Corey Schafer's social media tutorial. Each post/job in my app has a category field (NGO, Engineering, Oil&Gas, etc...) My goal is if I select a category, then all jobs of the same category are listed. Corey did the same with the "all posts of a selected author " approach, but I couldn't do similar thing with my category goal. I appreciate all help for guidance. If the pics aren't enough, a general guidance is fine, thanks! urls.py views.py model.py -
Rewriting a Django application from ground-up, is it possible to migrate user model?
I have a web app that I developed while learning back-end web development. I deployed it a while back and ended up getting some real users registered. Unfortunately, I wrote some smelly code and it is becoming very difficult to implement any new features without having to refactor large portions of the code base, so I am planning to rewrite the back-end. The main issue I'm facing is whether there is a way to migrate the CustomUser model I've created to a new PostgreSQL database. Is this possible by simply recreating the same model in the new backend, then doing a pg_dump and restore? -
How to use ajax to link views to form? Django
views.py def contact_form(request): if request.is_ajax(): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("django.contrib.staticfiles.urls")), path("single-post/", single_post, name="single-post"), path("contact-form/", contact_form, name="contact-form"), path("", index), ] index.html <form id="contactForm" method="get" action="{% url 'contact-form' %}"> <input type="text" class="form-control" id="name" name="name" placeholder="Name"> <input type="text" placeholder="Subject" id="msg_subject" class="form-control" name="subject"> <input type="text" class="form-control" id="email" name="email" placeholder="Email"> ... <button class="btn btn-common" id="submit" type="submit">Submit</button> </form> When I submit my form I get: The view app.views.contact_form didn't return an HttpResponse object. It returned None instead. How do I use ajax to link the form to contact_form? -
Improve performance of the an Django MPTT tree
I have implemented the follow model to capture the structure of a classical piece of music. I'm using the MPTT to implement movements, opera acts and arias. model.py: TreeForeignKey(Work, blank=True, null=True, db_index=True, on_delete=models.PROTECT).contribute_to_class(Work, 'parent') mptt.register(Work, order_insertion_by=['id']) class Work(models.Model): attributed_to = models.NullBooleanField() name = models.CharField(max_length=400, null=True, blank=True) lang = models.CharField(max_length=2, null=True, blank=True) name_original = models.CharField(max_length=200, null=True, blank=True) lang_original = models.CharField(max_length=2, null=True, blank=True) name_common = models.CharField(max_length=200, null=True, blank=True) name_common_orig = models.CharField(max_length=200, null=True, blank=True) dedicated_to = models.CharField(max_length=200, null=True, blank=True) pic = models.ImageField(upload_to = 'pic_folder/', default = '/pic_folder/None/no-img.jpg') piece_type = models.CharField(max_length=100, null=True, blank=True) category = models.CharField(max_length=100, null=True, blank=True) date_start = models.CharField(max_length=100, null=True, blank=True) date_start_gran = models.CharField(max_length=5, choices=DATE_TYPES, default='Year') date_signature = models.CharField(max_length=100, null=True, blank=True) date_signature_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year') around = models.BooleanField(null=True) date_published = models.CharField(max_length=100, null=True, blank=True) date_published_gran = models.CharField(max_length=10, choices=DATE_TYPES, default='Year') desc = models.TextField(max_length=8000, null=True, blank=True) order = models.CharField(max_length=100, null=True, blank=True) class Work_Music(Work): composer = models.ForeignKey(Composer, verbose_name=_('composer'), null=True, blank=True, on_delete=models.PROTECT) key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) Here is the view.py: class ComposerOverviewView(TemplateView): template_name = 'composers/overview/catalogue.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) opus = Work_Music.objects.filter(composer=self.kwargs['pk'], level=0) context.update({ 'composer': Composer.objects.get(pk=self.kwargs['pk']), 'opus': opus, }) return context When I try to run a query for all of the works for a composer (in the … -
Deploy django with apache and mod_wsgi get internal server error
I try to deploy django on a debian 10 server with apache2 and mod_wsgi. I follow and combine several guides. Now i have installed the following packages: apache2, libapache2-mod-wsgi-py3, apache2-dev an in python3: django, mod-wsgi My apache config file in /etc/apache2/sites-available looks like: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ServerName 127.0.0.1 ServerAlias localhost Alias /static /home/djangouser/django-project/static WSGIScriptAlias / /home/djangouser/django-project/django-project/wsgi.py <Directory /home/djangouser/django-project/static> Require all granted </Directory> <Directory /home/djangouser/django-project/django-project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/djangouser/django-project/> Order allow,deny Allow from all </Directory> DocumentRoot /home/djangouser/django-project/ </VirtualHost> I use ufw. Now if i go to the website in a browser i get an Internal Server Error. I think my config do this because before i edit the 000-default.conf apache shows the default page. But what is wrong with my config? -
django how to sum item * quantity for each items in cart
How to sum each items in cart * quantity, example first item 10 *- quantity = total, The second one item x * quantity = total, this suma give me the total all items in cart not for each items. def add_produktshitje(request, shitje_id): shitje = get_object_or_404(Shitje, id=shitje_id) suma= Produ.objects.filter(shitje_id=shitje.pk).aggregate(totals=Sum(F('sasia')*F('cmimi'), output_field=FloatField())) return render(request, 'polls/add_produktshitje.html', {'shitje':shitje,'suma':suma}) -
Can I remove verbose name from a django-generated migration?
Simple question. Can I remove verbose name from the 'id' field in this migration below. This migration was generated by manage.py makemigrations # Generated by Django 2.1.5 on 2019-09-16 15:53 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('uatu', '0035_auto_20190703_0849'), ] operations = [ migrations.CreateModel( name='StageExecutionParent', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=150)), model changes here: class StageExecutionParentManager(models.Manager): def get_or_create(self, **kwargs): return self.get_queryset().get_or_create(**kwargs) class StageExecutionParent(JsonableModel): name = models.CharField(max_length=150) manager = StageExecutionParentManager() def reprJSON(self): try: return dict( name=self.name, ) except: return dict() I try to stay away from altering any django created migration, but was instructed to remove the use of verbose name, so just want to make sure before I introduce a corrupted migration. -
django wkhtmltopdf rendered table and common header overlap
Creating pdf by wkhtmltopdf long table overlap with common header. Table rendered successfully and if I remove header it shows data. page break always is not fixing the issue. -
Is it possible to get access to PC system via web app using modules like pyautogui and win32gui/pywin32?
As a training project i have made activity tracker using python (no GUI, only command-line). Script checks with win32gui/pywin32 and pyautogui what program is currently used, and if it is web browser what web site is in use. Name of window, date, and amount of time spent on program/website is stored in sqlite3 database.Then with help of pandas module same names are grouped and time is summed up. I want to convert this script into web app using django but i am beginner in creating web apps, so i am wondering : is it possible to use this modules within django and is it even possible to create web app that works same as script mentioned earlier? Sorry if the question is trivial. I will be grateful for every tip where and what exactly to look for in this topic. -
syntax error trying to run django app with django channels
I am following tutorial at https://realpython.com/getting-started-with-django-channels/ to use django channels. It is using django==1.10.5 channels==1.0.2 asgi_redis==1.0.0 There are few parts main_app/routing.py: from channels.routing import route from example.consumers import ws_connect, ws_disconnect channel_routing = [ route('websocket.connect', ws_connect), route('websocket.disconnect', ws_disconnect), ] example/views.py: def user_list(request): return render(request, 'example/user_list.html') example/consumers.py: from channels import Group def ws_connect(message): Group('users').add(message.reply_channel) def ws_disconnect(message): Group('users').discard(message.reply_channel) The app is very small, but when I try to runserver I get the following error: Unhandled exception in thread started by <function wrapper at 0x0000000004566518> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.ready() File "C:\Python27\lib\site-packages\channels\apps.py", line 22, in ready monkeypatch_django() File "C:\Python27\lib\site-packages\channels\hacks.py", line 10, in monkeypatch_django from .management.commands.runserver import Command as RunserverCommand File "C:\Python27\lib\site-packages\channels\management\commands\runserver.py", line 5, in <module> from daphne.server import Server, build_endpoint_description_strings File "C:\Python27\lib\site-packages\daphne\server.py", line 213 async def handle_reply(self, protocol, message): When I hit the main page, localhost:8000, it says "connection refused". How can I remove this error and get the app running? Thank you -
Django scheduler with aws-lambda
I have Django Postgres Database with DateField which is date of sending some message (SMS and email). I would like to schedule delivering somehow (so basically run function with parameters at this date). Everything is running on aws-lambda. I read Django - Set Up A Scheduled Job? but I wondering if there isn't some strictly aws solution (I'm not so familiar with AWS). Thanks! -
Error in Django while accessing external python script
I am writing a button click HTML code with multiple of them calling external python script and if my external python script is not using any call or open functions it is working fine. If my external python script has open ("another python script") then in django it is showing the file error as i didn't mention the path for the call.py script file in views.py file