Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Heroku admin page formatting
I know this has been around stack, but I have tried all the fixes in other threads and nothing seems to work. I've built a web app using Django and deployed through Heroku. Everything works perfectly. The only problem is the formatting of my live site admin page. It is not formatted nicely like all the other pages. However, it is formatted perfectly when I bring up the site on localhost. I've tried checking all my code in the settings.py file, and I have a static folder set up with a placeholder.txt file. I have all my settings.py code correct I feel. I ran >heroku run python manage.py collectstatic, which executed fine, although when I ran it locally >python manage.py collectstatic, I got an error, saying "django.core.exception.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a file system path" 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 = '((___*)b^_@_+_!' #left out key # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Django-filter - group like values with different primary keys in form
My goal is to filter a model that refers to plants. Below is an abbreviated version of my model: class Plant(models.Model): sku = models.CharField('SKU', max_length=14) name = models.CharField('Name', max_length=50) genus = models.ForeignKey(Genus, on_delete=models.SET_NULL, null=True, blank=True) class Meta: ordering = ['genus', 'name'] def __str__(self): return self.name My related model, Genus, is very basic with just two fields: class Genus(models.Model): common = models.CharField('Common Genus', max_length=100) latin = models.CharField('Latin Genus', max_length=100) class Meta: ordering = ['common'] verbose_name_plural = 'genera' def __str__(self): return self.common The point here is that an entry for Genus will sometimes have the same value for latin. For example Cherry, Peach, and Almond are all prunus but each has its own entry. { [ 'common': 'Cherry', 'latin': 'Prunus' ], [ 'common': 'Almond', 'latin': 'Prunus' ], [ 'common': 'Peach', 'latin': 'Prunus' ] } My problem arises when I use django-filter to filter these values. I have a common name filter and a latin name filter. The common name filter is straightforward since the common names will always be unique, but the latin name might be common among many entries. class LatinChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.latin class LatinFilter(django_filters.ModelChoiceFilter): field_class = LatinChoiceField class ProductFilter(django_filters.FilterSet): genus__common = django_filters.ModelChoiceFilter(queryset=Genus.objects.all(), label='Genus') latin_q = Genus.objects.all().order_by('latin') genus__latin … -
name 'slugify' is not defined
Once a user had logged into my site he could write a post and update it. Then I was making progress in adding functionality which allowed people to make comments. I was at the stage where I could add comments from the back end and they would be accurately displayed on the front end. Now when I try and update posts I get an error message. I assume it is because there is a foreign key linking the comments class to the post class. I tried Googling the problem and looking on StackOverflow but I wasn't entirely convinced the material I was reading was remotely related to my problem. I am struggling to fix the issue because I barely even understand / know what the issue is. # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now()) author = models.ForeignKey(User, on_delete=models.CASCADE) url= models.SlugField(max_length=500, unique=True, blank=True) def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by … -
Django returning None instead of a HTTP response
OK im probably doing this all wrong! I am trying to run a function in a view which calls another view. This seems to pass my request into the next function as a POST method before loading the form from the second function. my views.py def joinLeague(request): if request.method == 'POST': league = JoinLeagueQueue(user=request.user) form = JoinLeagueForm(instance=league, data=request.POST) if form.is_valid(): form.save() context = league.id return confirmLeague(request, context) else: form = JoinLeagueForm() context = {'form':form} return render(request, 'userteams/joinleagueform.html', context) def confirmLeague(request, league): league = get_object_or_404(JoinLeagueQueue, pk=league) pin = league.pin if request.method == 'POST': if 'accept' in request.POST: # This refers to the action from my form which is waiting for a button press in a html form. LeaguesJoinedTo.objects.create( leaguePin = pin, playerjoined = request.user.id, ) return redirect('punterDashboard') else: context = {'league':league} return render(request, 'userteams/confirmleague.html', context) -
Url parameters not get in my views in Django
I want to add and edit in same template. Url showing parameters but id showing none still in my views. http://127.0.0.1:8000/edit_supplierdetails/1 IN My Template: {% for supplier in suppliers %} <a href="{% url 'edit_supplierdetails' supplier.id %}">Edit</a> IN My URL url(r'supplierdetails/', views.add_supplierdetails, name='add_supplierdetails'), url(r'^edit_supplierdetails/(?P<id>\d+)$', views.add_supplierdetails, name='edit_supplierdetails'), In My Views: def add_supplierdetails(request, id=None): print(id) brands = SupplierDetails.objects.all() if id: productcategory = get_object_or_404(SupplierDetails, id=id) title = 'Update' else: productcategory = SupplierDetails() title = 'Add' form = SupplierDetailsForm(request.POST or None, request.FILES or None, instance=productcategory) if request.POST and form.is_valid(): form.save() messages.success(request, "Brand "+ title +" successfully") return redirect('/brand') return render(request, 'products/add_supplier2.html', { 'form': form, 'suppliers': brands, 'title': title }) -
Can't create multiple dynamic sub menus using bootstrap 4
I am currently having issues creating dynamic submenus with bootstrap. Using a simple ajax request I want to get the name of the folders on my Django server and then display the chosen folder items, creating several submenus. I'm using bootstrap 4, the first JS snippet works as intended but I can't get the second one to behave similarly and iterate upon its parent object. HTML <div class="dropdown show"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Analyze </a> <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <li class="dropdown-submenu"> <a id='spec_library' class="dropdown-item dropdown-toggle" href="#">Library</a> <ul id='spec_lib' class="dropdown-menu"> <!-- <li><a class="dropdown-item" href="#">History</a></li> <li><a class="dropdown-item" href="#">Geography</a></li> <li><a class="dropdown-item" href="#">Sociology</a></li> --> </ul> </li> <li><a class="dropdown-item" href="#">Upload</a></li> </ul> </div> JS The first snippet works as intended $('#spec_library').on('click', function(e) { $.ajax({ type: "GET", url: "spectro_lib", /* Call python function in this script */ /* Passing the text data */ success: callback }); function callback(response){ console.log(response) instrument = response size = response.length; spec_lib = document.getElementById("spec_lib") console.log(spec_lib.childNodes.length) $("#spec_lib").empty(); if (spec_lib.childNodes.length <= size){ for (i = 0; i <= size - 1;i++){ var spec_lib_x = "spec_lib_" + i var lib_submenu = document.createElement("li"); lib_submenu.id= spec_lib_x lib_submenu.className="dropdown-item dropdown-submenu" document.getElementById("spec_lib").appendChild(lib_submenu) var lib_subitem = document.createElement("a"); lib_subitem.id= "spec_lib_instrument" lib_subitem.className="dropdown-item dropdown-toggle" lib_subitem.href="#" lib_subitem.innerHTML = response[i] document.getElementById(spec_lib_x).appendChild(lib_subitem) var …