Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: OR search with the field value of the model and the m2m field value of that model is slow
Django: It takes a long time to filter the m2m model from the m2m-connected model by specifying the field values of the m2m model This question is similar to this one, but when I do a filter using the m2m field from a model that is tied to m2m, the query is very slow. How can I reduce the number of useless INNER JOIN as shown in the answer to the question above? Video.filter(Q(title__icontains='word') | Q(tags__name__icontains='word')).order_by('-published_at') Query issued SELECT "videos_video"."id" FROM "videos_video" LEFT OUTER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") LEFT OUTER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id") WHERE (UPPER("videos_video"."title"::text) LIKE UPPER('%word%') OR UPPER("videos_tag"."name"::text) LIKE UPPER('%word%')) ORDER BY "videos_video"."published_at" DESC; EXPLAIN(ANALYZE, VERBOSE, BUFFERS) QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Gather Merge (cost=51955.59..52038.90 rows=714 width=24) (actual time=1209.450..1305.089 rows=335972 loops=1) Output: videos_video.id, videos_video.published_at Workers Planned: 2 Workers Launched: 2 Buffers: shared hit=1617 read=19577, temp read=14576 written=14846 -> Sort (cost=50955.57..50956.46 rows=357 width=24) (actual time=1194.858..1209.600 rows=111991 loops=3) Output: videos_video.id, videos_video.published_at Sort Key: videos_video.published_at DESC Sort Method: external merge Disk: 3712kB Buffers: shared hit=1617 read=19577, temp read=14576 written=14846 Worker 0: actual time=1187.952..1202.470 rows=110827 loops=1 Sort Method: external merge Disk: 3696kB Buffers: shared hit=556 read=6211, temp read=5020 written=4740 Worker 1: actual time=1189.482..1203.544 rows=113757 loops=1 Sort Method: external merge Disk: … -
Django/Pillow - Image resize only if image is uploaded
I'm able to upload an image and resize it, but if I submit the form without images I get this error The 'report_image' attribute has no file associated with it. What should I do if no image is uploaded? This is my models.py class Report(models.Model): options = ( ('active', 'Active'), ('archived', 'Archived'), ) category = models.ForeignKey(Category, on_delete=models.PROTECT) description = models.TextField() address = models.CharField(max_length=500) reporter_first_name = models.CharField(max_length=250) reporter_last_name = models.CharField(max_length=250) reporter_email = models.CharField(max_length=250) reporter_phone = models.CharField(max_length=250) report_image = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True) date = models.DateTimeField(default=timezone.now) state = models.CharField(max_length=10, choices=options, default='active') class Meta: ordering = ('-date',) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.report_image.path) if img.height > 1080 or img.width > 1920: new_height = 720 new_width = int(new_height / img.height * img.width) img = img.resize((new_width, new_height)) img.save(self.report_image.path) def __str__(self): return self.description -
ckeditor5 error "toolbarview-item-unavailable" on Vuejs3 and Django
I am using CkEditor5 on my Vuejs3 and Django project, it works fine but I cannot use additional features, gives me error toolbarview-item-unavailable. What should I do to upload pictures to my django app? Features I got Features I want to get <script> import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; export default { data() { return { editor: ClassicEditor, editorData: '<p>Asosiy malumotlar</p>', editorConfig: { // The configuration of the editor. toolbar: { items: [ 'heading', '|', 'alignment', '|', 'bold', 'italic', 'strikethrough', 'underline', 'subscript', 'superscript', '|', 'link', '|', 'bulletedList', 'numberedList', 'todoList', 'fontfamily', 'fontsize', 'fontColor', 'fontBackgroundColor', '|', 'code', 'codeBlock', '|', 'insertTable', '|', 'outdent', 'indent', '|', 'uploadImage', 'blockQuote', '|', 'undo', 'redo' ], } } } }, } </script> -
Guidance question: Dockerized Django backend, and React front end Intranet application authentication question
This is more of a guidance question for a situation where we're stuck. Basically we've to deploy an Intranet application on client's Windows based network. Our API backend is written in Django which serves React based frontend, during offline development phase we used DRF - AuthUsers, Django Rest Framework and Simple JWT tokens, and deployed using Linux Docker Images. We've to deploy these in client's environment for which we've to implement Single Sign-On, Windows active directory authentication. Ideal target is Kubernetes but for first cut we can use plain old Docker containers. After some research, and input from client's IT dept, we've to use Apache2 Webserver docker container, set Kerberos config, keytab and deploy in same domain as that of Active Directory. We've few blockers: 1) Should we create 2 separate Apache2 based docker images, one to host Django backend and other for React frontend? 2) Where should we implement AD Authentication? i.e. frontend or backend? 3) If AD authentication needs to be impelemented, what are the required npm packages that we can try out? Most of articles/blogs for this scenario are referring to MSAL.js but our AD is on premises, not Azure based. We're using Axios for calling Django … -
Assertion Error - calling an function method inside another function in Django
I have created two API's ("startshift", "endshift") when they click on the "startshift" and "endshift" button, an another API "UserShiftDetailsAPI" will be called which return the response based on "UserStartShift" and "UserStopShift".These API are working correctly I have created a conditional statement in "UserShiftDetailsAPI" for both "UserStartShift" and "UserStopShift" but its giving as assertion error. I don't know how to call the both API method inside the function. Here, What I have tried views.py: startshift @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) if request.method == 'POST': UserId = request.data.get('UserId') Ip = request.data.get('Ip') PortNumber = request.data.get('PortNumber') cursor = connection.cursor() r=cursor.execute('EXEC [dbo].[Usp_StartShift] @UserId=%s, @IP=%s, @Port=%s', (UserId, Ip, PortNumber,)) return Response(True, status=status.HTTP_200_OK) endshift @api_view(['GET', 'POST']) def UserStopShift(request, UserId): if request.method == 'GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[USP_StopShift] @UserId=%s',(UserId,)) return Response(True) elif request.method == 'POST': serializer = UserShiftEndSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In GET method I have applied the condition but its showing an error. It should return the response based on the "UserStartShift and "UserStopShift" method UserShiftDetails @api_view(['GET']) def UserShiftDetailsView(request, userid): try: users = tblUserShiftDetails.objects.filter(UserId=userid) except tblUserShiftDetails.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': if UserStartShift == True: cursor … -
Django HTTP Error 404: Not Found: Using a config.json file in my views
I have 3 apps and one is called 'cv' but for this app I use a config.json file but it keeps giving me a 404-error when loading the page. My project is called "project_1" and my urls.py is defined as: urlpatterns = [ path("", include("cv.urls")), path("admin/", admin.site.urls), path("projects/", include("projects.urls")), path("blog/", include("blog.urls")), ] http://127.0.0.1:8000/admin http://127.0.0.1:8000/projects and http://127.0.0.1:8000/blog can be reached, but when I open http://127.0.0.1:8000 It gives me the error. In the cv-directory, I have my urls.py defined as: urlpatterns = [ path("", views.index, name="cv_index"), ] And my cv/views.py as: def index(request): BASEURL = request.build_absolute_uri() url = BASEURL + "/static/configuration/configuration.json" response = urllib.request.urlopen(url) configuration = json.loads(response.read()) return render(request, "index.html", configuration) Where my json configuration is located in the cv directory under static>configuration>configuration.json When I change my index function in cv/views.py to just render the request and give back my index.html file, it goes fine. So I expect it has something to do with this piece of code: BASEURL = request.build_absolute_uri() url = BASEURL + "/static/configuration/configuration.json" response = urllib.request.urlopen(url) configuration = json.loads(response.read()) My traceback looks like this: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.6 Python Version: 3.9.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', 'blog', 'cv'] Installed … -
cant get hello world in django
I have python version 3.10.1 and django version 4.0 url in project( name = home)` from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('hello.urls')), path('admin/', admin.site.urls), ] url in app (name = hello) from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('hello.urls')), path('admin/', admin.site.urls), ] views in app from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello World") I tried running server with and without adding 'hello' in setting.py still i get only default page. stuck from 3 days -
django : 'app name' is not a registered namespace
i have a "NoReverseMatch" error, how can i slove this i don't understand- Project_name/urls.py path('orders/',include('orders.urls')), ordres/urls.py from .views import chack_out path('chack_out/', chack_out, name='chack_out') ordres/views.py def chack_out(request): ..... product(anther app name)/product/templates/cart.html <form action="{% url 'orders:chack_out' %}" method="POST"> {% csrf_token %} error page -
The model is used as an intermediate model, but it does not have a foreign key error with through models
I am new to Django and currently trying to improve on a design I have been using. This is my models.py file. from djongo import models import uuid PROPERTY_CLASSES = ( ("p1", "Video Property"), ("p2", "Page Property"), ("trait", "Context Trait"), ("custom", "Custom Property") ) class Device(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class Platform(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class EventPlatformDevice(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = "Event Specifics" event_field = models.ForeignKey('Event', on_delete=models.CASCADE) applicable_apps = models.ForeignKey('Platform', on_delete=models.CASCADE) applicable_devices = models.ManyToManyField('Device') property_group = models.ManyToManyField('PropertyGroup', blank=True) custom_properties = models.ManyToManyField('Property', blank=True) class Event(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) applicable_platforms = models.ManyToManyField(Platform, through=EventPlatformDevice) class PropertyGroup(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) applicable_properties = models.ManyToManyField('Property') class Property(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) #applicable_platform = models.ManyToManyField(Platform, through=PlatformDevice) property_class = models.CharField(max_length=20, choices=PROPERTY_CLASSES) format_example = models.TextField(blank=True) notes = models.TextField(blank=True) The issue I am running into is with the EventPlatformDevice model. Right now in the Admin Panel I am able to select multiple items for the applicable_devices, property_group, and custom_properties field. The applicable_apps field is a single select. I am trying to turn that into a multi select as well but when changing the … -
The current path, /django_plotly_dash/app/test/, didn’t match any of these
We have a platform deployed on Django and we wanted to implement a dashboard created using plotly and dash in the existing Django application that we have. I followed some tutorials and integrated the dashboard application just the way everyone did but whenever I tried to go to the application url I get this message: The current path, /django_plotly_dash/app/test/, didn’t match any of these. I have created an app cars_dashboard. settings.py: MIDDLEWARE = [ 'django_plotly_dash.middleware.BaseMiddleware' ] INSTALLED_APPS = [ 'django_plotly_dash.apps.DjangoPlotlyDashConfig', 'channels', 'channels_redis', 'cars_dashboard' ] CRISPY_THEME_PACK = 'bootstrap4' ASGI_APPLICATION = 'cars_dashboard.routing.application' PLOTLY_DASH = { 'stateless_loader': 'cars_dashboard.dash_app.cars_dashboard', 'cache_arguments': False, 'serve locally': False } CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [ ('127.0.0.1', 6379), ], }, }, } STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django_plotly_dash.finders.DashAssetFinder', 'django_plotly_dash.finders.DashComponentFinder', 'django_plotly_dash.finders.DashAppDirectoryFinder', ] PLOTLY_COMPONENTS = [ 'dash_core_components', 'dash_html_components', 'dash_bootstrap_components', 'dash_renderer', 'dpd_components', 'dpd_static_support', ] main website's urls.py: urlpatterns = [ path('django_plotly_dash/', include('django_plotly_dash.urls')), path('cars_dashboard/', include('cars_dashboard.urls')), ] cars_dashboard views.py import django_plotly_dash from django.shortcuts import render, HttpResponse def home(request): return render(request, 'cars_dashboard.html') cars_dashboard urls.py from django.urls import path from . import views from .dash_app import cars_dashboard urlpatterns = [ path('', views.home, name='home'), ] The third line in the above code import the cars_dashboard.py script which contains the code for dashboard … -
Django Unit Test Login and Registration
I'm new with Django. I would like to write a unit test to test login (and possibly registration) but after several attempts I'm not sure where to start. Would you have any suggestions on how I could write these tests? Another question is: would be in this case BDD the best choice (with Behave) or should I remain for unit-test here? Thanks Code for the view.py: from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse from django.contrib.auth import login,logout,authenticate from labs.models import Category from .forms import createuserform def index(request): categories = Category.objects.all() context = { 'categories':categories, } return render(request, 'landing/index.html', context) def registerPage(request): if request.user.is_authenticated: return redirect('/labs') else: form=createuserform() if request.method=='POST': form=createuserform(request.POST) if form.is_valid() : user=form.save() return redirect('/login') context={ 'form':form, } return render(request,'landing/register.html',context) def loginPage(request): if request.user.is_authenticated: return redirect('/labs') else: if request.method=="POST": username=request.POST.get('username') password=request.POST.get('password') user=authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect('/') context={} return render(request,'landing/login.html',context) def logoutPage(request): logout(request) return redirect('/') -
Regex in django query is throwing InterfaceError: (-1, 'error totally whack')
Query1: Model.objects.filter(slug__istartswith="dfe") This is working fine in the shell. while Query2: Model.objects.filter(slug__regex="^dfe") This is throwing Error, InterfaceError: (-1, 'error totally whack') What could be the issue? -
Django , unable to get URL parameter from GET request
I have a class that accept user input and returns the filtered database class SearchView(ListView): model = Post ... ... def get_queryset(self): qs = self.model.objects.all() state = self.request.GET.get('state') print (state ) return qs When passing url, it supposed to print the state data from URL, but its not. -
django-celery-beat spams due tasks
I'm using django-celery-beat for some hourly/daily tasks. However, strange behaviour made me clueless what to do. I'm creating a task using this piece of code: periodic_task = apps.get_model('django_celery_beat', 'PeriodicTask') interval_schedule = apps.get_model('django_celery_beat', 'IntervalSchedule') schedule, _ = interval_schedule.objects.get_or_create(every=2, period='hours') periodic_task.objects.update_or_create( task=TASK, defaults={'name': 'Check missing documents', 'interval': schedule}, ) where TASK is a string pointing to this task: @app.task(ignore_result=True) def task(): <things to do> pass In the code you see that I use an interval of 2 hours, and once I started the beat with celery -A [project-name] beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler, no error pops up (I don't know if it actually works, 2 hours is a lot of time). However, when I change the interval to 1 hour, it spams these: [2021-12-21 15:32:45,333: INFO/MainProcess] Task app.tasks.task[6c0343b0-faf1-4eae-a8e0-721c862120a9] succeeded in 0.0s: None [2021-12-21 15:32:45,336: INFO/MainProcess] Scheduler: Sending due task <task description> (app.tasks.task) and then it continues to eternity, only stoppable with Ctrl+C. I do have the RabbitMQ Management plugin installed, and from the UI everyting looks fine - no queue, nothing unacked, etc. Any clue what this could cause? Even after purging the queue, it still happens (with celery -A [project-name] purge). -
django signal wont work after adding a save function
I have a simple model like this: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) info1 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) info2 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) info3 = models.CharField(max_length=64, choices=SURVEY_CHOICES, blank=True) is_interviewed = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.info1: self.is_interviewed = 'True' super(ScientificInfo, self).save(*args, **kwargs) Every time a user is added to the app, a ScientificInfo object will be created for it using this signal: @receiver(post_save, sender=User, dispatch_uid='save_new_user_survey') def survey_create(sender, instance, created, **kwargs): user = instance if created: survey = ScientificInfo(user=user) survey.save() everything worked fine until I added that save method inside my model. the method works but the signal is disabled. Can you guys help me? thanks -
Annotation inside an annotation in Django Subquery?
I've got a few models and am trying to speed up the page where I list out users. The issue is that I was leveraging model methods to display some of the data - but when I listed the Users out it was hitting the DB multiple times per User which ended up with hundreds of extra queries (thousands when there were thousands of User objects in the list) so it was a serious performance hit. I've since began using annotate and prefetch_related which has cut the queries down significantly. I've just got one bit I can't figure out how to annotate. I have a model method (on Summation model) I use to get a summary of Evaluation data for a user like this: def evaluations_summary(self): evaluations_summary = ( self.evaluation_set.all() .values("evaluation_type__name") .annotate(Count("evaluation_type")) ) return evaluations_summary I'm trying to figure out how to annotate that particular query on a User object. So the relationship looks like this User has multiple Summations, but only one is ever 'active', which is the one we display in the User list. Each Summation has multiple Evaluations - the summary of which we're trying to show as well. Here is a summary of the relevant parts … -
How to bootstrap style ModelFormset
I've have a view that uses the formset factory but I'm trying to style the rendered html form. But the usual styling for forms doesn't work and im not sure what i need to do to apply the CSS stytles. My View def get_questionnaire(request, project_id, questionnaire_id): # Get the Response object for the parameters response = Response.objects.get( project_name_id=project_id, questionnaire_id=questionnaire_id ) AnswerFormSet = modelformset_factory(Answer, fields=('answer',), extra=0) answer_queryset = Answer.objects.filter(response=response ).order_by('question__sequence' ).select_related('question') if request.method == 'POST': # to be completed pass else: # Get the list of questions for which no Answer exists new_answers = Question.objects.filter( questionnaire__response=response ).exclude( answer__response=response ) # This is safe to execute every time. If all answers exist, nothing happens for new_answer in new_answers: Answer(question=new_answer, response=response).save() answer_formset = AnswerFormSet(queryset=answer_queryset) return render(request, 'pages/formset.html', {'formset': answer_formset}) for the moment im just trying to style a single field by applying the widgets in forms.py. But this isn't working. class answer_formset(ModelForm): class Meta: model = Answer fields = ('answer',) widgets = { 'answer': forms.Select(attrs={'class': 'form-select'}), } HTML {{ formset.management_form }} {% for form in formset %} {{ form.id }} {{ form.instance.question.question }} {{ form.answer }} <br> {% endfor %} Thanks -
How to show 10 product in django template by using _set(reverse lookup class)?
{% for item in i.product_set.all %} <div class="col-md-6 col-sm-6 col-xs-12 isotope-item {{ i|lower }} mb-5"> <div class="menu-list"> <span class="menu-list-product"> <img width="80" height="80" src="{{ item.image.url }}" alt=""> </span> <h5>{{ item.name }} <span>৳ {% if item.discount %} {{ item.price|sub:item.discount }} {% else %} {{ item.price }} {%endif%}</span></h5> <p>{{ item.description|truncatewords:6 }}</p> </div> </div> {% endfor %} Above code show all product but I want to show last 10. -
Django: It takes a long time to filter the m2m model from the m2m-connected model by specifying the field values of the m2m model
The m2m through table has about 1.4 million rows. The slowdown is probably due to the large number of rows, but I'm sure I'm writing the queryset correctly. What do you think is the cause? It will take about 400-1000ms. If you do filter by pk instead of name, it will not be that slow. # models.py class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000) preview_url = models.URLField(max_length=1000, blank=True, null=True) embed_url = models.URLField(max_length=1000) sources = models.ManyToManyField(Source) duration = models.CharField(max_length=6) tags = models.ManyToManyField(Tag, blank=True, db_index=True) views = models.PositiveIntegerField(default=0, db_index=True) is_public = models.BooleanField(default=True) published_at = models.DateTimeField(default=timezone.now, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Video.objects.filter(tags__name='word').only('id').order_by('-published_at'); Query issued SELECT "videos_video"."id" FROM "videos_video" INNER JOIN "videos_video_tags" ON ("videos_video"."id" = "videos_video_tags"."video_id") INNER JOIN "videos_tag" ON ("videos_video_tags"."tag_id" = "videos_tag"."id") WHERE "videos_tag"."name" = 'word' ORDER BY "videos_video"."published_at" DESC; EXPLAIN(ANALYZE, VERBOSE, BUFFERS) QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Sort (cost=4225.63..4226.23 rows=241 width=24) (actual time=456.321..473.827 rows=135178 loops=1) Output: videos_video.id, videos_video.published_at Sort Key: videos_video.published_at DESC Sort Method: external merge Disk: 4504kB Buffers: shared hit=540568 read=11368, temp read=563 written=566 -> Nested Loop (cost=20.45..4216.10 rows=241 width=24) (actual time=5.538..398.841 rows=135178 loops=1) Output: videos_video.id, videos_video.published_at Inner Unique: true Buffers: … -
Python Django ERROR: 'int' object has no attribute 'lr' [closed]
I am trying to build my Keras model using TensorFlow and Keras. code is following: This Django project is to find the predictive analysis of data. This project is running live. but I am going to run it locally for militance. An issue is found that, " 'int' object has no attribute 'lr', here 'lr' is the learning rate. Admin.py def build(self, request, queryset): count = 0 for p in queryset: if build_id(p.project_management.id): count += 1 else: messages.warning(request, f"Could not build model for {p}") messages.success( request, f"Successfully built models for {count} projects") build.short_description = "Build models for selected Projects" Build.py # build models for project with id project_id def build_id(project_id): # get directory path to store models in path = fetch_model_path(project_id, True) # train model model, scaler_in, scaler_out = train_project_models(project_id) # ensure model was trained if model is None: return False # store models store_model(f'{path}/model.pkl', model) store_model(f'{path}/scaler_in.pkl', scaler_in) store_model(f'{path}/scaler_out.pkl', scaler_out) # clear current loaded model from memory keras_clear() return True Utils.py # train models for project with id project_id def train_project_models(project_id): # get relevant data project, df = fetch_project_data(project_id) if project is None: return None, None, None # extract list parameters dense_shape = [int(x) for x in project.dense_shape.split(',')] lstm_shape = … -
Filtering in a many-to-many relationship in Django
I have three models, here I show two: class Product(models.Model): description = models.CharField(max_length=50) price = models.IntegerField() stock = models.IntegerField() def __str__(self): return self.description # Many-to-many relations class ProductsCategories(models.Model): idProduct = models.ForeignKey(Product, on_delete=CASCADE) idCategory = models.ForeignKey(Category, on_delete=CASCADE) How can I get in the views.py file products filtered by the category number 3 for instance? I have this: products_list = Product.objects.all() Thanks in advance. -
django-bootstrap-modal-forms saving instance twice (couldn't resolve with other issues open)
I am implementing a django-bootstrap-modal-forms 2.2.0 on my django app but I am having a problem. Every time I submit the modal form, the instance is created twice. I read that it is expected to have two post requests...the issue is that I am doing a few things on the form before saving it (adding a many to many value) and as I am trying to override the save function now it ends up saving the model twice. class DirectorModelForm(BSModalModelForm): class Meta: model = Contact exclude = ['owner', 'matching_user', 'id', 'referral', 'name_surname','title','city'] class NewDirectorView(BSModalCreateView): template_name = 'action/forms/DirectorModelForm.html' form_class = DirectorModelForm success_message = 'Success: Director was created.' success_url = reverse_lazy('action:new_jobproject') def get_object(self): pk = self.kwargs.get('pk') director = get_object_or_404(Contact, pk=pk) return director def form_valid(self, form): obj = form.save(commit=False) obj.owner = self.request.user obj.save() obj.title.add(Title.objects.get(title_name='Director', title_department='Production')) return super().form_valid(form) -
Expo Push Notification not Working on Heroku App (Back End)
Expo Push Notifications are working locally. I use Django on backend. But, once the app is deployed on Heroku server, Expo Push Notifications are not working, and I get an error. The code is breaking on backend, when communicating with Expo Backend Service (when calling https://exp.host/--/api/v2/push/send). -
Django Search returning the detailed view page
in models.py class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField(blank=True, null=True) in views.py def index(request): entry = Person.objects.all() context = {'entry':entry} return render(request, 'searching/index.html', context) def detail(request, pk): entry = Person.objects.get(id=pk) context = {'entry':entry} return render(request, 'searching/detail.html', context) in urls.py path('name/', views.index, name='index'), path('name/<str:pk>/', views.detail, name='detail'), I am stuck, i want to make a search bar where if you search the exact id, example my model has id of 1 if i search 1 in the box it should return mysite.com/name/1 instead of getting a page with results of queries that contain the 1 i want the exact one i searched for. I have looked so hard but i can't find a solution, it seems like a simple question and i feel so dumb. Is there an easy solution that i am missing? -
How to give tabs in django admin inline?
I am using django-baton and like to give tabs inside inline, but unable to give it Here is my code for admin.py and model.py file admin.py class ContentInLine(admin.StackedInline): model = Content extra = 1 class schoolProfileAdmin(admin.ModelAdmin): # exclude = ('content',) inlines = [ContentInLine] save_on_top = True list_display = ('school_name',) fieldsets = ( ('Main', { 'fields': ('school_name', ), 'classes': ('baton-tabs-init', 'baton-tab-group-fs-multi--inline-items', 'baton-tab-group-inline-things--fs-another', ), 'description': 'This is a description text' }), ('Multiple inlines + fields', { 'fields': ('email', ), 'classes': ('tab-fs-multi', ), }), ) models.py class SchoolProfile(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True) school_name = models.CharField(max_length=255) school_logo=models.FileField(upload_to='media/', blank=True) incharge_name = models.CharField(max_length=255, blank=True) email = models.EmailField(max_length=255, blank=True) phone_num = models.CharField(max_length=255, blank=True) num_of_alu = models.CharField(max_length=255, blank=True) num_of_student = models.CharField(max_length=255, blank=True) num_of_cal_student = models.CharField(max_length=255, blank=True) #content = models.ManyToManyField(Content, blank=True, related_name='groups') def __str__(self): a = Content.objects.all() for e in a: print(e.shows_name,'************************') return self.school_name class Content(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) content_type = models.CharField(max_length=255) # show=models.CharField(max_length=255) show=models.ForeignKey(Show,on_delete=models.CASCADE) sponsor_link=models.CharField(max_length=255) status=models.BooleanField(default=False) added_on=models.DateTimeField(null=True) content_file=models.FileField(upload_to='media/') title = models.CharField(max_length=255) shows_name = models.CharField(max_length=255) subtitle = models.CharField(max_length=255) description = models.CharField(max_length=500) publish_now = models.BooleanField(default=False) schedule_release = models.DateField(null=True) expiration = models.DateField(null=True) tag = models.ManyToManyField(Tag) topic = models.ManyToManyField(Topic) category = models.ManyToManyField(Category) school_profile = models.ForeignKey(SchoolProfile, on_delete=models.CASCADE,unique=True, blank=True) def __str__(self): return self.title Following is link for screenshot of admin page where i am unable to get …