Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Supervisor error - gunicorn: ERROR (spawn error)
I am getting the error gunicorn: ERROR (spawn error) when trying to deploy django application with gunicorn wsgi in the supervisor. My supervisor.conf GNU nano 4.8 supervisord.conf [unix_http_server] file=/tmp/supervisor.sock ; the path to the socket file [supervisord] logfile=server/supervisor/logs/supervisord.log ; main log file; default $CWD/supervisord.log logfile_maxbytes=5MB ; max main logfile bytes b4 rotation; default 50MB logfile_backups=10 ; # of main logfile backups; 0 means none, default 10 loglevel=info ; log level; default info; others: debug,warn,trace pidfile=/tmp/supervisord.pid ; supervisord pidfile; default supervisord.pid nodaemon=false ; start in foreground if true; default false minfds=1024 ; min. avail startup file descriptors; default 1024 minprocs=200 ; min. avail process descriptors;default 200 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket [program:gunicorn] command=/home/ubuntu/strategy_app/venv/bin/gunicorn strategy_server.wsgi:application -c /home/ubuntu/strategy_app/server/gunicorn/gunicorn.conf.py --chdir /home/ubuntu/strategy_app when I run the same above command outside of supervisor, it works /home/ubuntu/strategy_app/venv/bin/gunicorn strategy_server.wsgi:application -c /home/ubuntu/strategy_app/server/gunicorn/gunicorn.conf.py --chdir /home/ubuntu/strategy_app I also tried other options available in the official docs -
InterfaceError: Error binding parameter 3 - probably unsupported type
I have an error here with my Django backend: Environment: Request Method: POST Request URL: http://localhost:8000/MultipleChoiceQuestion/ Django Version: 2.2.11 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'db.apps.DbConfig', 'rest_framework', 'corsheaders', 'django_filters'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) The above exception (unrecognized token: ":") was the direct cause of the following exception: File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in execute 99. return super().execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in execute 67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers 76. return executor(sql, params, many, context) File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\utils.py" in __exit__ 89. raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Python37\lib\site-packages\django\db\backends\utils.py" in _execute 84. return self.cursor.execute(sql, params) File "C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 383. return Database.Cursor.execute(self, query, params) During handling of the above exception (unrecognized token: ":"), another exception occurred: File "C:\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python37\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\viewsets.py" in view 114. return self.dispatch(request, *args, **kwargs) File "C:\Python37\lib\site-packages\rest_framework\views.py" in dispatch 505. … -
Django: how do use * for Decimal and float?
I have below models, and it shown error: "unsupported operand type(s) for *: 'float' and 'Decimal'" for "self.item.price * 1.034". what should I do for fixed it?? models.py class Product(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10, blank=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def get_total_price_credit(self): return round(self.quantity * self.item.price * 1.034) def get_final_price_credit(self): return self.get_total_price_credit() class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) def get_total_credit(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price_credit() return total -
Getting error in django rest framework testing
Trying to test update in django rest framework but, it returns following error. How do test to edit update of gallery. self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 400 != 200 my models.py class GalleryImage(models.Model): image = models.ImageField(upload_to='gallery/') alt_text = models.CharField(max_length=300) created = models.DateTimeField(auto_now_add=True) class Gallery(models.Model): name = models.CharField(max_length=30) slug = AutoSlugField(populate_from='name', unique_with='id') images = models.ManyToManyField(GalleryImage) created = models.DateTimeField(auto_now_add=True) my factories.py class GalleryImageFactory(DjangoModelFactory): class Meta: model = GalleryImage image = factory.django.ImageField(color='blue') alt_text = 'alt_text' class GalleryFactory(DjangoModelFactory): class Meta: model = Gallery name = 'Image Gallery 1' @factory.post_generation def images(self, create, extracted, **kwargs): if not create: return if extracted: for image in extracted: self.images.add(image) my tests.py class UpdateDeleteGalleryTestCase(APITestCase): def setUp(self): image1 = GalleryImageFactory() image2 = GalleryImageFactory() self.gallery = GalleryFactory(images=(image1, image2)) def test_update(self): data = { 'name': 'edited gallery', 'images': [1] } url = reverse('delete:retrieve_update_delete_gallery', kwargs={'slug': self.gallery.slug}) response = self.client.put(url,data=data,format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) -
Django - Changing queryset order_by
Using Djanog I'm trying to implement some sorting in my table trigger by button but I have no clue how to deal with it as my query set is both filtered and paginated. Could you please give me a hint how to implement this? Should it be done in frontend, i.e. JavaScript or maybe handled by backend, changing qs.order_by('param') ? I would also appreciate any examples as I'm quite new to Django. Here's my code: --index.html <body> <main role="main" class="container"> <form method = "GET" action = "."> <div class="form-row"> <div class="form-group col-8"> <label for="filter_by_name">Search by name</label> <div class="input-group"> <input class="form-control py2 border-right-0 border" type="search" name="filter_by_name" placeholder="Name contains.."/> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> <div class="form-group col-md-4"> <label for="filter_by_shop">Search by shop</label> <select id="filter_by_shop" class="form-control" name="filter_by_shop"> <option selected>All shops</option> <option>first shop</option> <option>second shop</option> </select> </div> </div> <button type="submit" class="btn btn-primary">Search</button> </form> <table> {% for x in queryset %} <tr> <td>{{x.NAME}}</td> <td>{{x.PRICE}}</td> <td>{{x.SHOP}}</td> </tr> {% endfor %} </table> </main> </body> def MyView(request): qs = prices.objects.all().order_by('PRICE') filter_by_name = request.GET.get('filter_by_name') filter_by_shop = request.GET.get('filter_by_shop') if filter_by_name != '' and filter_by_name is not None: qs = qs.filter(NAME__icontains=filter_by_name) if filter_by_shop != '' and filter_by_shop is not None: qs = qs.filter(SHOP__icontains = filter_by_shop) … -
Django CSS not working when using block content
I'm trying to make a simple ordered list. Basically, I have a template that is a navigation bar that is at the top of every page in my web page. This is how the html/css looks on it. {% block content %} <style> * { margin: 0; padding: 0; box-sizing: border-box; } html { font-size: 10px; font-family: sans-serif; } a { text-decoration: none; color: #ea0a8e; font-size: 18px; } header { width: 100%; height: auto; background: #121212; background-size: cover; position: relative; overflow: hidden; } .container { max-width: 120rem; width: 90%; margin: 0 auto; } .menu-toggle { position: fixed; top: 2.5rem; right: 2.5rem; color: #eeeeee; font-size: 3rem; cursor: pointer; z-index: 1000; display: none; } nav { padding-top: 5rem; display: flex; justify-content: space-between; align-items: center; text-transform: uppercase; font-size: 1.6rem; } .logo { font-size: 3rem; font-weight: 300; transform: translateX(-100rem); animation: slideIn .5s forwards; color: #ea0a8e; } .logo span { color: white; } nav ul { display: flex; } nav ul li { list-style: none; transform: translateX(100rem); animation: slideIn .5s forwards; } nav ul li:nth-child(1) { animation-delay: 0s; } nav ul li:nth-child(2) { animation-delay: .5s; } nav ul li:nth-child(3) { animation-delay: 1s; } nav ul li:nth-child(4) { animation-delay: 1.5s; } nav ul li:nth-child(5) { animation-delay: … -
Filter and count QuerySet items with a variable
I am new to Django and am working on a very basic social media site as a practice project. Right now, I am trying to figure out how to filter a QuerySet based on a variable and counting how many items in the QuerySet match the filter. To demonstrate what I am trying to do, let's say I am looping through all the visible posts (like a Facebook post or something similar), and I am wanting to display the number of comments each post has. This is how I would go about that: {% post in all_posts %} <h1> There are currently {{ HOW DO I FILTER AND COUNT? }} comments on this post</h1> {% endfor %} This is what the relevant section of my views.py file looks like: def index(request): all_posts = Posts.objects.order_by('-date_published') all_comments = Comments.objects.order_by('-date_published') context = {'all_posts': all_posts, 'all_comments': all_comments } return render(request, 'social/index.html', context) The comments link to the posts through the post ID. So, I know this doesn't work, but ideally I would like to replace my HOW DO I FILTER AND COUNT? part of the template with something like: {{ all_comments.filter(postID=post.id).count }} Is there an easy way to do this in my views.py or … -
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label
I had an issue with getting some UTC as local time values from a database in my django app as I was doing it be 'hand' in my script, someone in that issue (located here) suggested I try running the script with django (reworking to use the django ORM) decent idea but then get this error which is coming from my models file here: from __future__ import unicode_literals from django.db import models from django.db.models import Q from django.contrib.auth.models import User # Create your models here. class OnSiteLog(models.Model): objects = models.Manager() user = models.ForeignKey(User, on_delete=models.CASCADE) ... So the full error I get is: Traceback (most recent call last): File "report_mailer_django.py", line 13, in <module> from covidlog.models import OnSiteLog File "/mnt/h/programming/web/covid19/covidlog/models.py", line 7, in <module> from django.contrib.auth.models import User File "/usr/local/lib/python3.6/dist-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.contenttypes.models import ContentType File "/usr/local/lib/python3.6/dist-packages/django/contrib/contenttypes/models.py", line 133, in <module> class ContentType(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 111, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I am not sure what is causing this, the file I am trying to fun should be loading django stuff just fine: import django import os from django.conf import … -
Look up nearest coordinates in database / GeoJson
I am working with a GeoJson file with thousands of rows of data, and given a coordinate pair (obtained through MapBox GL JS reverse geocoding) want to find the closest matching result in the dataset. My current approach is to convert the GeoJson into a Postgres DB to be modeled via Django/Python. The GeoJson contains linestring data therefore I loop through each linestring array and save the individual coordinate pairs as a new DB record along with the the linestring array itself. To query the DB I run the following SQL select query: SELECT id, linestring FROM GeoJsonDB ORDER BY ABS(geocoding_latitude-latitude) + ABS(geocoding_longitude-longitude) ASC LIMIT 1 where: geocoding_latitude and geocoding_longitude are generated by Mapbox latitude and longitude are the columns containing the requisite data in my DB id is the DB primary key linestring is an array of arrays containing the linestring coordinates to be drawn as a layer on the map This works but where the ‘nearest’ result is not really that near I will still pull a result which is not helpful (if too far away). So my questions are: (1) Is there a better way/more accurate way to work with the GeoJson data to accomplish this task … -
Is there a way to get a set of m2m from a queryset in Django
I am trying to find a way to get a set of m2m objects from a queryset. A simplified use case would be: I have an Event class with a M2M attendees(user) field. I have a user who is attending Event 1,4,6 I want to find all other users that are attending Events 1,4,6 It is simple enough to do, but it just seems like something that Django would be able to do out the box. -
How to Run a function (view) with a "request" argument from another function (view)?
How run this function (view) in views.py from other function(view)? I want follow to DRY conception. def add_many_rows(request): if request.method == 'POST': data = json.loads(request.body) for row in data: something = Something(name=row['name']) something.save() return HttpResponse("OK") My problem is argument (request). What should I pass in the argument to call this function FROM ANOTHER FUNCTION (instead of calling from the HTML page). I would like something like that: def other_view_function(request): ... add_many_rows(magic_argument_for_my_dumb_tasks) ... return redirect('row_list') -
How do I filter a Django Queryset by removing results in which another model has a ForeignKey relationship?
With the following models.py ... from django.db import models class Notebook(models.Model): name = models.CharField(max_length=255) class Entry(models.Model): notebook = models.ForeignKey(Notebook, on_delete=models.CASCADE) name = models.CharField(max_length=255) How would I write a filter to only return Notebook that have no Entry? -
Django 'AnonymousUser' object has no attribute '_meta' login function doesn't work properly
{% extends 'toDo/base.html' %} {% block content %} <h1>Log In</h1> <h4>{{error}}</h4> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Log In</button> </form> {% endblock %} Thats template def log_in_user(request): if request.method == 'GET': return render(request, 'toDo/logInUser.html', {'form': AuthenticationForm()}) else: user = authenticate(request, username=request.POST['username'], password=request.POST['password']) if user is None: return render(request, 'toDo/logInUser.html', {'form': AuthenticationForm(), "error": "Incorrect username or password. Try again."}) else: login(request, user) return redirect('currentTodos') That's my function that should login user and redirect him to succes page. However it only works for superuser. If i try to login as user with no staff premissions i get and error message i created return render(request, 'toDo/logInUser.html', {'form': AuthenticationForm(), "error": "Incorrect username or password. Try again."}) I've already tried writing it like this but it doesn't change anything: from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: # A backend authenticated the credentials else: # No backend authenticated the credentials I also tried adding backed=... to login function. Nothing works Please help. -
Avoiding the "Two event loops are trying to receive() on one channel layer at once!" error with Django Channels
In short: I am trying to make Django-channels consumers communicate with a separate logic thread. Regardless of what I ask below, there might be a better-suited option I need to consider besides Django-Channels. My goals are: I want to start logic thread programmatically, this is why Django-Channels worker threads do not really work for me. I want the logic thread to be able to send data to consumers I want consumers to be able to send data to the logic thread I do not want to handle game logic in a (for example) "host" consumer, as the game will crash if the host has to reconnect their websocket Longer version: Let's say I am trying to make a simple game on a website, which uses websockets to communicate between the front- and backend. using Django Channels, this could be very easily set up. However, when I need to handle game logic, I want to compute it in some central thread that does not cease whenever a client disconnects. I have found that you can communicate with consumers from some arbitrary thread from outside the consumer scope here. However, this has an issue: The game logic can send information to clients … -
Dockerfile for golang and python
There is a django project already running. Now Inside the code, I need to execute the following command in the subprocess module: cmd = f's5cmd cp {obj1} {obj2}' Now locally this code is running fine. But after deploying the code it is unable to find s5cmd. According to s5cmd documentation it is written in golang and on my system it is installed that's why it is working fine. So i updated the dockerfile but still its not working. FROM python:3.6 COPY ./requirements.txt /tmp/requirements.txt RUN pip install --no-cache-dir -r /tmp/requirements.txt COPY . /apps/project/ WORKDIR /apps/project/project/ EXPOSE 8000 CMD gunicorn project.wsgi:application --timeout 3000 --access-logfile '-' -w 3 -k gevent --bind=0.0.0.0:8000 This dockerfile is working. Now the updated dockerfile looks like this but its not working i.e the s5cmd command is not working with docker. FROM python:3.6.7-alpine3.6 # author of file LABEL maintainer="Baktawar" # Install native libraries, required for numpy RUN apk --no-cache add musl-dev linux-headers g++ RUN apk add --no-cache --virtual .build-deps bash gcc musl-dev openssl go RUN apk update && apk add ca-certificates wget && update-ca-certificates RUN wget -O go.tgz https://golang.org/dl/go1.15.2.src.tar.gz RUN tar -C /usr/local -xzf go.tgz RUN cd /usr/local/go/src/ RUN ./make.bash RUN export PATH="/usr/local/go/bin:$PATH" RUN export GOPATH=/opt/go/ RUN export PATH=$PATH:$GOPATH/bin … -
form.ValidationError is not showing in template
I'm new to Django so excuse some errors. I'm trying to create validation system for email and print those errors, if any, to the template. Just to make clear, I'm able to create new user and redirect to login page, I just can't display error messages. I do apologize if this is trivial question, but I'm kinda stuck on this for 2 days. I have tried this video on youtube: and i have tried to follow this post and it didn't work. forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms # This class will overwrite origginal UserCreationForm0 class CreateUserForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User # this will add email to our register_form fields = [ 'username', 'email', 'password1', 'password2' ] def clean(self): cleaned_data = super(CreateUserForm, self).clean() email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('User with same email already exists') return cleaned_data views.py from django.shortcuts import render, redirect from .forms import CreateUserForm from django.contrib.auth import login, authenticate, logout from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages # Create your views here. def registration_page(request): if request.user.is_authenticated: return redirect('') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) … -
Django {% url %} inside React component
I am trying to use the Django {% URL %} tag inside a React component. For some reason, URLs without arguments work just fine. However, as soon as I try to pass an argument to the tag the following error appears: Reverse for 'expression' with arguments '('',)' not found. 1 pattern(s) tried: ['en/define/(?P[-a-zA-Z0-9_]+)$'] Here is my React code: class Definition extends React.Component { render() { const definition = this.props.definition; const expression = definition.expression; return ( <a href="{% url 'dictionary:expression' expression.slug %}"> {expression.expression}: {definition.definition} </a> ); } } Here is the URL_patterns for my app called "dictionary": path("define/<slug:slug>", dictionary_views.ExpressionView.as_view(), name="expression") Why doesn't React accept {% url 'dictionary:expression' expression.slug %}? -
I have a foreign key relationship between two ModelChoiceField
I have a foreign key relationship between two ModelChoiceField. How do I make sure that when the user selects an option, the associated options are listed in the other ModelChoiceField. -
django : how can I create the admin?
I am trying to follow django's tutorial on how to create a poll but I cannot create a super user such as python manage.py createsuperuser. Trying to execute the command only gives the following error django.db.utils.OperationalError: no such table: auth_user and connecting to the admin page ( the default http://127.0.0.1:8000/admin ) also gives the same error when inputting a random user name and password. Isn't the instruction supposed to create the table ? I saw nothing in the tutorial about creating that table manually. -
Django Mysql database
So today is my first time connecting my django project to a mysql database. I followed some instructions I saw on the web to do so. When I ran "py manage.py migrate" my cmd said wheel not installed. So I installed it which was a pain finding the right one to install. So after that I ran the command again but my cmd says mysqldb module not found. Right now when I run that command in my venv again this is what shows: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n"). -
Django form not using function parameters correctly
Im redirect to a page with a form on where the user can upload an image and comment but I keep getting errors. I'm trying to make it so that the forbrief field automatically gets via the pk when this function was called. models.py class Designs(models.Model): forbrief = models.ForeignKey(Brief, on_delete=CASCADE) description = models.CharField(max_length=200) postedby = models.ForeignKey(User, on_delete=models.CASCADE, null=True) design = models.ImageField(null=True) date = models.DateTimeField(auto_now=True, blank=True) forms.py class ImageForm(forms.ModelForm): class Meta: model = Designs fields = ['description', "design",] Views.py def designUpload(request, pk): render(request, "users/upload_design_page.html") if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.instance.forbrief = pk form.save() return render(request, 'users/upload_design_page.html') else: form = ImageForm() return render(request, 'users/upload_design_page.html', { 'form': form }) HTML {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endblock %} -
Set instances of a Form without the User input
I am trying to set an instance of a Modelform that render through ListView. Program Model: class Program(models.Model): patient = models.ForeignKey(User, on_delete=models.CASCADE, default=0) program_name = models.CharField(max_length=1000, default="") date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.id) + " - " + self.patient.username + " - " + self.program_name + " - " + str(self.date_posted) def get_absolute_url(self): return reverse('program-detail', kwargs={'pk': self.pk}) Exercise Model: class Exercise(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, default=0) date_posted = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=1000, default="") description = models.TextField(default="") load_share = models.TextField(default="") breath_method = models.TextField(default="") recovery_method = models.TextField(default="") measure_method = models.TextField(default="") notes = models.TextField(default="") extra_info = models.TextField(default="") reps = models.PositiveSmallIntegerField(default=0) sets = models.PositiveSmallIntegerField(default=0) def __str__(self): return str(self.program_id) + " - " + str(self.pk) + " - " + " - " + self.name + " - " + str(self.date_posted) Data Model: exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default="0") set_number = models.PositiveSmallIntegerField(default=0) spo2 = models.PositiveSmallIntegerField(default=0) hr = models.PositiveSmallIntegerField(default=0) physical_level = models.PositiveSmallIntegerField(default=0) breath_level = models.PositiveSmallIntegerField(default=0) sys = models.PositiveSmallIntegerField(default=0) dia = models.PositiveSmallIntegerField(default=0) misc_input = models.PositiveSmallIntegerField(default=0) def __str__(self): return self.exercise.name My Exercise listView include the Data form that the User need to fill up, It is paginated to 1 exercise per page. Exercise ListView: # Exercise list inside each program + Data form class ExerciseListView(LoginRequiredMixin, FormMixin, ListView): model … -
Save a History of person in DB with Django
I'm developing something and I'm having difficulty with a part of the Model, I registered a customer and within this customer, I would like to register customer history information (registered manually), where there will be only 1 text field (unique, because each user has its own history). A story cannot be shown on another customer. When accessing the customers page, inside it will have several customers, when entering the specific customer page, I want to be able to insert a customer information, and in that information, I would like to click "add" and it will go to the bottom of the site, thus recording a 'customer history', this can be done several times, as more than one comment can be made to the customer. How to do this with 'models'? Because I would like to save everything in a database, so I don't have a chance to lose any information. -
Inserting a 'hidden timestamp field' in a modelform?
I have a simple form that allows a user to create a post. The fields are post_title, post_content, post_date. The post_title and post_content will be provided by the user, however the post_date will be autogenerated by the system and will give the current timestamp. Due to this, I will only show both title and content in the form. When I try and submit a request however, this gives me an IntegrityError saying NOT NULL constraint failed: main_app_post.post_date. I am fairly new at Django so I really have no idea what to do. I want it that whenever the user sends a Post request (and if it passes the validations), it will generate the current timestamp to post_date before saving it to the database. Any advices in regards of this? Thanks a lot! models.py: class Post(models.Model): post_title = models.CharField(max_length=100) post_content = models.TextField(max_length=400) post_date = models.DateTimeField() def __str__(self): return self.post_title forms.py: class PostForm(forms.ModelForm): class Meta: model = models.Post fields = ('post_title', 'post_content') views.py: if request.method == 'POST': form = forms.PostForm(request.POST) if form.is_valid(): post_title = form.cleaned_data['post_title'] post_content = form.cleaned_data['post_content'] post_date = datetime.datetime.now().timestamp() form.post_date = post_date form.save(commit=True) -
How can I return an array of objects instead of an array of arrays in Django Rest Framework?
I am trying to display all doctors that work at a certain clinic as an array of objects instead of an array of arrays. http://localhost:8000/api/clinic/ results [ { "id": 1, "doctors": [["Henry", "Ford", 20], ["Elon", "Musk", 30]] // get array of objects instead "name": "Clinic number 1", }, ... ] This how I implemented my models, serializers and viewsets: class Clinic(models.Model): name = models.CharField(max_length=200) class Doctor(models.Model): clinic = models.ManyToManyField(Clinic, related_name="doctors") class ClinicSerializer(serializers.ModelSerializer): doctors = serializers.SerializerMethodField() class Meta: model = Clinic fields = '__all__' class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' class ClinicViewset(viewsets.ModelViewSet): queryset = Clinic.objects.all() serializer_class = ClinicSerializer class DoctorViewset(viewsets.ModelViewSet): queryset = Doctor.objects.all() serializer_class = DoctorSerializer