Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django POST query: Pass tuple or list in a param
I am trying to pass a tuple in a DJANGO POST query. But it is taking the value type as string. Like this: ('id','country_name') I found various links but none on how to pass a list/tuple in params. -
Django "Illegal mix of collations" for MySQL utf8mb4 table
I have reviewed other questions related to this topic, such as django python collation error However, the solutions say to encode the table using a utf8 charset. That is not a viable solution for our modern Django app running on a utf8mb4-encoded database. In my case, I need to enforce a charset or collation in the Django generated query, or in the DB itself, when utf-8 characters are being passed in (from a call to model.objects.get_or_create(), I believe with an emoji character being passed in one of the kwargs fields.) I'm getting this error: django.db.utils.OperationalError: (1267, "Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='") Any advice welcome. Thanks! -
Set the value of the Django 2 Admin Autocomplete widget using jQuery
I'm trying to add some custom logic with jQuery to a django admin view. I want to change the value of some select fields on my tabular inline fields when the value the "formula" Select Input Change. I've tried the following code, but the django admin autocomplete values does not change. rowNumber = 0 var ingredientInput = $('#id_formulaexplosioningredient_set-' + rowNumber + '-ingredient'); // console.log('aaa', ingredient, rowNumber, ingredientInput, ); console.log('select', ingredientInput.select2()); console.log('djangoAdminSelect2', ingredientInput.djangoAdminSelect2()); ingredientInput.djangoAdminSelect2().val(ingredient.ingredient.id.toString()).trigger('change'); ingredientInput.select2().val(ingredient.ingredient.id.toString()).trigger('change'); ingredientInput.val(ingredient.ingredient.id.toString()).trigger('change'); As you can see I tried 3 ways, with the val() of the element. The val() of the select2 plugin and the val() of the djangoAmindSelect2() plugin. Can anyone help me out and show me what I'm doing wrong? Thank you! -
Revoke-token error in oauth2 Django Oauth2
I have such a trouble I can't do revoke-token command in oauth2 django convert-token works good,and i don't understand why,they are quite similar I call each command with PostMan,but second don't want to work. Trace:{ "error": "invalid_request", "error_description": "URL query parameters are not allowed" } In addition,i am doing it with YouTube guide,step-by-step,but nothing help I was trying to call it from windows cmd,trying to search for different solutions online but nobody has the same. 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 = ''#i will hide it for my sec # 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', 'ba_app', 'users', 'bootstrap3', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] 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 = 'be_aware_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'be_aware_project.wsgi.application' # … -
Python add multiple strings to one string with indexes same time
I have a long text, and some list of dict objects which points indexes of this long text. I want to add some strings to this indexes. If I set a loop, indexes change and I must calculate the indexes again. I think this way very confusing. Is there any way add different strings to different indexes in single time? My sample data like that: main_str = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.' my indexes list like that: indexes_list = [ { "type": "first_type", "endOffset": 0, "startOffset": 5, }, { "type": "second_type", "endOffset": 16, "startOffset": 22, } ] My main purpose: I want to add <span> attributes to given indexes with some color styles based on types. After that I render it on template, directly. Have you another suggestion? -
Save data into two table. Student with ID “None” doesn’t exist. Perhaps it was deleted?
I tried to save data to the standard User class and for my Student class. But I've got a problem. Student with ID “None” doesn’t exist. Perhaps it was deleted? models.py class Student(models.Model): studentIndex = models.IntegerField(unique=True) studentName = models.CharField(max_length=50) studentSurname = models.CharField(max_length=50, default='') studentPhoneNumber = models.CharField(max_length=12, default='+48') studentPesel = models.CharField(max_length=11, default='') studentStudyMode = models.CharField(max_length=12, default='') studentFaculty = models.CharField(max_length=30, default='') studentSemester = models.IntegerField(default='') studentAddress = models.CharField(max_length=255, default='') studentMotherName = models.CharField(max_length=100, default='') studentBirth = models.DateField(help_text='year-month-day') studentEmail = models.EmailField(max_length=255, default='') studentImage = models.ImageField(default='default.jpg', upload_to='profile_pics') studentPassword = models.CharField(max_length=100, default='12345678', help_text='Do not modify this field. Password will be generated automatically') studentDateJoined = models.DateTimeField(default=now) def save(self, *args, **kwargs): default_password = str(self.studentBirth)[0:4] + str(self.studentBirth)[5:7] + \ str(self.studentBirth)[8:10] +\ self.studentMotherName[0] +\ lower(self.studentName[0]) User.objects.create_user(username=self.studentIndex, email=self.studentEmail, password=default_password, first_name=self.studentName, last_name=self.studentSurname) def __str__(self): return f'{self.studentIndex} - {self.studentName} {self.studentSurname}' When I try this ... def save(self, *args, **kwargs): default_password = str(self.studentBirth)[0:4] + str(self.studentBirth)[5:7] + \ str(self.studentBirth)[8:10] +\ self.studentMotherName[0] +\ lower(self.studentName[0]) Student.objects.create() # <- this one User.objects.create_user(username=self.studentIndex, email=self.studentEmail, password=default_password, first_name=self.studentName, last_name=self.studentSurname) I've got string index out of range error (IndexError) or maximum recursion depth exceeded in comparison (RecursionError) I'm new in Django, so I'll be grateful if you'll help me Thanks a lot -
The model Group is already registered in app 'auth'
I switched my database to Postgresql and I'm having issues registering them to the admin interface. I'm having the error The model Group is already registered in app 'auth'. But, when I try to unregister the model (reference: Already Registered at /appname/: The model User is already registered), I get the error: django.contrib.admin.sites.NotRegistered: The model User is not registered It's really weird. Let me know if you need any piece of code. Thanks in advance! -
Django - Retrieving data from different spans
I am actually having a page which asks the user to build a team from a list of names and also to select some few other things later on the page.. I am a using Django and then I am a bit lost on the best way I could get this data from (the selected elements) Almost all my clickable elements are of type span. I also would like to get some data from two select elements. My questions are the following: Is it possible to get the data I want by using this page? or should I start over do a Django Form? (I have done this page way before I started Django and I spent hours on it, so I would like to avoid starting over...) If it is possible, then What would be the best way I could get all the data I want using Django? Here is a picture of my page for you to see what I am trying to achieve: select teammates select parts Here is an sample of my code: HTML <div class="card-body" id="team-list"> <p class="card-text">Select today's teammates:</p> <ul class="list-group list-group-flush"> <li class="list-group-item"> <span class="name">name 1</span> <span class="move" style="float: right;">Add to the team</span> … -
Deleting a very big folder in Google Cloud Storage
I have a very big folder in Google Cloud Storage and I am currently deleting the folder with the following django - python code while using Google App Engine within a 30 seconds default http timeout. def deleteStorageFolder(bucketName, folder): from google.cloud import storage cloudStorageClient = storage.Client() bucket = cloudStorageClient.bucket(bucketName) logging.info("Deleting : " + folder) try: bucket.delete_blobs(blobs=bucket.list_blobs(prefix=folder)) except Exception as e: logging.info(str(e.message)) It is really unbelievable that Google Cloud is expecting the application to request the information for the objects inside the folder one by one and then delete them one by one. Obviously, this fails due to the timeout. What would be the best strategy here ? -
ModelForm not processing upload
I have a ModelForm in django: class uploadform(forms.ModelForm): class Meta: model = upload fields = ['email', 'title', 'date', 'file'] From the model: class upload(models.Model): email = models.EmailField() title = models.CharField(max_length=100) date = models.DateField() file = models.FileField() Here is my view for processing the form: def upload(request): if request.method == 'POST': form = uploadform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('upload') else: form = uploadform() context = { 'form': form } return render(request, 'content/upload.html', context) Here is my HTML: <div class="site-section mb-5"> <div class="container"> <div class="form-register"> <form method="POST"> {% csrf_token %} <legend>Upload Content</legend> <div class="form-group"> {{ form | crispy }} </div> <button class="btn btn-outline-info" type="submit">Upload</button> </form> Form populates well, form will allow me to attach, but whenever I press "Upload", I get redirected with the file actually going to S3. I know my S3 connection is correct because If I go to admin and create an upload, the file will appear in S3. What could be causing the file upload from the form.save() to not work? -
ProgrammingError at / relation "blog_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_post"
Im getting this error when Im trying to deploy my django project to Heroku. Can anyone help -
Django error: Tcl_AsyncDelete: async handler deleted by the wrong thread
I am totally new in Django and I am having this error while I was trying to upload a CSV file through rest API. Basically, the back-end will receive sensor data as a CSV file. and the algorithm will run and proposed the sensor data and will return back a plotting script to the frontend. data_pre_process.py has a function called main def main (data): ld = LidarData(data) ld.apply_all_cleaning(verbose=False) angs,ss = compute_ransac_angles(ld.x, ld.y, n_win=80, n_trials=100, verbose= True) trans_slide = search_transition_regions(angs, verbose=True) wall_lines = compile_walls(trans_slide, ld.x, ld.y, verbose=True) sects = get_wall_corners(wall_lines) return ld here compute_ransac_angles takes around 20 sec to compute and process the data properly. overall the main takes 30 sec to return back the results after all the computation. here is my views.py from django.shortcuts import render from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.exceptions import ParseError from rest_framework.parsers import FileUploadParser from lidar.create_plot import plotting, floorPlanPlotting from lidar.data_pre_process import * ########### # Create your views here. class lidarApi(APIView): def post(self, request): lidarData= request.data["data"] result = main(lidarData) plot = floorPlanPlotting(result) #check_request = request.data #plot = plotting(check_request) return Response(plot) for the very first case, it's working fine. but after few times later back end stop working … -
How Can I fix it?The app shows error in API key just like (KeyError: 'Api Key not found. ')
from django.shortcuts import render from django.contrib import messages from airtable import Airtable import os AT = Airtable(os.environ.get('AIRTABLE_MOVIESTABLE_BASE_ID'), 'Movies', api_key=os.environ.get('AIRTABLE_API_KEY')) Create your views here. def home_page(request): ##print(str(request.GET.get('query',''))) user_query=str(request.GET.get('query','')) return render(request,'movies/movies_stuff.html') -
adding percentage to graph
my code class BarChart(Drawing): def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.add(String(200, 180, 'Hello World'), name='title') self.add(Pie(), name='pie') self.add(Legend(), name='leyenda') h=Donador.objects.filter(genero='M').count() m=Donador.objects.filter(genero='F').count() datos = [(colors.yellow, 'Hombres'), (colors.red, 'Mujeres')] self.title.fontName = 'Helvetica-Bold' self.title.fontSize = 12 self.pie.slices[0].fillColor=colors.yellow self.pie.slices[1].fillColor=colors.red self.pie.data = [h, m] self.pie.x = 50 self.pie.y = 0 self.pie.width = 150 self.pie.height = 150 self.leyenda.x= 300 self.leyenda.y=100 self.leyenda.colorNamePairs = datos This code generates a pdf file with a pie chart. What I want is that said chart show percentages thanks you -
How can I get the particular friend who like my post
I'm new in Django. I have friends in Manytomany field, how do I get my friends who liked my post. When my friend liked my post, I want to display is profile_pic at the side of my like count, but if a user who is not my friend is profile_pic will not display. I attached an image so that my question can be clearly understood. class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) profile_pic = models.ImageField() friends = models.ManyToManyFiels('Profile', related_name='my_friends') class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL) likes = models.ManyToManyField(User, related_name='image_likes) def home(request): user = request.user list_friends = user.profile.friends.all() -
Is it possible to pull 600,000 rows from a MySQL database and Display it as JSON data in postman?
I am trying to return a MySQL table with 600,000 rows and display it as a JSON object. My views.py contains the method below. def SettlementsStatements_1(request, query=""): if query =="All": namemap={'ID':'id','Comapny Name':'COMPANY_NAME'} ssr=SettlementsStatements.objects.raw('SELECT id,COMPANY_NAME FROM telco_amazon.settlements_statements;',translations=namemap) data = serializers.serialize('json', ssr) return JsonResponse(data,safe=False) I am calling this view in postman and it has yet to load after 40 minutes.I am wondering, is it even possible to extract and load this much data? -
Como posso mudar o estilo de uma form do Django
Estou fazendo um site de Quizzes e estou com problemas na edição de usuários usando a model form do Django. Porém, queria que ele ficasse dessa forma: https://i.imgur.com/P09UMkT.png só que não estou conseguindo fazer. Resumindo, queria que o formulário do Django ficasse da mesma forma da print acima, só que fazendo da forma que fiz ele não vai. Desde já agradeço. edit.html <body data-spy="scroll" data-target=".navbar" data-offset="50"> <div class="container py-2 mt-5"> <div class="row my-2"> <div class="col-lg-4"> <h2 class="text-center font-weight-light">User Profile</h2> </div> {% csrf_token %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> {{ error }} </div> {% endfor %} <div class="col-lg-8"> </div> {% for field in form %} <div class="col-lg-8 order-lg-1 personal-info"> <form role="form" method="post"> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">Nickname</label> <div class="col-lg-9"> <input class="form-control" type="text" value="{{user|title}}" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">{{field.name}}</label> <div class="col-lg-9"> <input class="form-control" type="email" value="" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">{{field.name}}</label> <div class="col-lg-9"> <input class="form-control" type="password" value="11111122333" /> </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label form-control-label">{{field.name}}</label> <div class="col-lg-9"> <input class="form-control" type="password" value="11111122333" /> </div> </div> <div class="form-group row"> <div class="col-lg-9 ml-auto text-right"> <a href="/"><input type="reset" class="btn btn-outline-secondary" value="Cancel" /></a> <a href="{% url 'accounts:edit' %}"><input type="button" class="btn … -
Is there a way to prevent keyboard focus from being lost when reloading a pdb target?
If I'm debugging a django view with runserver and I change python source without exiting the debugger, the python process will notice the change and reload. This reload will kill the current context, and now keystrokes won't be sent to the terminal. To close the process I have to kill the terminal entirely. Is there a way to get the reloading django process to cleanly kill the open debugging process and ensure I can still control-c out of the runserver? -
How can I add a picture to the DetailView template?
I built an website and used my model 'Post' in the DetailView CBV. I have another Model called: 'UserProfileInfo' in which I have a imagefield. I want to display the post author pic next to his name in the post_detail template. How can I do this? I know I cant specify 2 models as the models in the DetailView function.. I thought about adding it to the get_context_data view somehow.. I dont realy know. The relevant code: Models: class UserProfileInfo(models.Model): user = models.OneToOneField(User, models.PROTECT) # mode ls.PROTECT is an on_delete value which protect the source model and if he is not existed or having a problem he raises an Error to alert us # additional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='TheApp/profile_pics',blank=True) def __str__(self): return self.user.username class Post(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) post_views = models.IntegerField(default=0) def get_absolute_url(self): return reverse("TheApp:post_detail", kwargs={'pk':self.pk}) def __str__(self): return self.title The view: class PostDetailView(LoginRequiredMixin, DetailView): model = Post def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) obj = self.get_object() obj.post_views = obj.post_views + 1 obj.save() return context The template: {% extends "TheApp/base.html" %} {% block body_block %} <div class="container" style="margin-top:50px; margin-bottom:20px;"> <h1>{{post.title}}</h1> <div style="margin-bottom:20px;">{{ post.create_date }}</div> <p>{{ post.text }}</p> … -
Extract filtered data in django
OrderFilter is a django-filter. The export is working but I have only the header ... when i remove the request.get.get i have all the data extracted so i assume there is problem somewhere in my get request Can you help me please Views.py def Order(request): filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date') """ Don't work Category_query = request.GET.get('Category') qs = Order.objects.filter(Category= Category_query) """ if request.GET.get('Export') == 'Export': response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xlsx"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows=qs.values_list('Date', 'Category', 'Item') for row, rowdata in enumerate(rows): row_num += 1 for col, val in enumerate(rowdata): if isinstance(val,datetime.date): val = val.strftime('%d/%m/%Y') ws.write(row_num, col, val, font_style) wb.save(response) return response return render(request, 'template.html',{'orders':orders,'filter': filter}) template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <form method="GET" > <button class="btn btn-warning" type="submit" value="Export" name="Export"> Export</button> </form> -
Grabbing data from Postrgresql to Django
I'm new to Postgresql (and databases in general) and I have one that I filled with a lot of data. But now I need to access that data and create models, register it in the admin, etc. Does anybody know how I can do that? This is the data that I retrieved: https://github.com/guenthermi/the-movie-database-import -
How to modify messages displayed in Admin change page?
I have a model Document, and the admin can upload an image to a FileField. When a document/image is successfully uploaded, I also save a sha256 "fingerprint" of the image to test if an admin tries to upload a duplicate image. If a duplicate image is detected, I don't save the duplicate image and display an error message to the admin through the messages framework. However, I also get the message that the document was successfully uploaded. How can I prevent this from happening? My code in an abbreviated form: class Document(Model): document_id = models.AutoField(primary_key=True) computed_sha256 = models.CharField(editable=False, max_length=64, default="foobar") storage_file_name = models.FileField('File name', upload_to=settings.DOCUMENT_FOLDER_ORIGINALS, default=settings.DEFAULT_IMAGE_XXXLARGE_PATH,) class DocumentAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if form.is_valid(): if not change: # Uploading one or more images files = request.FILES.getlist('storage_file_name') if files: for f in files: # Check if this file has been uploaded before by checking the fingerprint _file = form.cleaned_data["storage_file_name"] sha256 = image_processing_utils.compute_sha256(_file) duplicate_files = Document.objects.filter(computed_sha256 = sha256) if len(duplicate_files) > 0: messages.add_message(request, messages.WARNING, 'Uploading a duplicate of "%s" and it will not be saved' % f.name) break; # more image processing stuff else: # some more image processing stuff obj.metadata = form.cleaned_data['metadata'] super().save_model(request, obj, form, change) The resulting admin … -
Django REST Framework - Only first query parameter showing in request.get_params
I would like to filter a queryset in a view using multiple query parameters, but "request.query_params" is only able to get the first query parameter in my query string. Here is my URLConf: urlpatterns = [ ... re_path(r'^descsearch/$', views.DescriptionSearchView.as_view(), name='descsearch'), ] Here is the top of my view where I'm attempting to get two query parameters from the query string ("description" and "descSearchMethod"): class DescriptionSearchView(generics.ListAPIView): serializer_class = DrawingSerializer def get_queryset(self): print("request.query_params: " + str(self.request.query_params)) description = self.request.query_params.get('description') print("description: " + description) descSearchMethod = self.request.query_params.get('descSearchMethod') print("descSearchMethod: " + descSearchMethod) ... When I make this GET request using curl: curl -X GET http://127.0.0.1:8000/api/descsearch/?description=O-RING&descSearchMethod=and The print statements in the Django console show that only the first query parameter "description" is in QueryDict. request.query_params: <QueryDict: {'description': ['O-RING']}> description: O-RING Internal Server Error: /api/descsearch/ ... If I switch the order so that "descSearchMethod" is the first query parameter, only it shows. Why is only the first query parameter showing in QueryDict? -
How can I open page with celery task?
from celery import Celery from celery import shared_task from Group.models import Group from django.shortcuts import render, redirect @shared_task def hello(): print('hello') return render() I want to open certain page with this task in django, is possible? return render not working! -
How do I change some routes in Django Project after login?
Let me explain with an example. Like when we first open www.coursera.org we get to their homepage. Then we login. After we login the session starts and we are redirected to main course dashboard. but if we see URl it is www.coursera.org so now the home route has chanmged from homepage to say dashboard. Now in django i can redirect to project.com/dashboard from project.com/login but what i want is after login the user should not have access to homepage at any route. So i want to change project.com/ which before login showed homepage to now showing the dashboard view simply change the view function linked to project.com/ route I hope I explained my question correctly. Thank you for help in advance