Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view field and rendering data
Is it possible to multiple view field for a single page/template? as example, suppose I have built site where people can post movie review and see others one as well. Now, I have to add an edit button to the review page and I don't want to let other viewers see that edit option. everyone can only see that edit option when they will be on their own article's page. Can you suggest me how to do that? Still now I have thought to create two different views, one for seeing the review and another one to edit and render them into a single template. -
Sharing Data in multiple databases
I have built an API for an app. It has user authentication through Tokens (Database used is MySQL). I have used django-rest-framework for authentication. Now, we are building a new app. However, the requirement is such that a completely new database (MongoDb) is to be used for it, but the user data should be common between the two apps. The new database has data which may reference a particular user. How exactly can I acheive this ? -
I want to show most liked comments in top list of comment section in django rest framework
I'm working on a project in which I want to show a most liked comment in the top list of comment sections just like Instagram, Facebook works. Here is my serializer PostCommentSerializer:- class PostCommentSerializer(serializers.ModelSerializer): profilephoto = serializers.SerializerMethodField() likes = serializers.SerializerMethodField() likes_count = serializers.SerializerMethodField() replypostcomment = ReplyPostCommentSerializer(many=True) class Meta: model = PostComment fields = ['id', 'commented_by', 'content', 'date', 'profilephoto', 'replypostcomment', 'likes_count', 'likes'] def get_commented_by(self, obj): return obj.commented_by def get_post(self, obj): return obj.post.title def get_profilephoto(self, obj): if profileDB.objects.all().filter(user=obj.commented_by).count() > 0: profile = profileDB.objects.all().filter(user=obj.commented_by) print(profile) return profile[0].profilephoto.url else: print("---------------------->") def get_likes_count(self, obj): return obj.likes.count() def get_likes(self, obj): p = obj.likes.all() lst = [] for i in range(len(p)): lst.append({"id": p[i].id, "username": p[i].username}) return lst here are my views.py add_comment_likes:- @api_view(['POST']) @permission_classes([IsAuthenticated]) def add_comment_likes(request, **kwargs): comment_liked = get_object_or_404(PostComment, pk=kwargs.get('i_pk')) if comment_liked.likes.filter(pk=request.user.i_pk).exists(): comment_liked.likes.remove(request.user) data = PostCommentSerializer(comment_liked, many=False) return Response({'status': status.HTTP_200_OK,'data':data.data}) else: comment_liked.likes.add(request.user) data = PostCommentSerializer(comment_liked, many=False) return Response({'status': status.HTTP_200_OK,'data':data.data}) -
Django: External API response to be mapped and stored into complex model with manytomany relationships
I have a Django application where system on click of a button calls an API. API returns data in a complex structure consisting of a list of items with further nested jsons: [ { "_id": "76070ba8-e9f8-11ea-a1ac-42010a800002", "courses": [ { "_id": "-machine-learning-solutions", "title": " Machine Learning Solutions", "tags": [ "MAChine learning", ] }, { "_id": "natural-language-processing", "title": "Natural Language Processing ", "tags": [ "Natural Language" ] } ], "description": "MAchine Learning "popularity": "This Program is not rated yet" }, { similar structure }] I have a model consisting of many of many relationships with another model like: class Bundle: name = models.charField(max_length=100) items = models.ManytoManyField(Item) popularity = models.CharField(max_length=100) class Item: name = models.charField(max_length=100) provider = models.ForeignKey(provider,null=True, blank=False, on_delete=models.CASCADE, related_name="+") What is the best way to map the json converted response(I have converted it to json using json.dumps for rendering) to a model so that I can call a view on click on the screen and do modelObj.save() or create(). Is there a specific example or tutorial which helps us create a middleware kind of layer for easy mapping of responses? I explored serialiser but did not find a good way to save. Note: due to many to many, I cannot iterate … -
Python import: from .filename import function vs from . import filename
Context: I am trying to import 2 classes located in models.py into another python file called admin.py. The django docs say to use this syntax: from .models import Question, Choice. This is the file structure: file structure Question: Why is it, when I use from . import models and then in the same file call models.Question and models.Choice I get an error for: "ModuleNotFoundError: No module named 'models' " In another file in the same directory, this syntax is used to import a file and call a function within the file without any issues: from . import views ... views.index -
how to fix “django-admin not recognizable error in pycharm”
I am trying to create the python project in the same environment as previous project but am i'm having an error message that it does not recognizes the "django-admin" command please help me to solve this issue.whenever i try to run my admin project i usually get the message (is not recognized as an internal or external command, operable program or batch file).here is a picture of the above error message i usually encounter when i try to run the project -
Django Rest - Return All Value @api_view
Is there a way to return All Value rather than access array like this UserHistorySerializer(queryset[1]) My Code @api_view(['GET']) def get_history(request): queryset = User.history.all() serializer_class = UserHistorySerializer(queryset[1]) return Response({"message": serializer_class.data}) I tried to create functions to return value however i got only one Value. def history_list(queryset): value = [] for data in queryset: return data @parser_classes([MultiPartParser, JSONParser]) @api_view(['GET']) def get_history(request): queryset = User.history.all() serializer_class = UserHistorySerializer(history_list(queryset)) return Response({"message": serializer_class.data}) I also tried to make change function something like below. def history_list(queryset): for data in queryset: return [value for value in data] However, i got error object is not iterable. I'll appreciate of all ur help. Thanks.. -
Why overriding __init__() of a Django model class is not recommended?
I need certain logic when creating new objects in my Django model. The documentation says: You may be tempted to customize the model by overriding the init method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding init, try using one of these approaches: [...] I can use the recommended approaches (classmethod for object creation, or a method on a custom manager), but the user of my class will have to be aware of that. To me it looks that it's less error-prone to provide the user with the default way of creating new objects with c = MyClass(...). I do not need to change the signature. Why is overriding model's __init__() not recommended? -
Combining data from cell and api using django-tables2
I have a simple model: class City(models.Model): name = CharField('name', max_length=120) ident_code = CharField("unique identification code", max_length=24) def get_population(self): return get_info(self.ident_code)["population"] def get_size(self): return get_info(self.ident_code)["size"] and a simple table: class CityTable(tables.Table): pop = tables.Column(accessor="get_population", verbose_name="population") size = tables.Column(accessor="get_size", verbose_name="size") class Meta: model = City sequence = ("id", "unique_ident", "name", "pop", "size",) assigned via a ListView: class CityListView(SingleTableView): model = City template_name = "app/cities.html" table_class = CityTable Now I have an external API ready with a function get_info that hands back information about a city when handed a unique ident code. This function is executed for almost every cell. Just calling get_info("ident_code") would hand me a dictionary {"name": "cityname", "population": 123446543, "size": ...} with many more items - how can I reduce the call to once per line only? Is there a way I can use get_context in the CityListView or something to make the call once and assign variables to some keys like: def get_context(self): inf = get_info(xxx) # how do I get the xx? context = {"population": inf["population, "size": inf["size"] ...} return context -
Inserting IDs to a foreign field in a model in Django SQLite3
I am fairly new to Django, in fact to programming so excuse me for asking such a stupid question. I am having data in a model named "Mdr_data_model". Now I read an excel, converted it into a data frame, storing it in another model named "Transmittal_data_model" which will be having 'almost the same'. class Transmittal_data_model(models.Model): doc_no_client = models.ForeignKey(Mdr_data_model, on_delete=models.CASCADE,max_length = 100, null = True) Now the problem is I have to map the IDs of the data present in the Mdr_data_model model with the Transmittal_data_model. I can upload the data, but mapping the data is where I am facing the problem. Below is the code I tried client_doc_list = list(report_df['Client Document ID']) for i in range(len(client_doc_list)): mdr_trans_filter = Mdr_data_model.objects.filter(doc_no_client = client_doc_list[i]) if len(list(mdr_trans_filter)) != 0: trans_obj[i].doc_no_client = mdr_trans_filter[0] trans_obj[i].save() -
django.contrib.auth.login() function not returning any user as logged in
I have created a basic app using Django's built in authentication system. I successfully created a User object in the shell using >>python manage.py createsuperuser. I then created a basic view, 'UserLogin' along with corresponding serializers/urls, to log an existing user in using the django.contrib.auth authenticate(), and login() functions. Upon testing with the credentials of my created user, the login function seemed to have worked successfully. To test this, I created another view function, 'CurrentUser' which returns the username of the currently logged in user. However, this view returns the user as empty. Why would the 'CurrentUser' view be returning no user as logged in? I have attached my code (minus imports) below. views.py: class UserLogin(APIView): def post(self, request, format = None): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): user = authenticate(username=serializer.validated_data["username"], password=serializer.validated_data["password"]) if user is not None: login(request, user) return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED) return Response("Invalid username/password", status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) class CurrentUser(APIView): def get(self, request, format = None): return Response(self.request.user.username) serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username'] class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=300, required=True) password = serializers.CharField(required=True, write_only=True) urls.py: urlpatterns = [ path('login/', views.UserLogin.as_view()), path('current/', views.CurrentUser.as_view()) ] Any guidance would be much appreciated. Thanks -
how to import celery tasks in django views
I am learning celery with django. I am trying to create a simple addition project with django and celery. I created a simple webapp with django. in the index.html template, I have a form with 2 input fields. The first input field takes the x value (the first number for addition). The second input field takes y value (the second number for addition). When the form is submitted, I want the celery task to run. The django project name is core and the app name is mainapp The celery task is as follows mainapp/tasks.py from celery import Celery from celery.schedules import crontab from celery import shared_task @shared_task def add_num(x, y): return x+y core/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.conf.timezone = 'UTC' app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() mainapp/views.py from django.shortcuts import render from . import tasks # Create your views here. def index(request): if request.method == 'POST': x = request.POST['x'] y = request.POST['y'] print(x, y) add_num.delay(x, y) return render(request, 'index.html') return render(request, 'index.html') I have rabbitmq running in the background with the following command brew services start rabbitmq celery is running in a separate terminal window with the following command celery -A … -
Trying to upload Base64 encoded image using DRF giving error: "the submitted data was not a file check the encoding type on the form"?
Im trying to allow users to submit profiles with one of the fields being a profile picture. When testing the API separately it lets me upload images just fine but when trying to submit it via the front end using a Base64 encoded string, it gives the following error: "the submitted data was not a file check the encoding type on the form error". I am using DRF on the backend and Angular Ionic on the front end. I am using models.ImageField with the Pillow library. I also tried using this solution on stackoverflow but it still was not working for me on the frontend. Code for the backend portion of profile upload: # SERIALIZERS class Base64ImageField(serializers.ImageField): """ A Django REST framework field for handling image-uploads through raw post data. It uses base64 for encoding and decoding the contents of the file. Heavily based on https://github.com/tomchristie/django-rest-framework/pull/1268 Updated for Django REST framework 3. """ def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid # Check if this is a base64 string if isinstance(data, six.string_types): # Check if the base64 string is in the "data:" format if 'data:' in data and ';base64,' in data: # Break out the … -
Django is not logging into file in docker
I have a Django app running in docker which is not writing the logs into the file specified in handlers. But when i do docker logs <container id> i can see the logs on my console. How can i solve this issue. Below is my logging function written in settings.py LOGGING={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file'], 'level':'DEBUG' } }, 'handlers':{ 'file':{ 'level':'DEBUG', 'class':'logging.FileHandler', 'filename': './webapp/logs/debug.log', 'formatter':'simple', } }, 'formatters': { 'simple': { 'format': '{asctime} {name} {levelname} {message}', 'style': '{', } } } Running the same app on local the logs are written to debug.log file. What might be the cause for this ? Dockerfile : FROM python:3.6-slim-buster ENV PYTHONUNBUFFERED 1 RUN apt-get -y update && apt-get install -y \curl \xvfb libfontconfig wkhtmltopdf RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: '3' services: web: build: . command: python ./webapp/server.py restart: always networks: - nginx_network - couchserver_network - dummyapi_flaskapp_network Any help is appreciated -
Django reverse foreign key and too many queries
2 models: class Airport(models.Model): city = models.ForeignKey('City', models.CASCADE, blank=True, null=True) objects = AirportManager() ... def __str__(self): return self.airport_name.get(language="01").title and translates for each one: class AirportTranslate(models.Model): airport = models.ForeignKey('Airport', models.CASCADE, blank=True, null=True, related_name='airport_name') title = models.CharField(max_length=50,blank=True, null=True) language = models.ForeignKey('Language', models.CASCADE, blank=True, null=True) def __str__(self): return f'{self.title}' Django admin create SQL query for each one airport to get a translate (from str method) First of all i tried to add prefecth_related to str method in Airport model. then i tred to create custom manager. (add objects = AirportManager() to Airport model) class AirportManager(models.Manager): def get_queryset(self): return super(AirportManager,self).get_queryset().prefetch_related('airport_name') But nothing change debug_toolbar -
Django Listview FormMixin
I am newbie to django sorry if its a silly question, I was trying to use FormMixin in django, but receiving the following error: return form_class(**self.get_form_kwargs()) TypeError: 'NoneType' object is not callable Forms.py class SubscriberForm(forms.Form): email = forms.EmailField(label='', max_length=100, widget=forms.EmailInput(attrs={'class': 'form-control', 'type':'email'}), validators=[validateEmail]) Views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from .models import Subscriber from .forms import SubscriberForm import random from django.views.generic.edit import FormMixin from django.urls import reverse class NewsletterList(FormMixin, generic.ListView): queryset = newsletter.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' from_class = SubscriberForm def post(self, request, *args, **kwargs): form = SubscriberForm(request.POST) if form.is_valid(): sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() return render(request, "index.html", {'form': SubscriberForm()}) else: return render(request, "index.html", {'form': SubscriberForm()}) Can someone help me pls. Thanks in advance -
Video Streaming website with Django or Django Rest Framework
I want to create a simple video streaming website with Django but i don't know how to do it. Can someone provide appropriate models.py, views.py, urls.py along with proper JS. If you can provide solution using pure django its great but rest framework also works Any help is highly appreciated -
bootstrap4 there is no file named 'css/all.css', 'style.css' and 'lightbox.css'
I'm new to web developing and bootstrap. Now I faced a problem that seems silly but I haven't found any solution for it. At my django project I made a folder named static and copyed css and js files of bootstrap 4 (compiled css and js that I downloaded from "https://getbootstrap.com/docs/4.0/getting-started/download/") into it. Then I added STATIC_ROOT = os.path.join(BASE_DIR, 'static') and STATICFILES_DIR = [os.path.join(BASE_DIR, 'static'),] to my setting.py file, after that on terminal in the virtual env of the project I typed this command python manage.py collectstatic. Now along the steps that I'm following, in the index.html which is simply my home page there are four css links, that are <link rel="stylesheet" href="{% static 'css/all.css'%}">, <link rel="stylesheet" href="{% static 'css/bootstrap.css'%}">, <link rel="stylesheet" href="{% static 'css/style.css' %}"> and <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}">.My Questions1. When there is no all.css, style.css and lightbox.css in the css folder of static files, what are they referring to?2. Is there any problem in the steps that I have described?3. What should I do now? -
public, date database to get information about dates [closed]
I am trying to build a webpage with django. I like to have section that has a sentence about current day and name of it like fathers day or independence day.. Since these days change every year how sould I write the code. Tnx -
Looping through two models that contain lists and are connected Django
I'm a start with Python/Django and I'm currently trying to make a basic app for saving. I have two classes in models.py with the following code: class object_category(models.Model): """This class contains the users different categories""" CATEGORY_CHOICES = [ ('category1', 'category1'), ('category2', 'category2'), ('category3', 'category3'), ] """Plural for multiple categories""" class Meta: verbose_name_plural = 'Categories' """Returns the above stated choices""" category = models.CharField(max_length=50, choices=CATEGORY_CHOICES) def __str__(self): return self.category class object_name(models.Model): """This class contains the object name that is housed within a certain category""" """Links the object to one of the chosen categories""" category = models.ForeignKey(object_category, on_delete=models.CASCADE) # Placeholder for connection with a plant database API object = models.CharField(max_length=50) """Return the object input from the user""" def __str__(self): return self.object and here is the views.py code: def collection(request): """The page that opens the collection of objects""" object_category = Object_category.objects.order_by('category') object_name = Object_name.objects.order_by('object') context = { 'object_category': object_category, 'object_name': object_name } return render(request, 'plntz_main/collection.html', context) finnaly here is my html doc code: {% for category in object_category %} {% for object in object_name %} <h3>{{ category }}</h3> <li>{{ object }}</li> {% empty %} <li>No category has been added yet.</li> {% endfor %} {% endfor %} This displays the category and the objects but … -
Gunicorn is failing to start with code=exited, status=203/EXEC
Gunicorn works when testing with 0.0.0.0:8000 but failing with the production version below. Tried switching user:group to myproject:myproject, root:nginx, myproject:nginx nothing working sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Sun 2020-08-30 08:49:57 PDT; 5s ago Process: 5576 ExecStart=/var/www/myproject/public_py/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/var/www/myproject/public_py/myproject.sock myproject.wsgi:application (code=exited, status=203/EXEC) Main PID: 5576 (code=exited, status=203/EXEC) Aug 30 08:49:57 myprojecthost systemd[1]: Started gunicorn daemon. Aug 30 08:49:57 myprojecthost systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Aug 30 08:49:57 myprojecthost systemd[1]: gunicorn.service: Failed with result 'exit-code'. gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=nginx WorkingDirectory=/var/www/myproject/public_py ExecStart=/var/www/myproject/public_py/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/var/www/myproject/public_py/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target Project lives in /var/www/myproject cat /var/log/nginx/error.log [crit] 1198#0: *51 connect() to unix:/var/www/myproject/public_py/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: xx.xxx.xx.xxx, server: myproject.com, request: "GET / HTTP/1.1", upstream: "http://unix:/var/www/myproject/public_py/myproject.sock:/", host: "myproject.com" stat /var/www/myproject/public_py/env/bin/gunicorn File: /var/www/myproject/public_py/env/bin/gunicorn Size: 243 Blocks: 8 IO Block: 4096 regular file Device: fd01h/64769d Inode: 1066021 Links: 1 Access: (0775/-rwxrwxr-x) Uid: ( 0/ root) Gid: ( 984/ nginx) Context: unconfined_u:object_r:httpd_sys_content_t:s0 Access: 2020-08-30 08:07:44.939754370 -0700 Modify: 2020-08-29 18:16:27.280494281 -0700 Change: 2020-08-30 08:46:09.047708570 -0700 -
How can I make collection page like unsplash in django
I am new to web development, trying to make a image gallery and I can't figure out how to make the collection page. -
Will learning PHP allow me to learn other back end tools like Django or Node easily?
I’m a beginner and I tried learning Django and I was overwhelmed by it so I read somewhere PHP is a little easier compared to node and Django -
In Django, when should we process data in models vs in views
I've noticed that to sort a list view we could call .order_by() in the views.py file, Question.objects.order_by('-pub_date') or use the Meta class inside the model class. ... class Meta: ordering =['-pub_date'] Is any particular approach better ? -
Failed to push some refs to Heroku due to requirement error
I'm new to Django, and I was doing this task with the book Django for beginner, I did everything the book said but keep getting this error when I try to use git push Heroku master. Here is the log: Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Delta compression using up to 4 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 291 bytes | 145.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (1/1), completed with 1 local object. To https://github.com/June907/pages-app.git c9ffa00..b1d98b4 master -> master Branch 'master' set up to track remote branch 'master' from 'origin'. PS C:\Users\Assassin_yoo\Documents\github\bacs350\pages> git push heroku master Enumerating objects: 33, done. Counting objects: 100% (33/33), done. Delta compression using up to 4 threads Compressing objects: 100% (29/29), done. Writing objects: 100% (33/33), 5.91 KiB | 432.00 KiB/s, done. Total 33 (delta 6), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: cp: cannot stat '/tmp/build_f896374c/requirements.txt': No such file or directory remote: -----> Installing python-3.8.5 remote: -----> Installing pip 9.0.2, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing dependencies with Pipenv 2018.5.18… …