Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Connection aborted.', ConnectionResetError 10054 error in django while trying to make a post request with files
I'm working on a django project for which I'm using an external API service. I have to send image files in the payload as well. When making a post request to the service, I'm getting this error: ConnectionError ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) Some key points are: The request works perfectly fine on Postman. The error appears only when I attach FILES in the payload, without which it works fine. -
Accessing the "many" side from the "one" side effectively
Considering the following models: class ManySide(django.db.models.Model): one_side = models.ForeignKey( to=OneSide, on_delete=models.PROTECT, related_name="related_one_side" ) class OneSide(django.db.models:model): # not containing any field relevant here def many_side_elements(self): pass # ? What should I include in method many_side_elements so that calling it from a OneSide Model instance would list a queryset of ManySide elements? Official docs imply that given o is a OneSide isntance, o.many_side_set.all() should work but it returns an error in shell. My current solution is the following: from django.apps import apps [...] def many_side_elements(self): ManySideModel = apps.get_model('<app_name_here>', 'ManySide') val = ManySideModel.objects.filter(one_side=self) But I'm concerned it's ineffective since it requires importing the other Model. Actually it caused a circular dependency error message in my project, hence the get_model usage. Is there any better way? Or xy_set should work in the first place? Then what am I doing wrong? -
No module named '_overlapped'
Working on a masters project and a fellow course mate has developed a web application using Django on a windows computer and has sent the file to us. I am trying to run the server on my MacBook terminal but when I run it, get the error "ModuleNotFoundError: No module named '_overlapped'. I have installed trollius as recommended in a previous post but hasn't worked for me. any help? -
The value I got from the jQuery is NoneType in django
I want to implement a function that updates the graph and displays the number of updates when the button is pressed. However, when I try to get the parameter in view.py using jQuery, it returns NoneType instead of the intended value. What is the problem? Also, I don't know if this is related, but when I use console.log() in a jQuery function, there is no output on the console of the browser developer tools. This doesn't seem to have anything to do with the error-only mode or the filter I entered in Console. The error is TypeError at /graph/update_graph int() argument must be a string, a bytes-like object or a number, not 'NoneType' Thank you. Here is the code views.py from xml.etree.ElementInclude import include from django.shortcuts import render from django.http import JsonResponse from . import graphdata def index(request): fig = graphdata.get_scatter_figure() plot_fig = fig.to_html(fig, include_plotlyjs=False) return render(request, 'graph/index.html', {'graph':plot_fig}) def update_graph(request): graph = graphdata.get_scatter_figure() grahp_html = graph.to_html(graph, include_plotlyjs=False) cnt = int(request.POST.get('count')) # <-- This is the error point cnt += 1 data = { "graph": grahp_html, "count": cnt, } return JsonResponse(data) index.html <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <!-- plotly JS Files --> <script … -
Two forms, one view, one ONE-TO-MANY relationship, how to get the id, the FK - DJANGO
First of all, just a disclaimer, i'm only posting because none of the topics here on the stack helped me, not even the related suggestions when i named this topic... I'm new to django, I'm working on opening a support ticket, I've been struggling with this problem for two days.... Is it possible to assign a value to the field defined in model.py by view.py? My problem is having two model classes, two forms with one-to-many relationship, which are rendered on the same page and must be saved when clicking a button only My models: class Ticket(models.Model): objects = None user_id = models.ForeignKey(User, null=False, blank=False, on_delete=models.DO_NOTHING) created_at = models.DateTimeField('Created at', auto_now_add=True) class MessageTicket(models.Model): objects = None ticket_id = models.ForeignKey(Ticket, null=False, blank=True, on_delete=models.DO_NOTHING) status = models.CharField(default=TicketStatus.TO_DO) content = models.TextField(null=True, default='') The point here is that 'ticket_id' in the 'MessageTicket' class should receive the 'id' of the last 'Ticket' saved, but as both are saved at the same time I'm not able to pull the last 'id' of the 'ticket'. My view, where saved in the database: As I said above I went through some forums and tried some things (in second 'IF'), I didn't leave them here to keep the code … -
Login System from .net Framework c# and need to connect it with rest API django python
I have a database created by someone using C# .Netframework, and now I need to create API using django and connect this API to the same database. But I can't program the login part because I don't know how to compare PasswordHash. As I read, .netframework stores the salt and hash together as PasswordHash PasswordHash= salt + hash( salt + pass) I need help to know which part is salt and which is the hash. Example of PasswordHash from database AQAAAAEAACcQAAAAEDFUVYGRfWBcYsa6qzyOdvc0a96dIVdaDpMJEU9OojIf1KCsdZrTa2Dem5yLnuAU6A== -
Override translation file django
I'm actually coding a web app with django and just started to use django allauth to go a bit quicker in the creation of my user interface. I've successfully changed the design of the templates by adding the templates from their github repo to my project. But I wanted to do the same with the translation because I want my app to be in french. So I did the same : I added the "locale" folder to my project and edited some things in the .po files but no change happened. Does someone know what to do, like what more is needed to override the ancient traductions ? Thanks in advance. -
'tuple' object has no attribute '_meta' while implementing serializer
I am implementing serializers for my models. But I am getting this error while accessing the api endpoint saying "'tuple' object has no attribute '_meta'". Here are my models and serializers Models class WorkflowStep(models.Model): name = models.CharField(max_length=200) workflow = models.ForeignKey('WorkflowType', null=True, blank=True, related_name='workflow', on_delete=models.SET_NULL) allowed_statuses = models.ManyToManyField("WorkflowStepStatus", null=True, blank=True, related_name='status') active_status = models.ForeignKey('WorkflowStepStatus', null=True, blank=True, related_name='active_status', on_delete=models.SET_NULL) default_status = models.ForeignKey('WorkflowStepStatus', null=True, blank=True, related_name='default_status', on_delete=models.SET_NULL) should_recheck = models.BooleanField(null=True, blank=True) step_type = models.ForeignKey("WorkflowStepType", on_delete=models.SET_NULL, null=True, blank=True, related_name='step_type') trigger_on_new_version = models.BooleanField(null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.name + "_" + self.workflow.name class Prerequisite(models.Model): workflow_step = models.ForeignKey("WorkflowStep", null=True, blank=True, on_delete=models.CASCADE, related_name='workflow_step') pre_requisite_step = models.ForeignKey('WorkflowStep', null=True, blank=True, on_delete=models.SET_NULL, related_name='pre_requisite_step') pre_requisite_step_status = models.ManyToManyField("WorkflowStepStatus", null=True, blank=True, related_name='pre_requisite_step_status') id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) def __str__(self): return self.workflow_step.name + "_pre_req_" + self.workflow_step.workflow.name Serializers class WorkflowStepSerializer(serializers.ModelSerializer): workflow = WorkflowTypeSerializer(many=False) allowed_statuses = WorkflowStepStatusSerializer(many=True) active_status = WorkflowStepStatusSerializer(many=False) step_type = WorkflowStepTypeSerializer(many=False) prerequisite = serializers.SerializerMethodField() class Meta: model = WorkflowStep fields = '__all__' def get_prerequisite(self, obj): pre_requisites = obj.workflow_step.all() serializer = PrerequisiteSerializer(pre_requisites, many=True) return serializer.data class PrerequisiteSerializer(serializers.ModelSerializer): workflow_step = WorkflowStepSerializer(many=True) pre_requisite_step = WorkflowStepSerializer(many=True) pre_requisite_step_status = WorkflowStepStatusSerializer(many=True) class Meta: model = Prerequisite, fields = "__all__" Error AttributeError at /api/workflowsteps/ 'tuple' object has no attribute '_meta' Request Method: GET Request … -
select2 ajax not show list of option, shows only the first option - django
I'm trying to make my drop down list into a ajax response via select2(version 4.0.7), but it only shows the first option, and select it automatically! i want to be able to which one i want to select note : i tried alot of answers in stackoverflow, but none of them worked here is my view @login_required def return_ajax_guests(request): if request.is_ajax(): term = request.GET.get('term') all_guests = Vistor.objects.all().filter(full_name__icontains=term) return JsonResponse(list(all_guests.values('full_name','city__name','dob')),safe=False) and here is my templates $(document).ready(function () { $('#guestinfo-0').select2({ ajax: { url: '{% url "return_ajax_guests" %}', dataType: 'json', processResults: function (data) { console.log(data) return { results: $.map(data, function (item) { $('#guestinfo').append("<option value='"+item.full_name+"' selected>"+item.full_name+"</option>") $('#guestinfo').trigger('change'); return {full_name: item.full_name, city: item.city__name}; }) }; } }, minimumInputLength: 1 }); }); <div class="col-span-5 groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "info" %}</label> <select name="guestinfo-0" id="guestinfo-0" class="visitors w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white"> </select> </div> is there a way to achieve that please? thank you in advance .. -
GCP, Django problem connection refused when trying to connect to the server
My django project runns normally on localhost and on heroku also, but when I deployed it to google cloud platform I am getting this error: could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/cloudsql/<connection_name>/.s.PGSQL.5432"? The connection to the database in settings.py looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'database_name', 'USER': 'postgres', 'PASSWORD': "password", # production 'HOST': '/cloudsql/connection_name', 'PORT': '5432', } Additionally, my app.yaml looks like runtime: python37 handlers: - url: /static static_dir: static/ - url: /.* script: auto env_variables: DJANGO_SETTINGS_MODULE: fes_app.settings requirements.txt looks like this plus sqlparse==0.4.2 toml==0.10.2 uritemplate==4.1.1 urllib3==1.25.11 whitenoise==5.2.0 twilio==6.9.0 I have tried using the binary version of psycopg, also gave a role client sql to the service account in the cloud. **NOTE : ** I am using an app engine standard environment -
Django url dispetcher route by id
this is my views.py class UserAPI(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated,] serializer_class = UserSerializer def get_object(self): return self.request.user and this is my url.py path('V1/api/users/', UserAPI.as_view(), name='user'), when i enter id,mail,username and go to localhost/v1/api/users/1 want to open user's which id is 1. what is best solutions ? -
AttributeError at /profile/create 'ProfileCreate' object has no attribute 'errors'
I am working on a social media project and getting this error while creating any profile. Please help me through this. Below is code mentioned. view.py from multiprocessing import context from pickle import FALSE from django.shortcuts import render,redirect from django.views import View from .form import CreateUserForm, ProfileForm from .models import CustomUser, Profile from django.contrib import messages from django.contrib.auth import login,logout,authenticate from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView, UpdateView from django.views.generic.list import ListView from django.views.generic.detail import DetailView # Create your views here. def index(request): context = {} return render(request,'index.html',context) def registration(request): userform = CreateUserForm(request.POST) if request.method=='POST': if userform.is_valid(): userform.save(commit='FALSE') else: messages.error(request,'An Error Occured!!') Users = CustomUser.objects.all() context = {'User': Users, 'form': CreateUserForm } return render (request,'registration.html',context) def log_in(request): 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('home') else: messages.info(request,'Username or Password is incorrect') context = {} return render(request,'login.html',context) @login_required def log_out(request): logout(request) messages.info(request, "Logged out successfully!") return redirect('index') @login_required def home(request): return render(request,'home.html') class ProfileCreate(CreateView): def get_queryset(self): return Profile.objects.all() fields = [ 'image', 'first_name', 'last_name' ] template_name = 'profile.html' success_url = "/home" def form_valid(self, form): print(form.cleaned_data) ProfileForm.save(self) return super().form_valid(ProfileForm) class ProfileDetailView(DetailView): model = Profile template_name = "profileview.html" … -
django choicefield Select a valid choice
I'm trying to submit my modelform with ajax loaded info of my other models. For the ChoiceField of my modelform I got this error; Select a valid choice. 69 is not one of the available choices. the request.POST seems well. I got all my fields properly. As my remind_object field is CharField already, I should be able to save ['69'] to there but I can't figure out why I got this error ? *** request.POST: <QueryDict: {'csrfmiddlewaretoken': ['dTtWIUKCOytmYVsbGf7StxMmd4ywPd0gzvvraAgrqiLuiUfLv3xo2TD1lv9Xpcxs'], 'topic': ['dsfdsfs'], 'remind_date': ['2022-02-22 13:45:59'], 'reminder_object_type': ['Client'], 'remind_object': ['69'], 'detail': ['<p>fdgfdgfd</p>\r\n'], 'submit_reminder_create_form': ['']}> models.py class Reminder(models.Model): user_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reminder_user') # user.reminder_user topic = models.CharField(max_length=100, blank=True, null=True) remind_date = models.DateTimeField(blank=True, null=True) reminder_object_type = models.CharField(max_length=100, blank=True, null=True) # Client # Contact # Action remind_object = models.CharField(max_length=999, blank=True, null=True) detail = RichTextField(max_length=999999,blank=True, null=True) reminder_status = models.CharField(max_length=100, default="Active", blank=True, null=True) slug = models.SlugField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.topic) def save(self, *args, **kwargs): self.slug = slugify(str(self.topic) + "-" + str(self.user_owner) + "-" + str(get_random_code())) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('reminder-detailview', kwargs={'slug': self.slug}) forms.py class ReminderModelForm(forms.ModelForm): class Meta: model = models.Reminder fields = ('reminder_object_type', 'topic', 'remind_date', 'remind_object', 'detail') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['reminder_object_type'] = forms.ChoiceField(required=True, label="", widget=forms.RadioSelect(attrs={'class': … -
Django 3.1 Field Level Permission
I have a User Form with 20+ Fields and 5 different user roles accessing the same form. Based on the Role, I need to set Field Level Permissions for the form. e.g User belonging to User Group 1 can create/edit/view all fields User belonging to User Group 2 can edit/view Fields 5, 6 and 7 only User belonging to User Group 3 can edit all fields but 9 and 10, view all Fields except 15 and 16. User belonging to User Group 4 can only view all fields but 9 and 11. So on and So forth. Any help with the same will be appreciated Thank you. -
Does Django come preconfigured for security out of the box?
Suppose I want to create a Django project for maintaining grocery lists. Each list contains multiple typical grocery items. The project has a simple REST API that is used to CRUD the lists and the items. Each list has an owner (user) so that any list can be accessed via the REST API only by the owner and no one else. If I was making this project, I would take these actions: Create a fresh Django project via the Django admin command tool. Create grocery list item models with fields for title, creation date, the owner and whether the item is ticked or not. Create views for the REST API. The views would check if the user that wants to perform an action on a model (grocery list or item) via the API is the same the owner of the model that the action is performed on. If the users are the same then the view performs the action on the model else it responds with a permission error. Do some other routine tasks such as migrating and etc. What other security affecting configurations would I need to change so that the project woks according to my naive and intuitive … -
Minimize the repeated queries in Django ORM
I want to minimize this query I've tried prefetch_related('rating', 'feedback') and select_related as well Here is my queryset code: queryset = Product.objects.select_related('product_brand', 'vendor', 'categories', 'warehouse', 'manufacturer').all() queryset = queryset.prefetch_related('available_area_pincodes').all() the feedback_feedback query is due to following field on Product: rating = models.DecimalField(default=0, null=True, blank=True, decimal_places=1, max_digits=8) And inside save method I'm using this: self.rating = self.reviews.aggregate(Avg('rating'))['rating__avg'] -
Caching in Django4
hello friends i am use Dajngo4 and for cache i use "django.core.cache.backends.redis.RedisCache" that does not use "django-redis" .it is my first project with Django4 and i have 2 command that i can not use without django-redis but i need it or alternative for it can everyone help me to find the appropriate command ? i want appropriate command for from django.core.cache import cache cache.ttl("example_key"), cache.expire("example_key",timeout=0), -
Looking For Tips Regarding Custom Website Builder?
I hope you all are well.So, I want to create custom a website builder with Django or Frappe or React,Node,Express or Laravel, from any of this platform then which is better for me and how can i create it any suggestion please? -
Django: Is it possible for a session dict to return more than one value for a key?
In my project, I store the serial number of the device that logs in it's session. However in the code that gets the value from the session: SESSION_SERIAL_NUMBER = 'terminal_serial_number' user._serial_number = request.session.get(SESSION_SERIAL_NUMBER, '') Very occasionally throws an error. The part that baffles me is: get() returned more than one Session -- it returned more than 20! How can a dict return more than one result, I don't know how to debug that? Heres the error: Internal Server Error: /accounts/login/ ProgrammingError at /accounts/login/ no results to fetch Traceback (most recent call last): File "/home/company/.venv/project/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 180, in _get_session return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "/home/company/.venv/project/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "./dist/terminals/middleware.py", line 11, in __call__ user._serial_number = request.session.get(SESSION_SERIAL_NUMBER, '') File "/home/company/.venv/project/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 65, in get return self._session.get(key, default) File "/home/company/.venv/project/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 185, in _get_session self._session_cache = self.load() File "/home/company/.venv/project/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 43, in load s = self._get_session_from_db() File "/home/company/.venv/project/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 32, in _get_session_from_db return self.model.objects.get( File "/home/company/.venv/project/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/company/.venv/project/lib/python3.8/site-packages/django/db/models/query.py", line 443, in get raise self.model.MultipleObjectsReturned( During handling of the above exception (get() returned more than one Session -- … -
Django runserver performance of functions that do not make requests
I have found plenty of questions on here that address the performance of runserver, but all of those were with regards to the performance of requests and responses. My question is about performance of methods of a class that are executed from views. I am quite new to Django, so forgive me for mistakes in general Django practices and let's try to focus on my question. Simplified for sake of clarity, my current project looks like this: search ├── manage.py ├── retrieval │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── retrieval_execution │ │ └── retrieval_execution.py │ ├── urls.py │ └── views.py ├── core │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── test.py In retrieval_execution.py, I have the following methods that are being executed through views.py: def delta_decoder(self, delta_encoded_inverted_list): """ input params: v_byte_encoded_inverted_list : dictionary one key being the word, and values a list with delta encoded doc_id and decoded positions return: inverted list in its original format {word: [document_count, [[doc_number, [positions]]]} """ doc_count, delta_pos_combos = delta_encoded_inverted_list # int, list list_out = [doc_count, {}] # add the first doc number manually current_doc_num, positions = delta_pos_combos[0] # int, list list_out[1][current_doc_num] = … -
DJANGO Compress on production
Im struggling with django compressor on production. When i have DEBUG = True all is working and in output from python manage.py compress --force i have succesfully compressed 4 blocks (as expected): Compressed 4 block(s) from 14 template(s) for 1 context(s). When I set DEBUG = False the output looks like this: Compressed 0 block(s) from 14 template(s) for 1 context(s). I configured COMPRESS_ENABLED = True and COMPRESS_OFFLINE = True but It looks like not working. My settings.py configuration for django_compress: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django_user_agents", # Third Party Packages "compressor", .... ] 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", "booqly.error_handler.ErrorHandlerMiddleware", "django_user_agents.middleware.UserAgentMiddleware", ] CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.MemcachedCache", "LOCATION": "127.0.0.1:11211", } } STATIC_URL = "/static/" STATIC_ROOT = "staticfiles" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "booqly/static"), os.path.join(BASE_DIR, "app/static"), ] STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.AppDirectoriesFinder", "django.contrib.staticfiles.finders.FileSystemFinder", "compressor.finders.CompressorFinder", ) # Compressor and minifier config COMPRESS_ENABLED = True COMPRESS_OFFLINE = True COMPRESS_CSS_HASHING_METHOD = "content" COMPRESS_FILTERS = { "css": [ "compressor.filters.css_default.CssAbsoluteFilter", "compressor.filters.cssmin.rCSSMinFilter", ], "js": [ "compressor.filters.jsmin.JSMinFilter", ], } HTML_MINIFY = True KEEP_COMMENTS_ON_MINIFYING = True I have {% compress %} tags only in index.html and homepage.html. When I run manage.py compress --force --verbosity 2 in trace i see that … -
Accessing nested ids in Queryset Django Rest Framework
how can i access the category_id? I want to create a list of similar products based on category. So each time i make a get request f.e products/1052/similarproducts, i want to get all the ProductsInStore of the same category as ProductInStore(id=1052) and exclude the ProductInStore(id=1052), my current code gives me "ecommerce.models.ProductInStore.DoesNotExist: ProductInStore matching query does not exist." Even though a productInStore of 1052 exists. class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=200) product_category = models.ManyToManyField(EcommerceProductCategory) class SimilarProductsListApiView(generics.ListAPIView): queryset = ProductInStore.objects.all() serializer_class = ProductInStoreSerializer #products/954/similarproductsr def get_queryset(self): product_id = self.kwargs['pk'] category = ProductInStore.objects.values_list('product__product_category', flat=True).get(product_id=product_id) return ProductInStore.objects.filter(product__product_category=category).exclude(product_id=product_id).all() -
Django multiple choice field, form.save() overwrites all values resetting previous entries rather than adding new ones
I have a form which is intended to add a number of sections to a project. I am using a CheckboxSelectMultiple with a list of choices restricted to only those that have not previously been selected. So with a new empty project with no sections: Project.sections.all() = null choices = [(1, 'a'),(2, 'b'),(3, 'c')] First time the form is submitted, adding sections a & b. Project.sections.all() = a, b choices = [(3, 'c')] Second time the form is submitted, adding section c. Project.sections.all() = c choices = [(1, 'a'),(2, 'b')] What I instead want is for c to be added onto the existing list of values for the project. models.py class Project(models.Model): number = models.CharField(max_length=4, unique=True) name = models.CharField(max_length=100) sections = models.ManyToManyField(Section) class Section(models.Model): code = models.CharField(max_length=2) description = models.CharField(max_length=50) views.py def add_section(request, project_number): project = Project.objects.get(number=project_number) full_section_list = Section.objects.all() project_assigned_sections = project.sections.all().values_list('id', flat=True) choices = list(full_section_list.exclude(pk__in=project_assigned_sections).values_list('id', 'code')) if request.method == 'POST': form = AddSectionForm(choices, request.POST, instance=project) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("project-page", args=(project_number))) else: print("invalid") else: form = AddSectionForm(choices, instance=project) return render(request, "app/add_section.html", { "project": project, "form": form, "choices": choices }) forms.py class AddSectionForm(forms.ModelForm): def __init__(self, choices, *args, **kwargs): super(AddSectionForm, self).__init__(*args, **kwargs) self.fields['sections'] = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, required=False, choices=choices ) class … -
django hide whole section when there is no result
I have a search bar with autocomplete functionality in my Django app that is displaying results based on user input. I connected this search bar to 3 models. Code below: search_items.html {% block body %} <section class="py-3 model-1"> <h2>Model 1</h2> <hr> <div class="row"> {% for qa in qa_list %} <div class="mb-3">{% include 'components/model_1_search.html' %}</div> {% empty %} <div class="align-items-center pt-4 mt-4"> <img class="img-fluid mx-auto d-block" src="{% static 'text no results.svg' %}"> </div> {% endfor %} </div> </section> <section class="py-3 model-2"> <h2>Model 2</h2> <hr> <div class="row"> {% for article in article_list %} <div class="mb-3">{% include 'components/model_2_search.html' %}</div> {% empty %} <div class="align-items-center pt-4 mt-4"> <img class="img-fluid mx-auto d-block" src="{% static 'text no results.svg' %}"> </div> {% endfor %} </div> </section> <section class="py-3 model-3"> <h2>Model 3</h2> <hr> <div class="row"> {% for video in video_list %} <div class="mb-3">{% include 'components/model_3_search.html' %}</div> {% empty %} <div class="align-items-center pt-4 mt-4"> <img class="img-fluid mx-auto d-block" src="{% static 'text no results.svg' %}"> </div> {% endfor %} </div> </section> <hr> views.py @login_required def search_address_qa(request): query = request.GET.get('title') payload = [] if query: lookups = Q(title__icontains=query) address_objects = Article.objects.filter(lookups, status=1).distinct() address_objects_qa = QA.objects.filter(lookups, status=1).distinct() for address_object in address_objects or address_objects_qa: payload.append(address_object.title) return JsonResponse({'status':200, 'data': payload}) @login_required def search_items(request): query … -
How to deploy Django 3.2 App in AWS EBS with a Python VENV
I've written a Django application and I want to deploy it to Amazon's Elastic Beanstalk. To deploy it, I use the following command: eb create bizkaimove-server-2-env But it fails when it comes to deploy it, here: (cfn-init-cmd.log) 2022-02-18 09:36:33,838 P3272 [INFO] Command pip_upgrade 2022-02-18 09:36:33,841 P3272 [INFO] -----------------------Command Output----------------------- 2022-02-18 09:36:33,841 P3272 [INFO] /bin/sh: /opt/python/run/venv/bin/pip: No such file or directory 2022-02-18 09:36:33,841 P3272 [INFO] ------------------------------------------------------------ 2022-02-18 09:36:33,842 P3272 [ERROR] Exited with error code 127 I've created a virtual environment to run it locally, but I don't know whether this venv is run within the EBS. But it seems it's. To sum up, my app is written using Django 3.2, Python 3.9 and it depends on a PostgreSQL database (remote, not embedded) and GDAL installation. My folder structure is the following: bizkaimove_server |- .ebsextensions |- 00-django.config |- 01-gdal.config |- 02-upgrade_pip.config |- 03-install_dependencies.config |- 04-django-contrab.config |- .elasticbeanstalk |- config.yml |- env_bizkaimove (python virtual environment folder) |- requirements.txt The content of the files are: 00-django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: bizkaimove_server.wsgi:application 01-gdal.config commands: 01_install_gdal: test: "[ ! -d /usr/local/gdal ]" command: "/tmp/gdal_install.sh" files: "/tmp/gdal_install.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash sudo yum-config-manager --enable epel sudo yum -y install make automake gcc …