Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's on_delete=CASCADE not deleting models from database
I have the following model: class WishListRelationship(models.Model): user = models.ForeignKey(UserProfile, db_index=True, blank=False, null=False, related_name='wishlist', on_delete=models.CASCADE) book = models.ForeignKey(Book, blank=False, null=False, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'wishlist_relationship' verbose_name = 'Wish list relationship' verbose_name_plural = 'Wish list relationships' unique_together = (('user', 'book'),) def __unicode__(self): return "%s -> %s" % (self.user, self.book) def __str__(self): return "%s -> %s" % (self.user, self.book) However, when I delete an user this model is not being deleted but user is being set as None instead (although the user is configured with on_delete=CASCADE and null=False). I've already read that Django will emulate the behavior of the SQL constraint specified by the on_delete argument, but what does it means? What should I have to do in order to have the WishListRelationship deleted on cascade when either an user or a book is deleted? Thank you very much in advance. -
Unable to create object with Many-to-many relation and request data in multipart/form-data
I have a user model with many to many relationships with the model team: class User(AbstractBaseUser): """ model to store user infomation """ ..... team = models.ManyToManyField( "team.Team", blank=True, related_name="team_member") ..... Here is a snippet of UserSerializer: class UserSerializer(serializers.ModelSerializer): """ User serializer for user ModelViewSet """ ..... team = serializers.PrimaryKeyRelatedField( queryset=Team.objects.all(), many=True, required=False, allow_null=True, ) ..... class Meta: model = User exclude = () and here is the view for same: class UserViewSet(viewsets.ModelViewSet): """ User model view """ ..... def create(self, request, *args, **kwargs): request.data._mutable = True team = request.data.get('team') team = json.loads(team) request.data['team'] = team serializer = self.get_serializer_class() serializer = serializer(data=request.data) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) ..... Below is attached screenshots of request body using postman form-data: Anyone can guide me on what I am doing wrong here. -
Python, Ubuntu, Linux
Is there any possibility to make any working screen into dark theme. For example, there is one drag and drop menu same as taking screen shot manually in windows or Ubuntu. In this case can we make an virtual screen which converts any screen into dark theme with altering text and some menu colours on virtual screen? -
unable to load tensorflow in django
I am trying to build a application using tensorflow, but when i include the tensorflow in django and try to start the development server, i get error as below. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 98, in handle self.run(**options) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 105, in run autoreload.main(self.inner_run, None, options) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 317, in main python_reloader(wrapped_main_func, args, kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 296, in python_reloader reloader_thread() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 274, in reloader_thread change = fn() File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 203, in code_changed for filename in gen_filenames(): File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 101, in gen_filenames [filename.__file__ for filename in new_modules File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 102, in <listcomp> if hasattr(filename, '__file__')]) File "/usr/local/lib/python3.7/site-packages/tensorflow/__init__.py", line 50, in __getattr__ module = self._load() File "/usr/local/lib/python3.7/site-packages/tensorflow/__init__.py", line 44, in _load module = _importlib.import_module(self.__name__) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in … -
Invalid Literal for int() with base10 error [closed]
I have a model called Project, class Project(models.Model): name = models.CharField(max_length=50, unique=True) technology = models.CharField(max_length=50, unique=True) def __str__(self): return self.name In my views.py, I am trying to get Projects.objects.all() but I get this error : ValueError: invalid literal for int() with base 10: b'17 04:47:27.864928' What could be the issue? I am using Django 2.2.1 and Python 3.6 versions. -
Add choices in ListView Django
I have the view which displays all transactions. I have a table with contractors and I want to display all rows from this table in the options to <select>. How can i do this? My view: class TransactionView(CustomPermissionRequired, ListView): # Переопределение из MultipleObjectMixin model = Transaction context_object_name = 'transactions' paginate_by = 20 login_url = '/' permission_required = ( 'registration2.can_see_payments', ) # Переопределение из TemplateResponseMixin template_name = 'payments.html' search_fields = [ ('contractor_name', 'deal__service__contractor__name__icontains'), ('from_pay_date', 'payment_date__gte'), ('to_pay_date', 'payment_date__lte'), ('tr_id', 'id__icontains') ] # Переопределение из MultipleObjectMixin def get_queryset(self): print('get_def') filter_args = [] filter_kwargs = {} for sf in self.search_fields: if sf[0] is not None: sf_value = self.request.GET.get(sf[0]) if sf_value: filter_kwargs[sf[1]] = sf_value return Transaction.objects.all().select_related('currency', 'payment_source__payment_type', 'deal__service__contractor' ).filter(*filter_args, **filter_kwargs).order_by('-id') def get_context_data(self, **kwargs): context = super(TransactionView, self).get_context_data(**kwargs) for sf in self.search_fields: if sf[0] is not None: context[sf[0]] = self.request.GET.get(sf[0]) return context My models Transaction and Contractors: class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) # service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) class Contractors(models.Model): id = models.IntegerField(blank=True, null=False, primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) -
display progress bar for ffmpeg process in front-end
I'm working on a cms project in which i have to transcode video files using ffmpeg. The transcoding proecss has been successfull. But i have to display the progress of the ffmpeg process in front-end. I tried pytranscoder,which failed to display the progress. Any help will be appreciated. Note: I'm using Ubuntu 14.04 -
TinyMCE not showing up in Django admin
I was just trying out tinymce. It worked well with the default config (I didn't put anything in the config). Later I found a few configs on the web and copy pasted them into the settings, and it worked fine. However upon copy pasting another config, the TinyMCE form doesn't seem to be displaying. My web app is a blog post. My settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'sid&6o(*h*r!9p+gs-++chd+c(8(awc^u6*1yia5s8a^csmgip' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'marketing', 'tinymce', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bootstrapblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join('templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bootstrapblog.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
how to create functional api in django restframework
we have 3 tables and I need to create and access with one api with those 3 tables using django rest framework.how to create functional api in django rest framework -
Python regex to get longest text inside single quotes
I have a variable with the below text/string: INSERT INTO "some_table" (id,field) VALUES ('1','01060000CDA209WE140000010000'); I want to retrieve the value inside the single quote, i.e. 01060000CDA209WE140000010000 Looks to me that I have to extract all strings between single quotes and then choose the longest one. -
Django URL appending hash
Hi All i have a small test app that has a basic model with a form based on this model: class PublicNotesPost(models.Model): noteName = models.CharField(max_length=255) termsAgreed = models.BooleanField(default=False) noteData = models.TextField() def __str__(self): return self.pk class Meta: verbose_name_plural = "Test Note Post Data" My aim is when i post a note it redirects to a viewer with a dynamic url, at the moment i have not setup the viewer just an empty html file with a H1 tag just to test redirection. However what happens is a Hash is appended to the end of the url and i cant for the life of me figure out why this is and wanted to post here in case anyone has experienced this and has an understanding of how to rectify it? http://127.0.0.1:8000/note/ryXVe7tAhC/# My Url patterns are as follows: from django.urls import path from .import views urlpatterns = [ path('note/composer/', views.NoteComposer.as_view() ,name="note_composer"), path('note/<str:shorturl>/', views.ViewNote ,name="noteviewer") ] View functions: from django.shortcuts import render, redirect from .forms import PostComposerForm from django.urls import reverse from django.views import View import string import random # Create your views here. def short_random_string(N:int) -> str: return ''.join(random.SystemRandom().choice(string.ascii_uppercase +string.ascii_lowercase+ string.digits) for i in range(N)) class NoteComposer(View): def get(self, request): try: formdata … -
how to make each note created specific to a particular user in Django
i have created the user dashboard and want to allow a specific user to create note, how can that be done? Models.py class Client(models.Model): user = models.OneToOneField(User, null=True, blank=True, unique=True, on_delete=models.CASCADE) TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Ms', 'Ms'), ('Miss', 'Miss'), ('others', 'others'), ) title = models.CharField(max_length=250, null=True, choices=TITLE) First_name = models.CharField(max_length=250, null=True) class Note(models.Model): title = models.CharField(max_length=250, null=True) notes_content = models.TextField(null=True) please how do i create a function to let me; -
How do I use Python list on my JavaScript?
I have a python list that has lists inside. I rendered it into Django template to use in my . But the problem is that, whenever I try to console.log(array.length), it gives me every single character, instead of how many lists there are inside of a list. -
How to call Drive API in backend after user picked the item from Google Picker?
User clicks the login button and after the OAuth dance flow I get access token along with client id client secret and refresh token. Now in UI, I will call Picker API to display document files. Once the user picked any document I will send a link to my backend for further processing. Now I get the File not found an error in my backend console. Here is my python view code. request_body = json.loads(request.body) document_id = request_body.get("document_id") credentials = google.oauth2.credentials.Credentials( request.user.profilegoogle.token, refresh_token=request.user.profilegoogle.refresh_token, token_uri=request.user.profilegoogle.token_uri, client_id=request.user.profilegoogle.client_id, client_secret=request.user.profilegoogle.client_secret, ) drive_service = build("drive", "v3", credentials=credentials) document = drive_service.files().get(fileId=document_id).execute() print(document) And my javascript file to create the picker loader. var view = new google.picker.View(google.picker.ViewId.DOCS); var picker = new google.picker.PickerBuilder() .enableFeature(google.picker.Feature.NAV_HIDDEN) .enableFeature(google.picker.Feature.MULTISELECT_ENABLED) .setAppId(appId) .setOAuthToken("{{ request.user.profilegoogle.token }}") .addView(view) .addView(google.picker.ViewId.DOCUMENTS) .setDeveloperKey(developerKey) .setCallback(pickerCallback) .build(); picker.setVisible(true); I think my access_token somehow messed up but I can't able figure out the exact place causing this issue. -
How can we use on_update CASCADE in django?
Scenario: We have a table of members in our schema which has foreign key references to multiple tables on a certain attribute in member table: member_id (which is explicitly generated during member creation which is unique for every member). Example: Member table id member_id first_name last_name -- --------- ---------- ------- 12 xyzqfad Test Member Transactions table txn_id txn_value member_id ------ --------- -------------- 425 500 xyzqfad Requirement: When we are deleting the member we want to modify the member_id some other value Final state: Member table id member_id first_name last_name -- --------- ---------- ------ 12 MASKED12 ****** ****** Transactions table txn_id txn_value member_id ------ --------- --------- 425 500 MASKED12 Problem: We are unable to modify the member_id due to the presence of foreign key references on member_id in other tables. -
Django: Querying of interlinked modals ... how best to achieve a prefetch or select related?
I have the following two modals, the notion of a Waiver: class Waiver( BaseModels.AbstractUUIDModel, BaseModels.AbstractTimestampedModel, ): ... And the notion of a CheckIn: class CheckIn( BaseModels.AbstractUUIDModel, BaseModels.AbstractTimestampedModel, ): waiver = models.ForeignKey('Waivers.Waiver', on_delete=models.CASCADE) Essentially, a CheckIn is linked to a Waiver. Within a viewset, I would like to return a QuerySet of Waivers, with the associated CheckIns linked. I have tried to produce the following to get a .values() list of the queryset. Waiver.objects.filter( void_type='0' ).filter( performance_datetime__year=date.year, performance_datetime__month=date.month, performance_datetime__day=date.day ).exclude( code='SPECTATOR' ).prefetch_related( 'checkin_set' ).order_by( 'performance_datetime' ).values() However, this doesn't seem to be prefetching the CheckIns...am I missing something here? -
Django allauth module throw error at login?
This is happen at login submit form, the problem is that I do not know how to debug it .. AttributeError at /users/login/ 'NoneType' object has no attribute 'is_active' Exception Location: C:\projects\Django-project\lib\site-packages\allauth\account\utils.py in perform_login, line 132 I can provide much more information (code) if need it. -
How can I use to Description of parameters about swagger.ui in django
I try to """ parameters: - name: test description : "TEST" """ but It does not apply.. -
iterate over two lists simultaneously from views.py in templates
I've two dictionaries. After value from one dictionary is selected, I've to display the other dictionary and this process should continue like a loop in templates(index.html) from views.py. can anyone tell me how to do that? -
Dash Callback Inside Functions
As you can see below i have a Dash application that generate routes by functions, however my callbacks to perform table calculations is not working as expectet. I tried let callback that return app before and after callbacks that update tables however it not worked also. How is the reason for these callbacks stop to work, also teher are anyway to make this work again? Ihave a dispathcer function, that request params, also i have a function that create app, and functions that generate routes(pages) in my app. import sys from random import randint import base64 import io import dash import dash_core_components as dcc import dash_html_components as dhc import pandas as pd import random import plotly.graph_objects as go import dash_table import dash_table_experiments import dash_table import dash_bootstrap_components as dbc import os from os import listdir from dash.dependencies import Input, Output, State def dispatcher(request): ''' Main function @param request: Request object ''' app = _create_app() params = { 'data': request.body, 'method': request.method, 'content_type': request.content_type } with app.server.test_request_context(request.path, **params): app.server.preprocess_request() try: response = app.server.full_dispatch_request() except Exception as e: response = app.server.make_response(app.server.handle_exception(e)) return response.get_data() def _create_app(): ''' Creates dash application ''' app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.config['suppress_callback_exceptions']=True app.layout = dhc.Div(children=[ dbc.Navbar( [ dhc.A( # Use … -
What's more efficient for real time web apps, ajax or websockets?
I'm building a real time webapp with django. The backend gets updated every 15min and I currently use ajax to update the template every 5min. I'm planning on having 1000 users logged in at the same time, will ajax be enough? I have been reading about django channels (Websockets) and I'm not sure how they will improve my webapp. -
How to use mysql in django project [duplicate]
When i run migrate command it gives following error- django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the dja ngo_migrations table ((1064, "You have an error in your SQL syntax; check the ma nual that corresponds to your MySQL server version for the right syntax to use n ear '(6) NOT NULL)' at line 1")) I have change my settings file in django- 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'thesocial', 'USER': 'root', 'PASSWORD': '1234', 'HOST': '127.0.0.1', 'PORT':'3306' } django version-3.0.3 python version-3.7.3 mysql query browser-1.2.12 -
Django stubs interrupt Pycharm autocompete
I have a django app with several models. Here is autocomplete when I filter objects Then I install django-stubs for MyPy pip install django-stubs Now my autocomplete looks like this When I delete django-stubs autocomplete works well, like on the first picture pip uninstall django-stubs So, is there a way to use django-stubs with Pycharm Django autocomplete? I use Pycharm Professional 2019.1 and Python3.7 -
adding auth decorators to class based views
hi there im trying to apply auth decorators to my class based views but they seem not to work since when i view the template i do not get redirected to the default accounts/login/next? url from .forms import TodoForm from .models import Todo from django.template import loader from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic import ( CreateView, ListView, DetailView, UpdateView, DeleteView ) from django.urls import reverse from django.shortcuts import render, get_object_or_404 # Create your views here. @method_decorator(login_required, name='dispatch') class TodoListView(ListView): template_name = 'ToDo/todo_list.html' queryset = Todo.objects.all() @method_decorator(login_required, name='dispatch') class TodoDetailView(DeleteView): template_name = 'ToDo/todo_detail.html' queryset = Todo.objects.all() def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Todo, id=id_) -
OneToOne field from two models
I have three models two of them select a value from another . But I want if the value is taken by a model to not be select by another Exemple: class Model_A(models.Model): ip = models.GenericIPAddressField(unique=True) class Model_B(models.Model): pc = models.CharField(max_length=100) ip = models.OneToOneField(Model_A, on_delete=models.CASCADE) class Model_C(models.Model): printer = models.CharField(max_length=50) ip = models.OneToOneField(Model_A, on_delete=models.CASCADE) When I insert in Model_B and select ip field from Model_A to cannot be selected by Model_C if I want to insert there something. How I do that?. Sorry for my English