Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'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 … -
sidebar scroll down to section
I have a sidebar with a list of items where users can go to particular pages. What I'd like to do is to click on the element and scroll down to the section but it has to move to a section only when clicking on this button. The problem is that my a tag looks like this: <a href="{% url 'article_list' %}"> <li class="nav_list">go to section</li> </a> So I am not able to follow this pattern: <html> <body> <a id="top"></a> <!-- the entire document --> <a href="#top">Jump to top of page</a> </body> </html> Because as you can see a tag is already referring to article_list. I am using Django 3.2 and Bootstrap 5. Any advise on how this can be easly implemented will be appreciated. -
"KeyError: 'added' "when importing different lists of json
I'm getting a "KeyError: 'added'" Error when i try to import one of my three lists inside a json file. The list i'm trying to import is the one called "added". I had this working when it was just one list without the name "added" on top but now it seems like i can't access the list anymore. I want to individually import them basically. This is my code to get the Json parts before i import them into the database: class Command(BaseCommand): def import_facility_from_file(self, data): UUID = data.get('UUID', None) Name = data.get('Name', None) PrimaryAddress = data["AddressInfo"]["PrimaryAddress"] The new version of the Json File that im trying to use but thats causing the error: { "added": {"125hk24h5kjh43k5": { "UUID":"125hk24h5kjh43k5", "Name":"Test Facility 1", "AddressInfo": {"PrimaryAddress":"1234 Drive RD"}, "ImporterLastModifiedTimestamp":1643721420}}, "deleted":["235hk24h5kjh43k5,235hk345789h43k5"], "modified":{"995hk24h5kjh43k5": { "UUID":"995hk24h5kjh43k5", "Name":"Test Facility 2", "AddressInfo": {"PrimaryAddress":"2345 Test RD"}, "ImporterLastModifiedTimestamp":1643721420} } } The old version of the json file that worked perfectly with the code i intially wrote: {"00016ed7be4872a19d6e16afc98a7389b2bb324a2": {"UUID":"00016ed7be4872a19d6e1ed6f36b647f3eb41cadedd2130b103a5851caebc26fbbbf24c2f1a64d2cf34ac4e03aaa30309816f58c397e6afc98a7389b2bb324a2","Name":"Test Facility","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200", "AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0, "InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0}, "Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}, "00016ed7be4872a15435435435b2bb324a2": {"UUID":"000c93dcb7a0b3d5783bb330892aff6abdb9fb57a7d3701c2d903f3640877579f3173ecd8a80532f6c3d53dbacde78a6a54ae42fef321a5793f5a01934f8de7a","Name":"Test Facility 2","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200", "AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0, "InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0}, "Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}, "00234324324343243afc98a7389b2bb324a2": {"UUID":"fffd4dec10054e6e1deb2a2266a7c6bb0136ba46222e734ceed5855651f735cfbe0bb66cfaf27c3d175ae261a8f6df0c36b5390d15c70b07d67e35e1081aaf6d","Name":"Test Facility 3","IssuedNumber":"123456","Licensee":"Test Licensee","Email":"test@example.com","AdministratorName":"Test Name","TelephoneNumber":"(123) 456-7890324879","ImporterLastModifiedTimestamp":"1362985200", "AddressInfo":{"PrimaryAddress":"123 Fake Road","SecondaryAddress":"","City":"Testcity","RegionOrState":"TX","PostalCode":"12345","Geolocation":"00.0000,-00.0000"},"Capacity":100,"MostRecentLicenseTimestamp":1575180000,"ClosedTimestamp":0, "InspectionInfo":{"ComplaintRelatedVisits":0,"InspectionRelatedVisits":0,"NumberOfVisits":0,"LastVisitTimestamp":0}, "Complaints":{"ComplaintsTypeA":0,"ComplaintsTypeB":0,"SubstantiatedAllegations":0,"TotalAllegations":0}}} So i tried it like this to get … -
How to Set DateTimeFields in Django Models to None Value (If current time is greater than this fields)
Below is my codes class Job(models.Model): pin_till = models.DateTimeField("Pin Job Post", null=True,blank=True) Here i wanna auto setup pin_till_date field to None if date is not None and than pin_till_date < now(). How to archives this method ah? with @property function, signals or just define in save function? -
upstream timed out by django and nginx in docker-compose
I have docker-compose which has django and nginx version: "3.9" services: admin_site: build: context: ./ dockerfile: Dockerfile_django.local ports: - "8011:8011" restart: always command: uwsgi --http :8010 --module admin_site.wsgi nginx: image: nginx:latest container_name: nginx volumes: - ./nginx/conf:/etc/nginx/conf.d - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params - ./static:/static ports: - '81:80' depends_on: - admin_site After docker-compose up I can confirm that localhost:8011 works, so uwsgi works correctly. However when I access localhost:81 nginx | 2022/02/18 10:07:14 [error] 24#24: *4 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 172.18.0.1, server: dockerhost, request: "GET / HTTP/1.1", upstream: "uwsgi://172.18.0.2:8011", host: "localhost:81" nginx | 172.18.0.1 - - [18/Feb/2022:10:07:14 +0000] "GET / HTTP/1.1" 504 569 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36" "-" connection timeout occurs. Test: I log in the admin_site container and curl 172.18.0.2:8011 it response correctly. my nginx.conf file is here. upstream django { ip_hash; server admin_site:8011; } server { listen 80; server_name dockerhost; charset utf-8; location /static { alias /static; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; } } my nginx container log is here. Is there any place I need to check?? nginx | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration … -
How to catch IntegrityError with ManyToMany add() with wrong ids?
I have two models (just for example): class One(BaseModel): name = models.CharField() twos = models.ManyToManyField(Two) class Two(BaseModel): title = models.CharField() When I try to add a list of ids of model Two to model One with one.twos.add(*[id1, id2]) it works until I pass a wrong id, when this fails with psycopg2.errors.ForeignKeyViolation: insert or update on table "one_twos" violates foreign key constraint "one_two_id_572a5216_fk_twos" DETAIL: Key (two_id)=(e2871924-5bb4-492e-b7c3-4c5ca3cc7f5e) is not present in table "twos_two". django.db.utils.IntegrityError: insert or update on table "one_twos" violates foreign key constraint "one_two_id_572a5216_fk_twos" DETAIL: Key (two_id)=(e2871924-5bb4-492e-b7c3-4c5ca3cc7f5e) is not present in table "twos_two". This does not seem to be the race condition (mentioned here Django: IntegrityError during Many To Many add()). I need to tell the front-end that such-and-such id is not valid, but I can't catch these two IntergityErrors to re-raise my custom exception with a message and id. Would highly appreciate any help with this. -
Django template for loop is empty in another block
I have a function in my view.py: @login_required(login_url='login') def gpd(request,pk): # get gpd by id current_gpd = get_gpd(pk) # get current campaign year #TODO check types current_campaign = get_campaign(current_gpd.gpd_year) # get all corporate goals for current campaign corp_goals = CorporateGoal.objects.filter(gpd_year=current_campaign.year) compl_weight = [] for goal in corp_goals: compl_weight.append(goal.corp_factor_weight*current_gpd.bonus.corporate_component//100) corporate_goals = zip(corp_goals, compl_weight) if is_manager(request)!=None: team = get_team(request) context = {'gpd':current_gpd, 'corporate_goals':corporate_goals, } return render(request, 'app/gpd_forms/form_gpd.html', context) else: context = {'gpd':current_gpd, 'corporate_goal':corporate_goal, } return render(request, 'app/gpd_forms/form_gpd.html', context) As you can see, in context I have corporate_goal. My form_gpd.html: {% extends 'app/navbar/main.html' %} {% load static %} {% block content %} {% include 'app/slidebar/gpd_form_slidebar.html' %} <div class="container" style="background-color:white"> <div class="row"> <div id="section2" class="container-fluid"> {% include 'app/gpd_blocks/corporate_goal.html' %} </div> </div> <hr /> </div> <div class="container" style="background-color:white"> <div class="row"> <div id="section5" class="container-fluid"> {% include 'app/gpd_blocks/test.html' %} </div> </div> <hr /> </div> </div> {% endblock %} for example in corporate block I am executing next: {% load static %} {% block content %} <div class="row" id="super"> <p>&nbsp</p> </div> <div class="row" id="super"> <div class="col-11" style="color: ivory; font-weight: bold; font-size: 1.3em;"> CORPORATE GOALS BLOCK </div> </div> <div class="row" id="super"> <p>&nbsp</p> </div> {% for goal, compl_weight in corporate_goals %} <hr style="height:2px;border:none;color:rgb(87, 124, 161);background-color:rgb(87, 124, 161);" /> <!-- Corporate … -
Create Virtual Environment The system cannot find the path specified
I want to active venv in new folder , when i write "D:\pythonproject\first_django>env\Scripts\activate" in cmd I get " The system cannot find the path specified." also I installed venv , when I run this command "pip install virtualenv" in cmd get "Requirement already satisfied: virtualenv in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (20.13.0) Requirement already satisfied: filelock<4,>=3.2 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (3.4.2) Requirement already satisfied: distlib<1,>=0.3.1 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (0.3.4) Requirement already satisfied: six<2,>=1.9.0 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (1.16.0) Requirement already satisfied: platformdirs<3,>=2 in c:\users\sam\appdata\local\programs\python\python310\lib\site-packages (from virtualenv) (2.4.1)" can any one tell me what's problem? I use win11 and python 3.10