Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-crispy: error filed not displayed (but added to the DOM)
I use django-crispy for template rendrering my issue is that field error is not displayed even if added to the DOM input field is underlined with red <form id="id-form" method="post"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <div class="alert alert-danger mb-0" role="alert"> {{ error }} </div> {% endfor %} {% endif %} <br> {% crispy form %} </form> If I render my form fied by field, error message is displayed <form id="id-form" method="post"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <div class="alert alert-danger mb-0" role="alert"> {{ error }} </div> {% endfor %} {% endif %} <br> <div class="row mb-0"> <div class="input-group input-group-sm col-6"> <label>{{ form.inc_dat.label }}</label> </div> <div class="input-group input-group-sm mb-1 col-2"> {{ form.inc_dat }} <div class="input-group-append"> <span class="input-group-text rounded-right" id="basic-addon2"><span data-feather="calendar"></span></span> </div> {% for error in form.inc_dat.errors %} <div class="invalid-feedback">{{ error }}</div> {% endfor %} </div> </div> </form> what is wrong with django-crispy? -
DRF: Using URL parameters to determine ordering on nested serializer fields
My question is whether there is a way to use filters given by the user in the URL to order a queryset using nested serializers using the nested fields. For example: class EventsSerializer(serializers.ModelSerializer): class Meta: model = Events fields = ['date', 'location'] class GuestsSerializer(serializers.ModelSerializer): events = EventsSerializer() class Meta: model = Events fields = ['name', 'phone', 'seat_no', 'events'] class GuestEvents(generics.ListAPIView): serializer_class = GuestsSerializer name_param = self.kwargs['name'] order_param = self.request.query_params.get('orderBy') def get_queryset(self): data = Guests.objects.select_related('events').filter(name=name_param) return data def list(self, request, *args, **kwargs): res = super(TestData, self).list(request, *args, **kwargs) res.data = {"guestevents":res.data} return res If i have these serializers and view in order to show what events a guest is attending and the ordering is by default ascending based on the date; is it possible to have the user type location as the orderType and have that be used for ordering or can i not make use of thee 'location' field at this point? -
Django Channels receive message from room group doesn't appear to be working
I am trying to build a notifications system using Django Channels. I completed the intial setup and when I run my server I get confirmation of Handshake and connection confirmed. However, when I view my console log, I cannot see the message to be sent. I also put a print statement on the send_notification function but it is never reached. I am new to using Django Channels so any help would be appreciated. What am I terribly doing wrong? Here is my ASGI file setup: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'clicksource.settings') from channels.auth import AuthMiddleware, AuthMiddlewareStack from notifications.routing import websocket_urlpatterns application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ) }) Here is my consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'notification_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from room group async def send_notification(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message':message })) Here is my routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/notification/(?P<room_name>\w+)/$', consumers.NotificationConsumer.as_asgi()), ] And the script in my … -
Adding fields from a many-to-many relationship to a Django Admin Inline
I am trying to set up a project where I have user, questions for the users, and then the answers that the users give. Here are my models. class User(models.Model): name = models.CharField(max_length=20) email = models.EmailField() def __str__(self): return self.name class Question(models.Model): question = models.TextField() def __str__(self): return self.question class Answer(models.Model): answer = models.TextField() user = models.ManyToManyField(User) question = models.ManyToManyField(Question) def __str__(self): return self.answer Then in the admin I would like to be able to click on a user and see their answers so I set my admin up like so. class AnswerInline(admin.TabularInline): model = Answer.user.through class UserAdmin(admin.ModelAdmin): list_display = ('name', 'email') inlines = [AnswerInline] class QuestionAdmin(admin.ModelAdmin): list_display = ('question',) class AnswerAdmin(admin.ModelAdmin): list_display = ('answer', ) fields = ('question', 'answer',) admin.site.register(User, UserAdmin) admin.site.register(Question, QuestionAdmin) admin.site.register(Answer, AnswerAdmin) However, when viewing users it only shows their answer. It doesn't show the question that answer is associated with. How do I add this information to the admin page in a way that makes sense. Preferably with the question first and then the answer to that question to the right of it. -
Bootstrap delete confirmation dialog
I am trying to Delete a record using bootstrap model in Djando while getting a confirmation. The Model view gets triggered and deletes the record but on success it points to the url pointing to the deleted record and it gives a 404 error. It seems it tries to post the request twice. I could not find resources on this to help me get around and also I am in learning phase so I am looking forward to expert advice on this. Thanks Delete button in the index.html against the record to delete. <button type="button" class="delete-task btn btn-sm btn-primary" data-id="{% url 'delete' task.pk %}"><span class="fa fa-trash"></span></button> Javascript in index.html $(".delete-task").each(function () { $(this).modalForm({formURL:$(this).data('id')}); }); Model.html: <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"></div> </div> </div> delete_task.html: {% load widget_tweaks %} <form method="POST" action=""> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title">Delete Task</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="delete-text">Are you sure you want to delete Task with title <strong>{{ task.title }}</strong>?</p> </div> <div class="modal-footer"> <button id="delete-task" type="submit" class="delete-task btn btn-danger" >Delete</button> </div> </form> View.py: class TaskDeleteView(BSModalDeleteView): model = Task template_name = 'delete_task.html' success_message = 'Deleted Successfully' def get_success_url(self): return reverse_lazy('index') Urls.py: path('delete/<str:pk>', … -
DRF upload extracted zip files
I'm going to upload some files through my DRF API. This API receives a .zip file that has some .xlsx files in, and I extract its content in the API view. Then I send this data to the serializer, But I get this error: [ { "file_name": [ "The submitted data was not a file. Check the encoding type on the form." ] } ] This is how I'm extracting my .zip file before passing data to the serializer: def _get_serializer_initial_data(self): with ZipFile(self.request.FILES.get('file_name')) as input_zip: return [ { 'file_name': input_zip.open(_input_excel) } for _input_excel in input_zip.infolist() ] Then I send data to the serializer this way: initial_data = self._get_serializer_initial_data() serializer = self.get_serializer(data=initial_data, many=True) I checked the extracted files type in the serializer class and it's ZipExtFile, which seems to be unacceptable by DRF. Any help would be appreciated. -
How to send notification before 30 days from expire date in django?
How i schedule notification for this program , i am using channels to create notification and use "crontab" for scheduling but it does't work............. please provide exact solution... def my_schedule_job(): vehicle_objs = Vehicle.objects.all() for vehicle_obj in vehicle_objs: insurance_expiry = vehicle_obj.insurance_expiry insurance_expiry_date = insurance_expiry - timedelta(days=5) today = date.today() print('insurance_expiry_date',insurance_expiry_date) print('today',today) if insurance_expiry_date == today: notification_obj = Notification(user_id=vehicle_obj.user_id,notification="Your insurance for {} will expire on {}".format(vehicle_obj.vehicle,insurance_expiry) ,is_seen=False) notification_obj.save() elif insurance_expiry_date <= today: notification_obj = Notification(user_id=vehicle_obj.user_id,notification=vehicle_obj.vehicle + " insurance is going to expire on " + str(insurance_expiry),is_seen=False) notification_obj.save() -
Python Azure SDK azure.mgmt.recoveryservices.operations VaultsOperations "VaultsOperations.__init__() missing required positional arguments' Error
I'm trying to get the list of RecoveryServiceVaults by resource group name using Azure SDK package for Python azure.mgmt.recoveryservices. . I coded as follows; from azure.identity import ClientSecretCredential from azure.mgmt.recoveryservices import RecoveryServicesClient from azure.mgmt.recoveryservices.operations import VaultsOperations subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"] tenant_id = os.environ["AZURE_TENANT_ID"] client_id = os.environ["AZURE_CLIENT_ID"] client_secret = os.environ["AZURE_CLIENT_SECRET"] credentials = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret) recovery_services_client = RecoveryServicesClient(credentials=credentials,subscription_id=subscription_id) vault=VaultsOperations(recovery_services_client) vaults_in_rg = vault.list_by_resource_group(rg_name) for vault in vaults_in_rg: print(vault) And the Error I got is; TypeError: VaultsOperations.__init__() missing 3 required positional arguments: 'config', 'serializer', and 'deserializer'. I don't know what variables I should provide to create VaultsOperations() class object. Could you give some guidance ? Does anyone know what kind of variable should be provided for object to be created? Any opinions is appreciated. Thanks in advance -
How build a category model after building legacy model in Django REST Framework
Hello, I have a question about improving legacy models. The Material model is old model, and i want to make category by using new model 'type'. But i have a little problem with when i use admin site. In admin site, i hope to choose the 'type' first, and upload data .. how can i make better models # new model class MaterialType(BaseModel): type = models.CharField(choices=MaterialTypeChoice.choices, max_length=50, null=True, blank=True) def __str__(self): return self.type # old model class Material(models.Model): type = models.ForeignKey(MaterialType, verbose_name=, null=True, blank=True, on_delete=models.SET_NULL) name = models.CharField max_length=50, null=True, blank=True) size = models.CharField(max_length=50, null=True, blank=True) unit = models.CharField(max_length=5, null=True, blank=True) price_unit = models.IntegerField(null=True, blank=True) def __str__(self): return self.name serializers # new class MaterialTypeListSerializer(serializers.ModelSerializer): class Meta: model = MaterialType fields = ["type"] # old class MaterialListSerializer(serializers.ModelSerializer): class Meta: model = Material fields = ["id", "type", "name", "size", "unit", "price_unit"] views # new class MaterialTypeList(ListCreateAPIView): queryset = MaterialType.objects.all() serializer_class = MaterialTypeListSerializer # old class MaterialList(ListAPIView): queryset = Material.objects.all() filter_class = MaterialFilter serializer_class = MaterialListSerializer admin @admin.register(Material) class MaterialAdmin(ImportExportModelAdmin): list_display = ["name", "size", "unit", "price_unit"] list_display_links = ("name",) list_filter = ("type",) list_per_page = 10 # list_editable = ('type',) search_fields = ("name", "size") resource_class = MaterialResource @admin.register(MaterialType) class MaterialTypeAdmin(ImportExportModelAdmin): list_display = ["type"] list_filter … -
Render all products that relate to one of subcategories of one category, in category page
I had a question. I am creating an ecommerce website in django. There, I have categories and subcategories. When I enter to subcategory page, I able to render all products that relate to this subcategory. But, when I wanted to render all product that relate on one parent category, I am having troubles. So, I have some subcategories in one category. In that category page, I want to render all products that relate to one of subcategories of this category. Can you help me please? models.py class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) image = models.ImageField(null=True, blank=True, verbose_name="Изображение") ordering = models.IntegerField(default=0) is_featured = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Categories' ordering = ('ordering',) def __str__(self): if self.parent is not None: return f"{self.parent}/{self.title}" return self.title @property def imageURL(self): try: url = self.image.url except: url = '' return url def get_absolute_url(self): return '/%s/' % (self.slug) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) parent = models.ForeignKey('self', related_name='variants', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=200, verbose_name="Название продукта") price = models.IntegerField(verbose_name="Цена") slug = models.SlugField(max_length=255) description = models.CharField(max_length=5000,blank=True, verbose_name="Описание:") image = models.ImageField(null=True, blank=True, verbose_name="Изображение") novinki = models.BooleanField(default=False, verbose_name="Новинки") popularnye = models.BooleanField(default=False, verbose_name="Популарные") def __str__(self): return self.name class Meta: verbose_name = … -
How to securely generate random passwords in Django?
I have imported a set of user data into a Django project. Now I need to set a random password for each of them. My question here is, how do I securely generate random passwords in Django? -
The view didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view
I am building a django app following this article(ERROR: Your view return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view) Here is my code: import asyncio This is the add view async def save_setting(request): return HttpResponse('ok') Run command: uvicorn config.asgi:application --reload When I tried above code, it says "The view views.save_setting didn't return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an 'await' into your view." -
Django XML file upload API not getting called and [error]: method not allowed
I am working on Django project that will upload XML file via rest API and i am facing issue and not sure what it is ! i am sharing my Codes that i have written for Different Modules for [API] URL.py path('xml-file/', xmlfileview.as_view(), name='xml-file') Serializers.py class xmlfileSerializer(serializers.ModelSerializer): file = serializers.FileField() class Meta: model = xmlColumns fields = ['inputfile'] Views.py class xmlfileview(generics.CreateAPIView): serializer_class = xmlfileSerializer # parser_classes = (FileUploadParser,) def post(self, request, *args, **kwargs): token = request.META.get('HTTP_AUTHORIZATION') try: # payload = jwt.decode(token, settings.SECRET_KEY) # payload is a dictionary to decode the token to get the user id user = User.objects.get(id=payload['user_id']) # user is a function to get the user model if user.is_verified: print(user) # serializer = self.get_serializer(data=request.data) # serializer.is_valid(raise_exception=True) # serializer.save() # file = serializer.validated_data['file'] # print(file) file_obj = request.data['file'] df = pd.read_xml(file_obj) for col in df.columns: print(col) # print(df) return Response({'msg': 'file sent'}, status=status.HTTP_400_BAD_REQUEST) except jwt.ExpiredSignatureError as identifier: return Response({'error': 'Activation Expired'}, status=status.HTTP_400_BAD_REQUEST) except jwt.exceptions.DecodeError as identifier: return Response({'error': 'Invalid token'}, status=status.HTTP_400_BAD_REQUEST) Models.py class xmlColumns(models.Model): ipfile = models.FileField() -
How can I Send a additional value to views with form django?
I have an HTML form: <form action="" method="POST" enctype="multipart/form-data" onsubmit="update_button()"> {% csrf_token %} {{ form|crispy }} <div class="row" style="background-color: white"> {% for x in data %} <div style="padding: 10px;"> <label id="label1" class="{% for selectedIMG in selectedimages %}{% if selectedIMG == x.image_d %} image-checkbox-checked{% endif %} {% endfor %} image-checkbox {{x.image}}"> <img su-media-id="{{ x.image }}" height="100px" width="100px" src="/media-images/{{x.image}}" class="image-checkbox-checked" /> <i class="fa fa-check"></i> </label> </div> {% endfor %} <div class="clearfix"></div> </div> <br> <div class="form-group"> <div class="col-md-6 offset-md-3"> <input type='submit' class="btn btn-primary btn-block" /> </div> </div> </form> and a script that is making an array of the selected image and making a POST request to view: function update_button() { alert(mediaArray) $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") }, }); $.ajax({ type:"POST", url: "{% url 'ajax-post' %}", data: {"image":String(mediaArray)}, }); } The form also and ajax also make a post request when ajax requests going then the form is being empty and when the form request going then the image (mediArray) coming empty line from I am fetching data from ajax: images = request.GET.getlist('image') I want to pass both (form & media array to view) -
cannot import name 'InvalidAlgorithmError' from 'jwt'
I'm trying to use JWT Authentication with Django Rest Framework(DRF) but I'm getting this error on trying to generate token and refresh token with 'POST' request along with user credentials on /api/token page Error : my settings.py file: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig', 'rest_framework', 'rest_framework_simplejwt', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } my urls.py file: from django.urls import path from . import views from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('api/', views.getRoutes), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] my requirements.txt file: asgiref==3.5.0 backports.zoneinfo==0.2.1 Django==4.0.3 djangorestframework==3.13.1 djangorestframework-simplejwt==4.8.0 PyJWT==2.3.0 pytz==2021.3 sqlparse==0.4.2 tzdata==2021.5 I also tried to work this out with '5.1.0' and '5.0.0' versions of djangorestframework-simplejwt but no use I followed this documentation link: https://django-rest-framework-simplejwt.readthedocs.io/en/stable/getting_started.html# -
Get post() function from the view function returned by resolve()
I defined a class based on rest_framework.views.APIView and added it as a view to some url. For example like: from rest_framework.views import APIView from rest_framework.response import Response from django.urls import path class MyApi(APIView): def post(self, request): # Do something with the request print(request.data) return Response(status=200) path('my-url', MyApi.as_view()) In another file, I want to access the post() function of that class, but I only know the url. So I use the django.urls.resolve() function to get the view function. from django.urls import resolve view, args, kwargs = resolve(url) However, I don't want to obtain the view function, but the underlying post() function that I defined in the API-Class. Is there any option to get that function while only knowing the url? I want to avoid building a lookup for every possible url. -
DRF Nested Serializer field not appearing
I'm trying to retrieve some data from two related models however i am unable (or would like to avoid to be more precise) to change the models. The problem is that the nested serializer doesn't return the data of the first model. I have the following serializers class NameSerializer(serializers.ModelSerializer): class Meta: model = Microcontrollers fields = ['name'] class DataCUTSerializer(QueryFieldsMixin, serializers.ModelSerializer): stationName = NameSerializer(read_only=True) class Meta: model = MeasurementsBasic fields = ['stationName', 'temp', 'hum'] def to_representation(self, instance): representation = super().to_representation(instance) return {'timestamp': instance.time_taken, **representation} return representation These serializers use the following models class MeasurementsBasic(models.Model): microcontroller = models.OneToOneField('Microcontrollers', related_name='measurements_basic', primary_key=True, on_delete=models.CASCADE) time_taken = models.DateTimeField() time_received = models.DateTimeField(blank=True, null=True) frame = models.IntegerField(blank=True, null=True) temp = models.FloatField(blank=True, null=True) hum = models.FloatField(blank=True, null=True) pres = models.FloatField(blank=True, null=True) co = models.FloatField(blank=True, null=True) no2 = models.FloatField(blank=True, null=True) o3 = models.FloatField(blank=True, null=True) so2 = models.FloatField(blank=True, null=True) latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True) altitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True) name = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = True db_table = 'measurements_basic' unique_together = (('microcontroller', 'time_taken'),) class Microcontrollers(models.Model): name = models.CharField(max_length=25) serial_number = models.CharField(max_length=20, blank=True, null=True) type = models.CharField(max_length=15, blank=True, null=True) software = models.CharField(max_length=20, blank=True, null=True) version = models.CharField(max_length=5, blank=True, null=True) date_installed = … -
Overriding restore method in Django
I would like to run a piece of code after object is restored in Django but not have it run every time save() is runed. How can I override restoration method in Django? I know it is using save() method, but I would rather have it seperate from it. Is there any way? Or if I were to use the save() method, is there a way to determine if the request is from restoration page? -
Celery workers not working with RabbitMQ after upgrade
Problem description I have a working django application using Celery along with Mongo and RMQ (3.7.17-management-alpine) The application runs on kubernetes cluster The application works fine in general But when I upgrade Celery (3.1.25) and Kombu (3.0.37) to Celery (4.1.0) and Kombu (4.1.0), I face following issue: Celery worker pods come up but do not receive the tasks I have verified that RMQ receives the messages needed to run tasks in celery workers There is no error in RMQ or celery worker pod In fact, celery pod mentions that it is connected to RMQ Strangely, when I restart the RMQ pod after Celery worker pod comes up things become fine I am able to run the new tasks in celery workers after I restart RMQ pod So I guess something happened wrt Celery/Kombu/RMQ after upgrade to 4.1.0 The code works fine with older version of Celery and Kombu. Can someone please help me wrt this? -
How to call a Django function from template and save return in a variable
Context: I have a piece of HTML that I want to dispaly in the template just in case a function return "true". Details: My function def show_avg_kpi(): return config.avg_times_visible register.filter('show_avg_kpi', show_avg_kpi) Template ( is the piece of code to display or not): {% if show_avg_kpi %} <HTML CODE> {% endif %} I want something like this, but I don't know how to save the result of the show_avg_kpi function in a variable to use it with the {% if %} tags Thank you in advance. -
Check In System by input user data in Django
I trying to do a Check In System where Students can do it themselves by input their ID's but I am really struggling. Follow views, models, forms and html VIEW class Attendance(CreateView): template_name = 'homepage.html' model = GetAttendance fields = ['aluno'] success_msg = "Check In Succesfully" def form_valid(self, form): form.save() success_msg = self.get_success_message(form.cleaned_data) if success_msg: messages.success(self.request, success_msg) return super().form_valid(form) def get_success_url(self): return reverse('attendance:homepage') def get_success_message(self, cleaned_data): return self.success_msg % cleaned_data MODELS class Aluno(models.Model): id = ShortUUIDField(primary_key=True, editable=False, alphabet="0123456789", length=5) photo = models.ImageField(upload_to='photos/', default='static/images/defaultuser.jpeg', blank=True) nome = models.CharField(max_length=255) phone = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True) location = models.ForeignKey(MasterUser, on_delete=models.CASCADE) belt = models.CharField(max_length=255, choices=BELT) stripe = models.CharField(max_length=255, choices=GRAU) join_date = models.DateField(default=timezone.now) last_graduation = models.DateField(default=timezone.now) gender = models.CharField(max_length=255, choices=GENDER) def __str__(self): return self.nome class GetAttendance(models.Model): aluno = models.ForeignKey(Aluno, on_delete=models.CASCADE) attendance = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.aluno) + ' - ' + str(self.attendance) That's views.py My models.py forms html check in page Basically what I need is instead having a choices form be able to input the student ID and run the model GetAttendance. -
Can't reach this page took too long to respond. Django, Gunicorn and Nginx. This is until I reboot my instance manually
I hosted my Django website on AWS Lightsail instance on an Ubuntu server with Nginx and Gunicorn. Everything works fine when it is running super fast everything works great, but sometimes it stops running, I can't reach the website only until I restart my lightsail instance manually. This I think happens in the interval of 24 hours (probably). I don't know why it is happening? what causing it? Someone suggested to me that it's something related to the server itself, Server goes to sleep, or something but when any request comes it can't respond to that. If there is anything that you want to see to get more info plz comment I'll add that. I don't have much idea about this problem, I'll appreciate your help. -
How to send kwargs for form MultipleChoiceField in POST view unit test
I am struggling to find the answer for testing my POST view with data. I have a form that generates the the choices options on init and the issue in my test is that I am not passing the list_of_ids required to populate the choices for the form on init so I am getting an error of "12345 is not one of the available choices." This then means my repsonse code is returing 200 as my form is not valid and failing the test. I cant work out the right way to test this or how I would pass the choices to the form in the test. class AddAccountForm(forms.Form): account_id = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices = []) def __init__(self, *args, **kwargs): self.list_of_ids = kwargs.pop('list_of_ids') super(AddAccountForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_action = 'add_account_ids' self.fields['account_id'].choices = [(id['account_id'],id['account_id']) for id in self.list_of_ids] self.helper.layout = Layout( 'account_id', Submit('submit', 'Add', css_class='btn btn-primary btn-sm ml-2'), ) the list_of_ids is coming from and api call in my view: @login_required def add_account_ids(request): api_client = api_authentication(request.user) list_of_ids = get_list__ids(api_client) if request.method == "POST": form = AddAccountForm(request.POST, list_of_ids=list_of_ids) print(request.POST) if form.is_valid(): for id in form.cleaned_data['account_id']: LinkedAccount.objects.create( account_id=id, social_provider="api", user=request.user ) return HttpResponseRedirect('/') else: print('test') form = AddAccountForm(list_of_ids=list_of_ids) context = {'form' : … -
How to query data from two tables using django?
I have mySQL tables connected with "one to many" relationship params of the main table are: name age height params of the second table are: f_name (as foreign key of ) salary_date salary I already get data from first table using this code: models.py from tabnanny import verbose from django.db import models, connections from django.urls import reverse class collection_data(models.Model): name = models.CharField(max_length=50) age =models.IntegerField() height = models.IntegerField() class Meta: verbose_name = 'Collection Data' class second_data(models.Model): # connect this table with previos data = models.ForeignKey(collection_data, on_delete=models.CASCADE) salary= models.FloatField(max_length=100) salary_date= models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Frequent Collection Data' ordering = ['salary_date'] views.py from django.views.generic import DetailView class InfoDetailView(DetailView): model = collection_data template_name = 'info/Info.html' context_object_name = 'info' urls.py path('<int:pk>', views.InfoDetailView.as_view(), name="info-data"), Info.html <ul class="data"> <li>{{ info.name }}</li> <li>{{ info.age }}</li> <li>{{ info.height}}</li> </ul> <table> <tr> <th>Date</th> <th>Salary</th> </tr> {% for el in second_data %} <tr> <td>05/06/2021</td> <td>1350$</td> </tr> {% endfor %} </table> Result on the page must be: -
Django update or create - pre save
I am struggling with what may be a simple issue. I am trying to create a record or update if there is already an existing record in place. I am trying to override the models save function. The criteria is based on is there a user that already has an answer for their exp_type. I want ed to update it if so, if not then i want to create it. Here is what i have: class UserExperienceTypeAnswer(TimeStampedModel): NA, NONE, SOME, LOTS, EXPERT = range(5) ANSWER_CHOICES = { (NA, "Not interested"), (NONE, "None"), (SOME, "Some"), (LOTS, "Lots"), (EXPERT, "Expert"), } user = models.ForeignKey(User, models.CASCADE, null=False, blank=False) exp_type = models.ForeignKey( RecruitmentExperienceType, models.CASCADE, null=False, blank=False ) answer = models.PositiveSmallIntegerField( choices=ANSWER_CHOICES, default=NONE, blank=False, null=False ) unique_together = ["user", "exp_type"] def save(self, *args, **kwargs): record = UserExperienceTypeAnswer.objects.filter( user=self.user, exp_type=self.exp_type ).first() if not record: super(UserExperienceTypeAnswer, self).save(*args, **kwargs) else: //This is the part im unsure of. I tried to save the record from query above record.answer = self.answer super(UserExperienceTypeAnswer, record).save(*args, **kwargs) // This gives duplicate key error (which i assume is because its trying to create new record) // I also tried to create model directly but this creates recursion error (as i assume i am calling …