Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problems with django-ckeditor
I have problems with ckeditor as to how it is shown in my template. It is shown as follows: As you can see the element does not respect the given space. Also when inspecting the code and making the screen smaller does not fit the screen, it always has the same size. Try to solve it with the following CSS styles: .django-ckeditor-widget, .cke_editor_id_content { width: 100% !important; max-width: 821px !important; } But it still has the same behavior and does not work. Any solution to solve this problem? -
Proper way to save image from front end app to backend API
In my case I'm using AngularJS and Django backend with Django Rest framework. So I need to save a Profile data with image. My model in database looks like: class Profile(models.Model): first_name = models.CharField() avatar = models.ImageField() But I can't decide what a best way to save this image on front end. Solution 1 - Convert image to base64 and create Base64Serializer in Django: https://xploit29.com/2016/09/13/upload-files-to-django-rest-framework-using-angularjs/ For me the most easy way Solution 2 - Multipart/form-data File Upload with AngularJS https://withintent.uncorkedstudios.com/multipart-form-data-file-upload-with-angularjs-c23bf6eeb298 I don't like the things like: $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) Looks like hack. And the same on backend side. We need to use https://www.django-rest-framework.org/api-guide/parsers/#multipartparser Solution 3 - Create a separate view to upload files and change database to: class Image(models.Model): image = models.ImageField() class Profile(models.Model): first_name = models.CharField() avatar = models.ForeignKey('Image', null=True, blank=True, on_delete=NULL) It is complicate to use on existing database, but seems very flexible. But also using solution 2 to implement file upload -
Define a list_filter on a manual many-to-many relationship in Django Admin
I have manually devised a many-to-many relationship between a Clothes model and a Seasons model by using a pivot model called Clothes2Seasons, like so: class Seasons(models.Model): name = models.TextField(max_length=10) def __str__(self): return self.name class Clothes(models.Model): name = models.TextField(max_length=20) class Meta: verbose_name = "Clothes" verbose_name_plural = "Clothes" class Cloth2Seasons(models.Model): clothes = models.ForeignKey(Clothes,on_delete=models.PROTECT) seasons = models.ForeignKey(Seasons,on_delete=models.PROTECT) class Meta: verbose_name = "Season" verbose_name_plural = "Seasons" unique_together = ('clothes', 'seasons',) How can I define a function that will allow me to filter on Clothes that have one or multiple seasons (if possible, I would like to have both AND and OR, as in django_admin_multiple_choice_list_filter). -
Resolving "GET /blog HTTP/1.1" 404 2065 (Python Django Tutorial: Full-Featured Web App Part 2 - Applications and Routes)
I am trying to follow this tutorial https://www.youtube.com/watch?v=a48xeeo5Vnk&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=2 on YouTube. I am getting the error message [24/Oct/2019 22:41:41] "GET /blog HTTP/1.1" 404 2065. urls.py from django.urls import path from .import views urlpatterns = [ path('', views.home, name='blog-home'), ] views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResposne('<h1>Blog Home</h1>') # Create your views here. urls.py - django_project1 """django_project1 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] I have tried to clear my history, cache and restart the server. I tried to find any typos I may have made. Other questions on SO about similar issues are either not referencing the tutorial series I am following or are referencing a later episode of the … -
Is it a good practice to have some code running independently of the main app but connecting to the same DB?
I'm a beginner python programmer. I am deploying my Django app to an IT Automation platform (like Heroku) using PostgresQL as the DB. In parallel I also want to deploy several python codes that should collect some data and connect to DB to make updates. I want those codes to run independently (on a separate virtual machine) because I will use cron to schedule their launches and also in order not to overload the app. Some codes will be run every minute updating the DB. So the Django app mostly reads records from the DB, only writing to it when creates/deletes users. Is it a good practise to have a such structure? What problems may arise? What are other options? -
Is it possible to run unit tests on code that uses subprocess?
My Django app has some management commands that start other management commands using subprocess.Popen(['manage.py', '<command>', ...). They are kept like this mainly to run processes in parallel and prevent one command from interfering with another. However, when writing unit tests these new processes don't use the test environment and database and therefore fail. For now, I've added a setting that runs call_command() instead of Popen() (see below): if settings.TESTING: self.returncode = call_command(self.command, *params) else: self.process = subprocess.Popen(['python', 'manage.py', self.command] + params) # ... later on: self.process.wait() self.returncode = self.process.returncode However the subprocess calls and the logic involved in waiting remains untested. Is it possible to test subprocess calls within the unit tests? Note: the test database is not an in-memory SQLite - I know that wouldn't work. It's an actual database that is created and destroyed every run. -
How to dispatch request to some view depending on http method?
I have Post django model: class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() Serializers: class PostListSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'title') class PostDetailSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' Views: class PostListView(generics.ListAPIView): queryset = Post.objects.all() serializer = PostListSerializer class CreatePostView(generics.CreateAPIView): queryset = Post.objects.all() serializer = PostDetailSerializer permission_classes = (permissions.IsAuthenticated,) Endpoint is /api/posts/ How to dispatch request to PostListView if HTTP Method is GET and to CreatePostView if HTTP Method is POST? -
Django Celery Invoking Periodically and Manually
I'm using Django and Celery for scheduling tasks. tasks.py @periodic_task(run_every=crontab(hour='00', minute='00', day_of_week="*")) def hello_world(0): print('hello world!) In addition to running the function daily, I need to be able to invoke it manually. If a user presses a button in the front-end it will run. I could do: @periodic_task(run_every=crontab(hour='00', minute='00', day_of_week="*")) def hello_world(0): print('hello world!) @task() def hello_world(0): print('hello world!) But that goes against DRY. Also, I may have more than one function that will have this same scenario. I will need to run it periodically, but also upon request. I tried this: def hello_world(): print('hello world!) @periodic_task(run_every=crontab(hour='00', minute='00', day_of_week="*")) hello_world() @task hello_world() But that does not work. I get invalid syntax I haven't been able to find this scenario in the documentation or other stackoverflow answers. They talk about invoking the function from the shell. Help would be appreciated. Thanks! -
Django is synchronous or asynchronous?
Django is synchronous or asynchronous? I want to know that the Django Framework is Synchronous or Asynchronous. I have heard about the interview problems they ask about the framework you are using is synchronous or asynchronous. So I want to know the meaning of Synchronous and Asynchronous in terms of web development. -
How to make Django model field derive its value from another field and be non editable
I have a use case in which i have created a custom user model in Django rest framework and another model called Book which is created by a user . My models looks like below : from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin) from django.conf import settings class UserManager(BaseUserManager): def create_user(self, email, password=None, author_pseudonm=None, **extra_fields): """Creates and saves a new user """ if not email: raise ValueError('Users must have an email address') if not author_pseudonm: raise ValueError("User must have an author pseudo name field") user = self.model(email=self.normalize_email(email), author_pseudonm=author_pseudonm, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, author_pseudonm): """Creates and saves a new super user""" user = self.create_user( email=email, password=password, author_pseudonm=author_pseudonm) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model which supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) author_pseudonm = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ["author_pseudonm"] class Book(models.Model): """Custom book model""" title = models.CharField(max_length=255, unique=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) description = models.TextField() price = models.IntegerField() author = models.CharField(default=user.author_pseudonm) is_published = models.BooleanField(default=True) def __str__(self): return self.title In the book model i have a … -
Finding latest date in Django Q object
Not 100% happy with the structure of this code, but unfortunately I can't change it at the moment. I'm searching a big database in Django, and because of technical limitations, I must store a list of Q objects, and use Django's reduce() function to merge the Q objects into a single Queryset. I currently have a model like such: class Obj(models.Model): id_number = models.CharField(max_length=128) modified = models.DateField('%Y-%m-%d', default='1900-01-01') I am currently using the following code to select rows that have an id_number present in a list, latest_ids: split_queries = [] for id_num in latest_ids: split_queries.append(Q(id_number=id_num)) result = Obj.objects.filter(reduce(operator.or_, split_queries)) This is working as I expected, but I would like to only keep the row where id_number=id_num and the date modified is the latest. I have seen solutions such as using Django's aggregate() function or the latest() function, but I can't figure out how to use these with Q objects. I was hoping for a Q object such as Q(id_number=id_num, Max('modified')) is behavior like this possible with Q objects in Django? -
Django / HTML Submit button redirecting to the wrong page
I am trying to make a registration form with Django & HTML and I am following this tutorial: Video 2:45:00 into the video, I do the exact same steps as him, even though the only difference in my code is related to my previous question: My previous thread This is my HTML code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Registration</title> </head> <body> <form action="register" method="post"> {% csrf_token %} <input type="text" name="first_name" placeholder="First Name"><br> <input type="text" name="last_name" placeholder="Last Name"><br> <input type="text" name="username" placeholder="Username"><br> <input type="email" name="email" placeholder="Email"><br> <input type="password" name="password1" placeholder="Password"><br> <input type="password" name="password2" placeholder="Confirm Password"><br> <input type="Submit"> </form> </body> </html> and this is my views.py: from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth def register(request): if (request.method == 'post'): first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) user.save() print('user created') return redirect('') else: return render(request, 'register.html') However, it seems that when I press "Submit", instead of the button actually reading the views.py code and check the IF statement, it just redirects me to localhost:8000/account/register/register, which is completely wrong, such as shown here: Imgur link … -
How should I divide up my project into applications?
I am using Django to create a small website and a small store to go along. I was wondering what are good conventions to split up my project, how do I decide I should create applications with more specific functionality. I heard alot of people write about either projects with 80(!?) apps or tell me each app should have it's own designated and independant functionality. The first makes me none the wiser and the latter indicates that I should create a single app for the entire store. Since payments would be useless without products, and without a shopping cart why even bother with payments... Before I started looking into how I should split it up I guessed that I should divide my shop in something along the lines of: Orders, Profiles, Products and Payments. Where an order is a collection of products, a profile and a payment. Where the payment can be uninitiated, in progress or completed. I believe this would be everything I need for a store. Do any of you have any advice on my implementation or any concrete suggestions on dividing a project into apps, espcecially when on a smaller and simpeler scale. Any articles or resources … -
django 'set' object has no attribute 'items' error
I am trying to deploy my django app on AWS. I create a web-crawler inside my app using bs4 adn requests.I used that to get data from e-commerce sites.it's works perfectly on amazon but it throw this(see at image1) when I try to scrape from newegg. but the same codes works on localhost. first I thought it's the user agent issue and I tried with other user agent but didn't works. I really can't figure out whats the issue so if you know what cause this error then please tell it will be very helpfull. the code and image below: image1 headers = {"User-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"} url = "https://www.newegg.com/p/pl?d="+query data = re.get(url,headers=headers) soup = bs4.BeautifulSoup(data.content, 'lxml') items_container = soup.find("div", {"class":"list-wrap"}) items = items_container.find("div", {"class":"items-view"}) prdList = [] for item in items.find_all("div", {"class":"item-container"}): header = item.find("a", {"class":"item-title"}) title = header.text link = header["href"] img = item.find("a", {"class":"item-img"}) imgsrc = img.find("img")["src"] price = item.find("li", {"class":"price-current"}) if price == None: price = '$--' else: price = price.find("strong").text prdList.append(Scraper.prdTmplt(imgsrc, title, price, link, site)) allProduct = prdList return allProduct -
Does boosting the number of dynos affect NewRelic APM throughput metrics?
Apologies if this is not the right venue/way to ask... I'm asking more out of curiosity than anything else. I've been working on a large application hosted on Heroku. We've implemented rolling deploy, but still try not to deploy during peak usage times. We recently increased the number of dynos by one, and a senior engineer claims that now it's "safe" to deploy at any time regardless of throughput as "the rpms is higher because we have more dynos to handle all the traffic." It looks like throughput is calculated based on the rate of successful request/response, and that requests that error may not be included in this metric. https://discuss.newrelic.com/t/how-is-throughput-calculated/62322 https://discuss.newrelic.com/t/what-is-the-definition-of-throughput/55856 I'm guessing that if there are a very large number of requests, the requests would queue so that more dynos would mean improvements in the request/response cycle. However, how would this affect throughput rates? And further, how would this affect deploy? If the throughput is 30k rpm wouldn't it still be better to wait until later in the day when usage has started to go back down? -
Django Rest Framework- can I allow pk id or full objects in a serializer's create method?
Lets say I have the following models: class Author(models.Model): first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) class Book(models.Model): title = models.CharField(max_length=64) author = models.ForeignKeyField(Author, on_delete=models.CASCADE) And I have the following serializer: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'title', 'author') read_only_fields = ('id') If I then query my books, A book's data looks like: { "id": 1, "title": "Book Title", "author": 4 } Which is what I want, as I return both an array of books, as well as an array of authors, and allow the client to join everything up. This is because I have many authors that are repeated across books. However, I want to allow the client to either submit an existing author id to create a new book, or all of the data for a new author. E.g.: Payload for new book with existing author: { "title": "New Book!", "author": 7 } or, payload for a new book with a new author: { "title": "New Book!", "author": { "first_name": "New", "last_name": "Author" } } However the second version, will not pass the data validation step in my serializer. Is there a way to override the validation step, to allow either an author id, or … -
Django searching
I am trying to make app which user can look for few names of one category in the same time. F.e. There are 10 name like mexicola, red rasputin and black magic. And i wish that user can look for mexicola and red rasputin just with writing "mexicola red rasputin" or "red rasputin mexicola black magic" or just "black magic" and so on. But now it works only with one.. i can not find what is wrong. Here are my views from django.shortcuts import render from django.db.models import Q #new from .models import Recipe from .models import Ingredient def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(): q = (Q(recipe_name__icontains=queries)) results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) model: from django.db import models class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) def __str__(self): return self.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name -
Trying to use natural_key in order to serialize objects
I'm trying to use natural_key methods in order to serialize my models. I have this method in my Monitor model with this inside print: def natural_key(self): print("INSIDEEEEEEEEE") fields = self._meta.fields + self._meta.many_to_many dict_result = {} for field in fields: attr_type = field.get_internal_type() if attr_type == 'ForeignKey': foreign_field = getattr(self, field.name) if foreign_field != None: dict_result[field.name] = foreign_field.natural_key() else: dict_result[field.name] = '' elif attr_type == 'ManyToManyField': foreign_field = getattr(self, field.name) ff_list=[ff.natural_key() for ff in foreign_field.all()] dict_result[field.name] = ff_list else: dict_result[field.field.name] = getattr(self, field.name) return dict_result And I'm calling serializer like this: queryset = serializers.serialize('json', monitors, use_natural_foreign_keys=True) The problem is that this serializer is not executing natural_key method. -
Django 403 Forbidden permission error on Linode even after assigning correct permission to all files.in Apache2
I was trying to host my Django website on Linode. This is how my project heirarchy is. Please access the website here. I haven't touched my etc/apache2/apache2.conf file. / -->root |-->Intranet(Project folder) |-->Intranet |-->wsgi.py Even after granting all the necessary permission I am getting a 403 permission error. The website can be accessed here http://172.105.36.26/. Where am I going wrong with the configuration files. My 000-default.conf file <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost #DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # … -
django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
This has already been asked, but none of the answers have helped me. This is my configuration. I can connect normally to my local db with this exact configuration, only changing the host in settings.py to localhost. Dockerfile FROM python:3.7 RUN mkdir /app COPY requierments.txt /app/ WORKDIR /app RUN pip install -r requierments.txt COPY . /app/ docker-compose.yml version: '3' services: db: image: mariadb:10.2 expose: - 3306 ports: - "3306:3306" environment: MYSQL_DATABASE: 'django_backend' MYSQL_USER: 'django' MYSQL_PORT: '3306' MYSQL_PASSWORD: 'mysql1234pass' MYSQL_ROOT_PASSWORD: 'password' web: build: . image: backendblockchain_web volumes: - .:/app ports: - "8000:8000" depends_on: - db links: - db command: - /bin/bash - -c - | sleep 10 python3 manage.py migrate python3 manage.py runserver 0.0.0.0:8000 setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_backend', 'USER': 'django', 'PASSWORD': 'mysql1234pass', 'HOST': 'db', 'PORT': '3306' } } -
jinja2schema not retrieving set variables
I've just started using the json2schema package to retrieve a list of all the variables (both undefined and defined via set) used in a given template. It is working fine with the undefined variables, but it's not retrieving the set variables. Example: from jinja2schema import infer template_str = "<html> {% set foo = 'bar' %} {{ foo }} {{ fizz }} {{ buzz }} </html>" variables_inferred = infer(template_str) # returns {'buzz': <scalar>, 'fizz': <scalar>} # foo isn't retrieved What am I missing? How can I retrieve the set variables? -
Why do I get Page Not Found (404) when using path() instead of url()?
I am working a new Django app following a YouTube tutorial, and so far in my 'urls.py' I've used this code: urlpatterns = [ path('', views.index, name='index'),] and it just worked. However, now I've reached a point where I'm making subdomains (localhost:8000/accounts/register) and using the following code: urlpatterns = [ path('register', views.register, name='register'), ] gives me the following error: Page not found error image (imgur) However, when instead of using path() I use url(), like so: urlpatterns = [ url('register', views.register, name='register')] it works as expected. What is the difference between path() and url(), and which one should I use (in general or in any specific cases)? Thank you for your help guys, I really appreciate it. -
Update value of a template tag from views in django
I have a form in Django to provide information regarding various tasks on a particular day, and these tasks are saved as model objects. I render the tasks on the HTML page as shown as follows in a grid view. (Click Here for the Grid View) But now I want to be able to show the tasks only on that particular day. Using the arrows on the top right corner, I want to be able to filter the tasks and display them. I have already extracted the current date from the javascript of the calendar and send it via ajax call in my views.py. From there I filter the tasks according to the date, but when once I change the view (ie., the date from the left and right corner arrows) I am able to capture the updated date but not able to update the template tags on the JS side. views.py # The default view when the page loads for the first time # As it loads by default to the current date, so filtering tasks on the current date. def schedule(request): today = datetime.datetime.today() tasks = Tasks.objects.filter(schedule_date=today.strftime("%Y-%m-%d")) context = { "tasks": processes, } return render(request, r'dhtmlx_grid_view.html',context) . . … -
how can we post and get data with React hooks by using api (django)
I work with react hook in frontEnd and django in backEnd. SignIn.js export default function SignIn() { const [email, setEmail] = useState(""); const [Password, setPassword] = useState(""); const [customers, setCustomers] = useState([]); const handleSubmit = (evt) => { evt.preventDefault(); alert(`Submitting email ${email}`) alert(`Submitting Password ${Password}`) } return ( some code for UI ..... ); } My question is how can i post and get data from\to django by using api. in other word how can check if user have account or not (Log in function) and sign up in website Thank you. -
Use datetime picker from django admin
I have a DateTimeField on my model, and I would like to utilise the datetime picker from Django admin. This is my view: class TaskCreateView(LoginRequiredMixin, CreateView): model = Task form_class = CreateTaskForm This is my form: class CreateTaskForm(ModelForm): class Meta: model = Task fields = [ 'title', 'description', 'done', 'due_date', 'priority' ] widgets = { 'due_date': AdminDateWidget() } In my template I have included this: {% block js %} {{ form.media }} <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/actions.min.js"></script> <script type="text/javascript" src="/static/admin/js/calendar.js"></script> <script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script> {% endblock %} However, all I am seeing is an input type="text" with a 'Today' anchor next to it. What do I need to do in order to implement admin datetime picker for my model field?