Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to develop Analytical Dashboard using django
I'm working on the project of Analytical Dashboard Web application. In this application user need to import data from datasource like server,local,drive. I don't want to import data from model. Is it possible in django-analytical. Request your suggestion. -
ValueError: cannot assign integer to foreign key during put request
So I have a model like this. class Member(BaseModel): objects = models.Manager() user = models.ForeignKey('api_backend.User', db_index=True, on_delete=models.CASCADE) cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE) And a generic api view for the same. lass MemberPutRetrieveUpdateDeleteView(PutAsCreateMixin, MultipleFieldLookupMixin, generics.RetrieveUpdateDestroyAPIView): queryset = api_models.Member.objects.all() permission_classes = [permissions.IsAuthenticated, IsMemberOrKickMembers] lookup_fields = ['user', 'cluster'] def get_serializer_class(self): if self.request.method in ['PUT']: return api_serializers.PartialMemberSerializer return api_serializers.MemberSerializer def destroy(self, request, *args, **kwargs): member = self.get_object() if member.cluster.owner == member.user: raise exceptions.ValidationError("cannot delete membership with this cluster as you own it.") return super(MemberPutRetrieveUpdateDeleteView, self).destroy(request, *args, **kwargs) I am currently using these mixins. class PutAsCreateMixin(object): """ The following mixin class may be used in order to support PUT-as-create behavior for incoming requests. """ def update(self, request, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object_or_none() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if instance is None: if not self.lookup_fields: lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] extra_kwargs = {self.lookup_field: lookup_value} else: # add kwargs for additional fields extra_kwargs = {field: self.kwargs[field] for field in self.lookup_fields if self.kwargs[field]} serializer.save(**extra_kwargs) return Response(serializer.data, status=201) serializer.save() return Response(serializer.data) def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) def get_object_or_none(self): try: return self.get_object() except Http404: if self.request.method == 'PUT': # For PUT-as-create operation, we need to ensure that … -
Django Makemigrations not working with ForeignKey field to an app that has AppConfig
We have an app called sessions, and since Django has similar django.contrib.sessions app, we need to create an AppConfig to fix the "duplicate app" error, that is, we set the app label as common.sessions. So, we have this folder/files structure: common sessions __init__.py apps.py models.py __init__.py default_app_config = 'common.sessions.apps.CommonSessionsConfig' apps.py class CommonSessionsConfig(AppConfig): name = 'common.sessions' label = 'common.sessions' models.py class SessionEventType(models.Model): name = models.CharField() class SessionEventTypeMapping(models.Model): session_event_type = models.ForeignKey(SessionEventType) settings.py INSTALLED_APPS = ( 'common.sessions', ... ) Running manage.py migrations will throw this error: File "/virtualenv/backoffice/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 125, in handle migration_name=self.migration_name, File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes changes = self._detect_changes(convert_apps, graph) File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/autodetector.py", line 111, in _detect_changes self.new_apps = self.to_state.apps File "/virtualenv/backoffice/lib/python2.7/site-packages/django/utils/functional.py", line 59, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/state.py", line 166, in apps return StateApps(self.real_apps, self.models) File "/virtualenv/backoffice/lib/python2.7/site-packages/django/db/migrations/state.py", line 248, in __init__ raise ValueError(msg.format(field=operations[0][1], model=lookup_model)) ValueError: Lookup failed for model referenced by field common.sessions.SessionEventTypeMapping.session_event_type: common.sessions.common.sessions.SessionEventType Apparently, it fails on this part and could not locate the SessionEventType class/model even though they're just in the same models.py file: session_event_type = models.ForeignKey(SessionEventType) Tried also this variant: session_event_type = models.ForeignKey('common.sessions.SessionEventType') but it didn't help, as well as this related issue. By the way, we're still using Py2/Django 1.8 since it's … -
__init__() got an unexpected keyword argument 'status' error in django
I'm using django-rest-framework. I can't understand why the error occurred. I am trying to save the queryset json. But it doesn't work. My queryset json is as below. I'm sorry for the misalignment. { "data": [ { "code": "123", "name": "hi", "cnt": "3", "construction":"123", "listedDate":"20171112", "lastPrice":"123", "state":"123", "token":"ff35885ab6c63290ccdf60b80a9b37769e287ec5" }, { "code": "123", "name": "hi2", "cnt": "3", "construction":"123", "listedDate":"20171112", "lastPrice":"123", "state":"123", "token":"ff35885ab6c63290ccdf60b80a9b37769e287ec5" }, { "code": "123", "name": "hi3", "cnt": "3", "construction":"123", "listedDate":"20171112", "lastPrice":"123", "state":"123", "token":"ff35885ab6c63290ccdf60b80a9b37769e287ec5" } ] } My Model class Stock(models.Model): code = models.CharField(max_length=20) name = models.CharField(max_length=30) cnt = models.BigIntegerField() construction = models.CharField(max_length=20) listedDate = models.DateTimeField() lastPrice = models.CharField(max_length=10) state = models.CharField(max_length=20) token = models.CharField(max_length=50,validators=[validate_token]) class Meta: db_table = 'stock' def __str__(self): return self.name This is my Viewset from requests import Response from rest_framework import viewsets, status from . import models, serializers class StockViewset(viewsets.ModelViewSet): queryset = models.Stock.objects.all() serializer_class = serializers.StockSerializer def create(self, request, *args, **kwargs): stock_data = request.data.get("data") serializer = self.get_serializer(data=stock_data,many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) print(serializer.data) return Response(serializer.data,status=status.HTTP_201_CREATED,headers=headers) def perform_create(self, serializer): serializer.save() and my serializers from rest_framework import serializers from .models import Stock class StockSerializer(serializers.ModelSerializer): listedDate = serializers.DateTimeField(format="%Y-%m-%d",input_formats=['%Y%m%d']) class Meta: model = Stock fields = '__all__' Even if there is no solution for the above, I would like you … -
name 'request/self' is not defined
Getting requests is not defined. please find the below code(I'm not using it directly in CBV). views.py class ShiftChangeUpdateView(request,PermissionRequiredMixin,UpdateView): permission_required = ('apple.change_shiftchange',) model=ShiftChange logger.info('Data has been Deleted by %s !', request.user.username) fields='__all__' I have checked by using self also but no luck. urls.py url(r'^updategenesys/(?P<pk>\d+)/$', views.ShiftChangeUpdateView.as_view()), How to fix this issue? -
Get Error information while in Production, Django
I'm getting this weird error which only shows when the app i am working on is in production. While its easy to identify and fix the error in development, I'm getting a 500 error page when I switch to production. I'm trying to get a way to discover the error details in productions but this is proving difficult. Some assistance will help. Thanks. -
How to exclude fields from nested representation Django?
I have following UserSerializer class class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'persons'] depth = 1 The depth option allows me generate nested representations { "id": 2, "persons": [ { "id": 1, "name": "Alex", "city": "Paris", "bio": "This is my bio", "phone_number": "9130095484", "age": 24, "height": 56, "weight": 54} ] I don't need all fields in nested representation. How to exclude some fields but keep the depth option? -
Django Not Displaying Image When I Go to image's Link
I was trying to show an image on my webpage but when I go to the image's link it just shows the whole webpage! -
I want to create a page that can upload Excel (xlsx) file and convert to MySQL in Django
i've create python code that can convert excel to mysql, but i have to put it in Web app using Django here's my code for converting excel to mysql import xlrd import pymysql book = xlrd.open_workbook(r'/home/ubuntu/casa_debitur/simpanan.xlsx') sheet = book.sheet_by_name('Sheet1') mydb = pymysql.connect("localhost","vyzyz","vyzyz!","casa_debitur") cursor = mydb.cursor() truncate = "TRUNCATE simpanan" try: cursor.execute(truncate) except Exception as e: print("Occured : ",e) print(truncate) mydb.commit() for row in range(1, sheet.nrows): cif = sheet.cell(row,0).value nama_debitur = sheet.cell(row,1).value produk_simpanan = sheet.cell(row,2).value norek = str(int((sheet.cell(row,3).value))) if len(norek) == 12: norek = '000' + norek if len(norek) == 13: norek = '00' + norek if len(norek) == 14: norek = '0' + norek instanding = str(int((sheet.cell(row,4).value))) query = 'INSERT INTO simpanan(cif, nama_debitur, produk_simpanan, norek, instanding) VALUES("'+ cif +'", "'+ nama_debitur +'", "'+ produk_simpanan +'", "'+ norek +'", "'+ instanding +'")' try: #print(query) cursor.execute(query) except Exception as e: print("Occured : ",e) print(query) mydb.commit() and here is my code for file upload {% extends "base.html" %} {% block content %} <h1>{{ title }}</h1> <form action="/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" title="Upload excel file" name="excel_file" style="border: 1px solid black; padding: 5px;" required="required"> <p> <input type="submit" value="Upload" style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;"> </form> <p></p> <hr> {% for … -
How to add multiple childs to a Parent using only ForeignKey?
I have a parent model and child model. Child model have a foreignkey relationship with the parent model. But If i want to add multiple child to single parent without changing the model then how it is possible.? Child Model class Market(models.Model): market = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) parent_market = models.ForeignKey( 'ParentIndustry', null=True, blank=True, related_name='parent_market', on_delete=models.SET_NULL, default=None) Child Industries But I want to add multiple child industries to Parent then how can i do that in admin.? Parent model class ParentIndustry(models.Model): name = models.CharField(max_length=285, blank=True, null=True) modified_by = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) Parent Industries admin.py class ParentIndustriesAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'company_count','email_count') search_fields = ['id', 'name', ] ordering = ['-date_modified'] def save_model(self, request, obj, form, change): obj.modified_by = request.user obj.save() admin.site.register(ParentIndustry, ParentIndustriesAdmin) -
Why does Django have a slug field?
This might seems a real simple question, but why does Django have a slug field? I have seen may articles about slug fields but I have not seen anybody explain why we should create a slug field. The closest I have seen is a couple of articales saying the URL should be in human readable field and unique is there any other reasons ? -
ModuleNotFoundError: No module named 'user_accounts'
I'm using Django and the CSV built in library and calling/referencing the User Model. I get that error on the implementing line in my python(django) code. import csv from user_accounts.models import CustomUser with open('test_data.csv') as csv_file: csv_reader = csv.DictReader(csv_file) line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: try: user_search = CustomUser.objects.get( id=row["UserId"], username=row["UserName"] ) print('user: ', user_search) except: print('except returned') continue print( f'\t{row["Id"]} works in the {row["UserId"]} department, ' f'and was born in {row["UserName"]}.') line_count += 1 print(f'Processed {line_count} lines.') -
How do I filter from two models (one to one) in Django
I have two models with 1-1 relationship, User and deviceInfo. I am trying to query to get all Users with a specific device ID, and also only guests. My Models: class User(models.Model): userID = models.CharField(max_length=101,primary_key=True) guest = models.BooleanField() class deviceInfo(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE, unique = True) deviceID = models.CharField(max_length=101, default=None) So far I figured out how to filter by device ID. But im not sure how i'd filter this further because the guest value is in another model. What I have so far: (only filters device id) numIDs = LoggedUserInfo.objects.filter(deviceID=deviceId).count() What I tried: (doesn't work) User.objects.filter(loggeduserinfo = numID) I get the error "The QuerySet value for an exact lookup must be limited to one result using slicing." -
Class 'foodgrains' has no 'objects' member error in django
I'm getting this error i'm not finding solution because in earlier i did same things and that worked but now it is not working my views.py file def foodgrainviews(request): foodgrain =foodgrains.objects.all() return render(request,'foodgrains.html',{'foodgrain':foodgrain}) my models.py file #inherit TopList model class foodgrains(TopList): desc = models.TextField(max_length=5000) -
django button click email send
I am a beginner in Django. I want to send an email on button click. Button is delete button. when press on delete button, i want to send an email to receiver@gmail.com. As per the below code, email send when the page loaded. could you please help me to change the as email send on button click. views.py class delete_profile(View): print("nothing") def post(self, request, *args, **kwargs): print("nothing") template = loader.get_template("frontend/subscription-start.html") email_content = "deletion confirmation" send_mail( 'No Dowry Marriage - Subscription', email_content, 'sender@gmail.com', ['reciever@gmail.com'], html_message=email_content, fail_silently=False ) urls.py path('delete_profile', csrf_exempt(delete_profile.as_view()), name='delete_profile') user_profile.html <script> function delete_profile1() { var csrftoken = getCookie('csrftoken'); console.log("rhgrjhrj") $.ajax({ type: 'POST', url: '{% url "delete_profile" %}', data: { csrfmiddlewaretoken: csrftoken }, success: function () { toastr.info('Preference Updated Successfully') } }); } </script> THANKS IN ADVANCE!!!! -
How to insert json data in the form of a table into a webpage?
I have never done front end development before but I have a task where I would have to insert the data extracted from an existing JSON file into an existing webpage with https://........... link. The data has to be inserted inside a table which can be made in the empty webpage by just using the editing tools in that empty page. But the data has to be automatically inserted by appending from the JSON file into the table in that web link. This JSON file is generated from a Python script that I created and I would also need to call that frontend file as well from the python script which would automatically insert the required data from the JSON file into the empty webpage. I was thinking to maybe create an endpoint via Flask/django that will host the json and make an http request from the frontend to get the json. But if I have to make the changes from the fronend of that http:: website don't I need access to the frontend codebase of the webpage? It is since normally that website is secure so people usually use a username and password to log in. To be honest … -
Deserialization error. permission matching query does not exist
I'm trying to deploy my django web app to heroku and I get the deserialization error whenever i run the command 'Heroku run python manage.py loaddata project_dump.json'. Here is my github repo of the project ' https://github.com/hainhtat/carzone-github. Here is the screenshot of the error. Error screenshot -
Is there a Python library to generate a simple misleading web game? [closed]
I am creating a CTF challenge and I want to imbed the flag within the code of a misleading web game. Players might try to complete the game but it won't give them the flag. Is there a way to generate one of those games (like a maze) easily with a Python library? Or maybe somewhere I can copy paste the code from? I will be using the Django framework. -
Django-allauth manual linkup for existing users
I am using django-allauth for social login. But existing users doesn't have any Social account or Social application token..Is there any way to manually assign them Social Account and Social Application Token from python shell / admin-panel? -
How to escape SECRET_KEY in Django from environment file when generated SECRET_KEY begins with '$'?
In my Django project I have a .env file that contains the SECRET_KEY for the production settings. I generated the secret key by running a script from the command line (Here it just prints the generated key as an example). python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())' It just so happens that a secret key was generated that started with a '$' character. My .env file looked like this. DJANGO_SECRET_KEY=$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2% This is read in my production settings file in the following way import os import environ env = environ.Env() # BASE_DIR is the root level directory of the project env_file = os.path.join(BASE_DIR, '.env') if os.path.exists(env_file): environ.Env.read_env(env_file=env_file) # reading .env file SECRET_KEY = env('DJANGO_SECRET_KEY') When I run my Django project with this secret key I get the following error django.core.exceptions.ImproperlyConfigured: Set the *%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2% environment variable Because of the '$' character Django seems to think that the secret key value is an environment variable itself. This is understandable as environment variables in Bash have a '$' prefix. But when I try changing the .env file to DJANGO_SECRET_KEY='$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2%' or DJANGO_SECRET_KEY="$*%0e@-7suq*h#2(srya8n&lhb(qy+73xj_db)tpq4qenknk2%" I get the same error. How do I escape the SECRET_KEY in an .env file on the off chance a secret key is … -
Django cursor.executemany what's the preferred batch size for each "executemany"
I use the following code to do bulk insert with extended "insert into". cursor = connections['default'].cursor() sql = "INSERT INTO %s (%s) VALUES ([xxx], [xxx], ...) " step = 1000 for l in range(0, len(values), step): s_values = values[l:l+step] cursor.executemany(sql, s_values) My question here is if I have a lot of rows to insert, for example, 100, 000: should I insert in one query. or call multiple executemany with fixed step, such as 1000. I read some articles, it is suggest to use 100. I test my code with 100, 000 records to insert. One executemany is faster than multiple. I am not sure what should I do. Not sure whether I miss understood something here. Please help to comment. Thanks. -
Could not import models from the same folder in Django
I cannot import my models in my api/views.py of my products app. Every folders and subfolders are shown in the image here. Products app Image My api\views.py is from products.models import * class CategoryAPIView(ListAPIView): queryset = Category (cant import Category) -
Return name of model an authenticated user belongs to
I have custom user models from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Meta: verbose_name = 'supplier' verbose_name_plural = 'suppliers' class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) is_hub_manager = models.BooleanField(default=False) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) class Meta: verbose_name = 'worker' verbose_name_plural = 'workers' Views.py class AccountType(APIView): permission_classes = (IsAuthenticated,) def get(self, request, format=None): print(type(request.user)) return Response({'account_type':"supplier"} , status=status.HTTP_202_ACCEPTED ) and I have created /auth/account_type which is supposed to return the type authenticated user I would like it to be able to return a response like { "account_type": "Supplier" } where the word Supplier is got from the name of the model class it belongs to. What is the best way to achieve this? -
How to extract PDF data in Django?
I have been trying to extract the data from pdf files, but not with any success. On the website, the user can upload a PDF file and that PDF file's data should save into the database. I am using the below model. from django.db import models class Document(models.Model): document = models.FileField(upload_to='documents/') My view is the following from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from .forms import DocumentForm def index(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'app/index.html', { 'form': form }) forms.py from django import forms from .models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) Template: <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> <center> <h1>Adcuratio Assignment {{ filename }}</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ … -
I'm getting errors when attempting to makemigrations and tables aren't being created
So I'm getting some errors when attempting to run "python3 manage.py makemigrations". A small snippet of the errors are as follows: Traceback (most recent call last): File "/home/vincentqchen/.venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "catalog_video" does not exist LINE 1: INSERT INTO "catalog_video" ("url", "title", "length", "view... ^ This is my models folder: from django.db import models import os from datetime import datetime #Google api import json from googleapiclient.discovery import build #Scheduler from apscheduler.schedulers.background import BackgroundScheduler class Video(models.Model): #youtube_cache = models.ForeignKey(YoutubeCache,on_delete=models.CASCADE) url = models.CharField(max_length=600, null=False, blank=False) title = models.CharField(max_length=600, null=False, blank=False) length = models.CharField(max_length=600, null=False, blank=False) views = models.IntegerField(null=False, blank=False) date = models.DateField(auto_now=False, auto_now_add=False) ytType = models.CharField(max_length=30, null=False, blank=False) # Create your models here. def ytCacheHelper(): youtube = build('youtube','v3',developerKey = Secret) #Most popular videos in the us YTrequest = youtube.videos().list( part="snippet,contentDetails,statistics", chart="mostPopular", regionCode="US" ) response = YTrequest.execute() #Python dictionary of all top yt videos items = response['items'] for x in range(len(items)): # Parts of video snippet = items[x]['snippet'] contentDetails = items[x]['contentDetails'] statistics = items[x]['statistics'] # Figure out length of video length = contentDetails['duration'] length = length[2:] #Figure out date of video date = snippet['publishedAt'] year = int(date[:4]) month = int(date[5:7]) day = int(date[8:10]) hour = int(date[11:13]) minute …