Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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… … -
Django inline formset delete is not working
My system has Formulas and each formula can have a lot of FeedstockFormulas. This is my view: def feedstockformulas(request, id=0): formSet = inlineformset_factory(Formulas, FeedstockFormulas, fields=('feedstock', 'ratio'), extra=1) formInstance = Formulas.objects.get(pk=id) if request.method == 'POST': formInstance = Formulas.objects.get(pk=id) form = formSet(request.POST, instance=formInstance) if form.is_valid(): form.save() formInstance.save() return redirect('dashboard:formulas-index') form = formSet(instance=formInstance) return render(request, 'dashboard/formulas/form2.html', {'form': form}) When I open the form page after adding some FeedstockFormulas and try to delete one, I simply can't. I checked the delete box and then pressed the button to send form and nothing happened. Is there some error in my view code? -
django css works for sometime and then stops
so i'm using django in my project my problem is that the css file works properly for sometime and then stops working for no reason i don't know if i'm changing something or.. , but i think i"m not changing anything related to css i'll show you all my configuration for the css, so i have in my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] the static file is located in project-folder/static/css/main.css and here it is .home-images { height: 10px; } .another-image { margin-left: 293px; margin-top: 290px; } and i have {% load static %} in the html file <!-- Bootstrap's CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <!-- My css --> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> please don't down vote, i need to figure this out i've been facing it for a long time -
Attach data to label (Chart.js & Django 3)
I got this view where I get 3 types of data, defining my labels and add 2 dicts to each other, to display the collected amount of expenses in one bar in my chart.js. In this case I only got one object in each expenses, that is created in August, but it displays as created in January. It seems like I do not attach the month of the object being created with the correct label. How can I achieve this? class SalesExpensesChart(APIView): """ View to list all sales and expenses. * Requires session authentication. * Only the users own data is visible to the user authenticated. """ authentication_classes = [SessionAuthentication] permission_classes = [] def get(self, request, format=None): user = Account.objects.get(email=request.user) invoices = user.invoice.all() expenses_to_pay = user.expenses_to_pay.all() expenses_paid = user.expenses_paid.all() # Get total earnings in the different months (month: 1-12) total_earn_month = {} for invoice in invoices: invoice_month = invoice.created_at.month if invoice_month in total_earn_month: total_earn_month[invoice_month] += invoice.total else: total_earn_month[invoice_month] = invoice.total # Get total expenses to pay in the different months (month: 1-12) total_etp_month = {} for expense in expenses_to_pay: etp_month = expense.invoice_date.month if etp_month in total_etp_month: total_etp_month[etp_month] = expense.price else: total_etp_month[etp_month] = expense.price # Get … -
Uploading two different Csv file in django with different Encoding
In my Django admin i have a button which is used to upload csv File. I have two files, one in UTF-8 Encoding and one in ASCI/cp1252 encoding. So in my code if i write data = pd.read_csv(value.file, encoding = "ASCI", engine='python') one csv file is uploaded but other after being uploaded it has special character between texts. I dont want special characters to be uploaded. And if i write data = pd.read_csv(value.file, encoding = "UTF-8", engine='python') The one showing special characters does not give error while other one do not gets uploaded. Can anyone tell me how to fix this? Below is my Forms.py class CsvUpload(forms.Form): csv_file = forms.FileField() def clean_csv_file(self): # Probably worth doing this check first anyway value = self.cleaned_data['csv_file'] if not value.name.endswith('.csv'): raise forms.ValidationError('Invalid file type') try: data = pd.read_csv(value.file, encoding = "UTF-8", engine='python') data.columns= data.columns.str.strip().str.lower() data=data.rename(columns = {'test case id':'Test Case ID'}) except Exception as e: print('Error while parsing CSV file=> %s', e) raise forms.ValidationError('Failed to parse the CSV file') if 'summary' not in data or 'Test Case ID' not in data: raise forms.ValidationError( 'CSV file must have "summary" column and "Issue Key" column') return data -
Django - Keep latest record of User
I want to keep the latest record of a user: class Record(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='site_pics') date = models.DateTimeField(null=True, blank=True, auto_now_add=True) def save(self, *args, **kwargs): super(Record, self).save(*args, **kwargs) numdata = Record.objects.select_related('name').count() print(numdata) #if numdata > 1: # Record.objects.select_related('name').first().delete() As per this post Filter latest record in Django, I tried: .distinct() .select_related() .prefetch_related() None of them return the correct number of records or don't work at all because I'm using SQLite. Thank you for any suggestions -
How to get the content from my database in views.py? [Django]
I am trying to print the content fields from my database, Here's my models.py file: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() read_time = models.TimeField(null=True, blank=True) view_count = models.IntegerField(default=0) Here's my views.py file:- class PostDetailView(DetailView): model = Post def get_object(self): obj = super().get_object() obj.view_count += 1 obj.save() return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) all_texts = { 'texts': context.content } print(all_texts[texts]) return context I am trying to access all the data's from the content field from my database, But the above way is not working, Is there any way I can access all the data's from the content field, because I have to perform some action on these fields, like calculate the read_time of any content, based on the length of it. -
Is this the right way to code this django rest api function ? I have a post as well as a delete function inside the post request function
Is this the right way to code this django rest api function ? I have a post as well as a delete function inside the post request function. Is there a better way or is this the way to do it? Iam new to this django rest api. class AcceptFollowRequestAPI(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def post(self, *args, **kwargs): current_user = request.user user = Account.objects.get(id=self.kwargs['id']) contact, created = Contact.objects.get_or_create(user_from=user, user_to=request.user) if user != request.user: create_action(user, 'started following', current_user) notify.send(current_user, recipient=user, verb='has accepted your follow request.') notify.send(user, recipient=current_user, verb='started following you.') return Response({'response':'Started following'}, status=status.HTTP_201_CREATED) try: pending_request = PendingRequest.objects.get(send_user=user, recieve_user=current_user) pending_request.delete() except PendingRequest.DoesNotExist: return Response({'response':'Not Found'}, status=status.HTTP_404_NOT_FOUND) -
Trouble toggling text in for loop, using javascript
I have a list of cards displayed via a for loop. On click I want to toggle some text. It works fine for the top card, but when I click the card below, it toggles the first card. This is the case even though i've given the cards different id's used in the javascript toggle function. Any ideas about what i'm doing wrong? <!-- HTML --> {% for card in cards %} <div class="card mb-3"> <div class="card-header"> <img class = "float:left mr-2 mt-1 small-profile-picture" src ="{{ card.creator.profile.image.url }}" > <a class="mb-4 float-up" > {{ card.creator }}</a> <small> <p class=mt-2> {{ card.date }} </p> </small> </div> <!-- Card Header ender --> <!-- Here we have the questions and answers --> <div onclick="myFunction()" style="cursor: pointer;"> <div class="card-body mt-4"> <h5 class="card-title"> <a class="article-title">{{ card.question }}</a></h5> <p id="myDIV{{card.card_id}}"> Click to see Answer </p> <!-- <p class="card-text"> {{ card.answer}} </p> --> </div> <!-- Card body ender --> </div> <!--Javascript --> <script type="text/javascript"> function myFunction() { var x = document.getElementById("myDIV{{card.card_id}}"); if (x.innerHTML === "Click to see Answer") { x.innerHTML = "{{card.answer}}"; } else { x.innerHTML = "Click to see Answer"; } } </script> {% endfor %} Thanks for reading