Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django class based view, how to return when using django_filter
I am using class based view because I employed django_filter. I also utilize django_tables2. When rendering request after POST I return the context. I figured out how to add table to it, but can't find a way to return pagination or my filter. I can simply redirect to the same page, but it just doesn't feel right. class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 2 filterset_class = ZamowienieFilter def post(self, request, *args, **kwargs): table = self.table_class(Zamowienie.objects.all()) filterset_class = self.filterset_class(ZamowienieFilter) if request.POST.get('zatwierdz_zam'): pk_zn_zamowienie = request.POST["zatwierdz_zam"] Zamowienie.objects.filter(pk=pk_zn_zamowienie).update(zam_status=1) elif request.POST.get('anuluj_zam'): pk_zn_zamowienie = request.POST["anuluj_zam"] Zamowienie.objects.filter(pk=pk_zn_zamowienie).update(zam_status=0) context = {'table': table, 'filterset_class': filterset_class, 'paginate_by': 2} return render(request, self.template_name, context) -
Django Error NoReverseMatch at /invest/(?P1\d+)/
So I am trying to update a value in django. But when clicking on submit it is throwing me a error. NoReverseMatch at /invest/(?P1\d+)/ Reverse for 'invest' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['invest/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/$'] I am calling invest page from brand.html page in this manner <a href="{% url 'invest' pk=marking.id %}";><button type="button" class="btn btn-primary" data-toggle="modal" >Invest</button></a> I am passing the value properly in my html code <script> $(document).on('submit', '#post-form',function(e){ // console.log("Amount="+$('input[name="amount"]').val()); e.preventDefault(); // getting the value entered amount = $('input[name="amount"]').val(); product_title = $('input[name="product_title"]').val(); console.log("Product title="+product_title); console.log("Amount entered by user="+amount); $.ajax({ type:'POST', url:"{% url 'invest' pk=context.id %}", data:{ product_title: product_title, amount: amount, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function(xhr, errmsg, err){ window.location = "brand" }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); console.log(xhr.status + ": " + xhr.responseText); } }); }); </script> urls.py path('invest/(?P<pk>\d+)/', views.invest, name='invest'), views.py def invest(request, pk): # fetching the current event details event_data = MarketingMaestro.objects.get(pk = pk) context = { 'id' : event_data.id, 'product_title' : event_data.product_title, 'total_value' : event_data.total_value, 'total_votes' : event_data.total_votes, } # fetching user details user_data = MarketingInvesment.objects.get(emailID = request.user.email) user_details = { 'name' : user_data.name, 'emailID' … -
Offline django web application with high level of encryption for database
The task: Build an application that manages important documents for internal use only. No internet involves. My solution: Build a django web application that uses sqlite. My question: Is django applicaiton a good choice for this task? How do I encrypt the database, so that hacker cannot use a simple SQLite browser to read the content of the database? Thank you! -
Django crispy forms helper
i installed crispy using pipenv install django-crispy-forms {% load crispy_forms_tags %} works perfectly but when i try to import crispy_forms.helper like below from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit its says Unable to import 'crispy_forms.helper'pylint(import-error) i use Python 3.9.2, and Django 3.1.7 and crispy 1.11.1 i tried install a fresh crispy-forms but still the same problem -
Django Messages not showing in generic view
I am trying to show a flash message in a django app (Django 3.1), but having difficult time figuring out how: My settings are as follows: MIDDLEWARE = [ # other middleware 'django.contrib.messages.middleware.MessageMiddleware', # Even more middleware ] MESSAGE_TAGS = { messages.DEBUG: 'alert-secondary', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } Then my generic view is as follows: class AppIndex(generic.ListView): model = User, template_name = 'users/index.html' def get(self, request, *args, **kwargs): messages.success(request, "Test users flash message") return super().get(request, *args, **kwargs) My index.html looks like this: {% include 'users/_messages.html' %} <table> {#List of users here...#} </table> The _messages.html partial file looks like this: {% if messages %} {% for message in messages %} <div container-fluid> <div> {{message }} </div> </div> {% endfor %} {% endif %} But this doesnt seem to work in any way. Any help will be greatly appeciated. -
How can I make my twilio code send sms when I sent a product to a customer?
I have a django shop application and I want to send sms using twilio when I sent product to a customer and changed something in the database(for example: changed something to true). So where can I do it to make it work? I am using django + postgresql + gunicorn + nginx + twilio Any suggestions will be appreciated -
Jquery in django : Uncaught TypeError: Cannot read property 'createDocumentFragment' of null
For the life of me I can't figure out what's wrong with this code. It used to work in an earlier version and after I rearranged the javascript at the bottom of the page it just won't work properly. It keeps giving me this error: The row where it throws the error is the following: $('.formset_row').formset({ And this is the jquery plugin that i used. This used to work perfectly until like yesterday when i probably touched something i shouldnt have. <!-- Select2 JS --> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <!-- Semantic UI --> <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> <!-- Select2 JS --> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <script src="/static/js/script.js"></script> <script> /*$('body').on('focus',".my-date-picker", function(){ $('.my-date-picker').datetimepicker({ format: 'DD/MM/YYYY', ignoreReadonly: true, showTodayButton: true }); });*/ </script> <script src="/static/formset/jquery.formset.js"></script> <script type="text/javascript"> $('.formset_row').formset({ addText: '<div style="color: #34C6AA;" class="my-2 text-center"><span class="oi oi-plus"></span> Add Education</div>', deleteText: '<div style="color: #f4816e; text-decoration: none;" class="my-2 text-center"> <span class="oi oi-x"></span> Remove Education</div> ', prefix: 'educations' }); </script> </body> -
Testing Django views when using django-allauth
I'm using django-allauth for authentication on my site. All my views use LoginRequiredMixin. I'm wanting to simply test that a view loads as expected but I can't seem to correctly login. from django.test import Client password = 'test1234' username = 'test' user = get_user_model().objects.create(username=username, email='test@test.com') user.set_password(password) user.save() client = Client() client.force_login(user) But when I test that I'm able to load the home page, I get redirected back to the login page. Any help would be super appreciated -
Django AppConfig Ready Error: Models aren't loaded yet
I'm trying to run a pubsub function will running in background all the time. In AppConfig i use ready(self) function to start that function and it's running all the time. In that function i call class GetPubSubMessages(Process): and inside of it in def run(self): i run that pubsub listener function. Problem is ,in that listener function i can't use any model or view (error :django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.). I tried to get model in appconfig's ready function but i couldn't pass it as a param to procces class and use it in func. Is there any way that i can include apps then use it in function ? -
Filtering modified at by hour
I was trying to get the number of insurance claims by Day and what time it occurred. For Example, it is March 22 today and there were claims on 8 am another in 12noon. I was trying to get all the claim count this day and what hour did the claims occured. I did try using modified_at__hour but it doesn't show what I needed. Sample code for claims per week and show what day it was claimed class GetClaimsCompare_week(APIView): def get_claim_count(self, claims_data, claim_type): claims_count = claims_data.filter(claim_type = claim_type).count() return claims_count def get_claims_type(self, claims_per_day): return claims_per_day.claim_type #return claims_data.claim_type def get(self, request): today = datetime.now() claims_data = Claims.objects.filter(modified_at__day = today.day) claims_per_day = claims_data.annotate(day = TruncDay('modified_at')).values('day').annotate(claim_type=Count('id')) labels = [] claims_type = list(set(map(self.get_claims_type, claims_data))) final = {} for claims in claims_per_day: labels.append(claims['day']) #data.append(claims['claims']) for claim_type in claims_type: final[claim_type] = self.get_claim_count(claims_data, claim_type) context = { 'Date(s)': labels, 'Claims on this date': final } return Response(context) -
How to optimize access to reverse ForeignKey?
I have models: class ModelA(models.Model): name = models.CharField(max_length=200) class ModelB(models.Model): model_a = models.ForeignKey( ModelA, on_delete=models.CASCADE, related_name="model_bs" ) is_main = models.BooleanField(default=False) I want to make request that returns all ModelA-s, including its main ModelB. Like: [ { "name": "foo", "model_b": { "is_main": true } }, { "name": "bar", "model_b": null } ] I can achieve this with SerializerModelMethod: class ModelASerializer(serializers.ModelSerializer): model_b = serializers.SerializerMethodField() class Meta: model = ModelA def get_model_b(self, obj): model_b = obj.model_bs.filter(is_main=True).first() return ModelBSerializer(model_b).data But it entails an "n+1" problem with DB. It will make additional query on every ModelA. And prefetch_related on model_bs won't help. How to optimize it? -
Django_filters changing label, how to figure out default filter type
I am using django_filter, displaying it in my own way in template. I want to edit label of one of the filters. To do that I need to provide filter type. It works great in default but I can't figure out which filter type is used. This field in my model looks like this: class Zamowienie(models.Model): zam_kontrahent_fk = models.ForeignKey(Kontrahent, on_delete=models.CASCADE) On template it looks like typical select box. I figured out its not django_filters.ChoiceFilter but django_filters.ModelChoiceFilter. I tried using its queryset option but it only displays list of primary_keys (1 instead of 'name' field from the table foreign_key is) class ZamowienieFilter(django_filters.FilterSet): zam_status = django_filters.ModelChoiceFilter(label='Status', queryset=Zamowienie.objects.order_by('zam_kontrahent_fk').values_list('zam_kontrahent_fk', flat=True).distinct()) class Meta: model = Zamowienie fields = [ 'zam_kontrahent_fk', ] Is it correct way to handle that? I didn't find a way to log default filter behaviour, it would help a lot, simply copying this fragment. Any idea how to display values, not list of primary_keys? -
How to prevent upload the file on submit the form
I uploading the file in django with progress bar, and when i choose the file the progress start and when the finish that's mean the file uploaded but when I click in submit form the file upload again and this mean the progress bar is useless, so I want to make something like when I click in submit button the file save with the form but not upload again how I can do this? my form class Video_form(forms.ModelForm,): class Meta: model = Video fields = ('video', 'video_poster', 'title',) the view def VideosUploadView(request, *args, **kwargs): V_form = Video_form() video_added = False if not request.user.is_active: # any error you want return render('account/login.html') try: account = Account.objects.get(username=request.user.username) except: # any error you want return HttpResponse('User does not exits.') if 'submit_v_form' in request.POST: print(request.POST) V_form = Video_form(request.POST, request.FILES) if V_form.is_valid(): instance = V_form.save(commit=False) video = request.FILES['video'] clip = VideoFileClip(video.temporary_file_path()) instance.video_duration = clip.duration instance.author = account instance.save() V_form.save_m2m() V_form = Video_form() video_added = True if instance.save: return redirect('home') contex = { 'account': account, 'V_form': V_form, 'video_added': video_added, } return render(request, "video/upload_videos.html", contex) the template <form id="upload-form" action="." method="post" enctype="multipart/form-data"> {% csrf_token %} <div id="progress-box" class="d-none">progress</div> <div class="custom-file"> <input type="file" class="custom-file-input" id="formGroupExampleInput2" required value="{{V_form.video}}"> <label class="custom-file-label" … -
Django 500 Internal server error when authenticating against Django’s user database from Apache
I have two web pages on the same server, for each webpage I have created a VirtualHost in Apache. In order to access webpage A (not django) I have to log in previously using the user database from Apache. When I access webpage B (django) I also have to log in, but by default django takes care of it so I don't need to care about it. To achieve that, I have installed mod_wsgi for authentication following Django's documentation My 000-default.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined LogLevel info WSGIDaemonProcess wikimedia python-path=/home/ubuntu/django_app python-home=/home/ubuntu/django_app/django_app WSGIProcessGroup wikimedia WSGIScriptAlias / /home/ubuntu/django_app/django_app/wsgi.py <Location "/"> AuthType Basic AuthName "Top Secret" Require valid-user AuthBasicProvider wsgi WSGIAuthUserScript /home/ubuntu/django_app/django_app/wsgi.py </Location> </VirtualHost> <VirtualHost *:80> ServerAdmin webmaster@example.com ServerName ec2-52-194-22-185.ap-northeast-1.compute.amazonaws.com DocumentRoot /home/ubuntu/django_app ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django_app/static <Directory /home/ubuntu/django_app/static> Require all granted </Directory> <Directory /home/ubuntu/django_app/django_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_app python-path=/home/ubuntu/django_app python-home=/home/ubuntu/django_app/django_app WSGIProcessGroup django_app WSGIScriptAlias / /home/ubuntu/django_app/django_app/wsgi.py </VirtualHost> wsgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_app.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() And this is the apache error.log: Mon Mar 22 07:13:29.386595 2021] [mpm_event:notice] [pid 36906:tid 140284783721536] AH00491: caught SIGTERM, shutting down [Mon Mar 22 07:13:29.480317 2021] [mpm_event:notice] [pid 37031:tid 140582871116864] … -
Django Post save signal gives error save() missing 1 required positional argument: 'self'
I have been working on following model class Member(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE) refer_code = models.CharField( max_length=20, unique=True, blank=True, null=True ) and the refer_code was set to be automatically generated when save method is called i.e during creation (not during update) here is my clean method and save method. def clean(self): if not self.user.is_member: raise DjangoValidationError({'user': _('User must member')}) def save(self, *args, **kwargs): if self._state.adding: self.refer_code = self.user.username super(Member, self).save(*args, **kwargs) post_save.connect(save, sender=User) I followed certain tutorials on youtube but got following error save() missing 1 required positional argument: 'self' I want post_save signal to be triggered during creation so I tried created = True but got error. Any help will be useful. -
PUT/PATCH method not updating the response but changes taking place in the database in DRF
I am working on an API using Django REST framework. In my case, I am using nested serializers so I am required to overwrite the .update method. Here's the required desc: Serializers Config Serializer class DeviceConfigSerializer(serializers.ModelSerializer): config = serializers.JSONField() context = serializers.JSONField() class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] Device Detail Serializer class DeviceDetailSerializer(serializers.ModelSerializer): config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device fields = [ 'id', 'name', 'organization', 'mac_address', 'key', 'last_ip', 'management_ip', 'model', 'os', 'system', 'notes', 'config', ] def update(self, instance, validated_data): config_data = None if self.data['config'] is None and validated_data.get('config'): config_data_ = dict(validated_data.get('config')) config_templates = config_data_.pop('templates') config = Config.objects.create(device=instance, **config_data_) for template in config_templates: config.templates.add(template.pk) if validated_data.get('config'): config_data = validated_data.pop('config') # When config data is provided with PATCH requests if config_data: instance.config.backend = config_data.get( 'backend', instance.config.backend ) instance.config.status = config_data.get('status', instance.config.status) config_templates = config_data.get('templates') instance.config.templates.clear() for template in config_templates: instance.config.templates.add(template.pk) instance.config.context = json.loads( json.dumps(config_data.get('context')), object_pairs_hook=collections.OrderedDict, ) instance.config.config = json.loads( json.dumps(config_data.get('config')), object_pairs_hook=collections.OrderedDict, ) instance.config.save() return super().update(instance, validated_data) Device Detail Views class DeviceDetailView(RetrieveUpdateDestroyAPIView): serializer_class = DeviceDetailSerializer queryset = Device.objects.all() Now when I Send a PUT/PATCH request to its endpoint, It works fine and the fields in the database get updated, but since after the PUT/PATCH request … -
DJANGO password reset link
Hey , please i want to send an email with custom reset link in django in case the user click the reset button in the login page. **ps :** iam hosting my app on aws and i'm using my email to send . -
How to use django-autocomplete-light on django-countries==7.1 country fields for admin panel
I want the To country field for the admin field as per My Model.py File. how to use it. settings.py file:- INSTALLED_APPS = [ 'dal', 'dal_select2', # 'grappelli', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admission', 'employment', 'form', 'frontend', 'study', 'travel', 'hrm', 'event', 'dal_queryset_sequence', ] Model.py file:- from django.db import models from django_countries.fields import CountryField class University (models.Model): ESTABLISHED_YEAR_CHOICES = [(x, str(x)) for x in range(1088, 2021, 1)] university_logo = models.ImageField(upload_to='pics', verbose_name="University Logo") university_name = models.CharField(max_length=255, verbose_name="Name") university_rank = models.IntegerField(verbose_name="Rank", default="0") university_country = CountryField() international_students = models.IntegerField( blank=True, null=True, verbose_name="International Students") established_year = models.IntegerField( choices=ESTABLISHED_YEAR_CHOICES, blank=True, null=True, verbose_name="Established Year") total_students = models.IntegerField(blank=True, null=True, verbose_name="University Total Student") university_website= models.CharField(max_length=255, blank=True, null=True, default="https://www", verbose_name="University Website") university_address= models.CharField(max_length=255, blank=True, null=True, verbose_name="University Address") def __str__(self): return self.university_name class Meta: verbose_name = 'Top University' verbose_name_plural = 'Top Universitys' -
Error: [Win Error 10049] The requested address is not valid in its context
I am new to using Nginx. I am trying to host my Django application on Ngnix so that I can expose APIs defined in views.py so that they are accessible from other server. But I am getting above error while starting Django application. site specific .conf file: server { listen 8004; charset utf-8; client_max_body_size 10M; location / { proxy_pass http://10.11.12.34 } } nginx.conf file: worker_processes 10; error_log logs/error.log; events { worker connections 1024; } http { include mime.types; include '../../.conf' #included path to site-specific .conf file access_log logs/access.log; sendfile on; keepalive_timeout 65; } Added new file Django runserver.py: (code snippet) if __name__ == '__main__': serve(application, host = 10.11.12.34, port 8004) What must be causing this error? Also, I am not sure what IP address to be used there? how to decide which IP address to be configured? Can someone help me with this? -
MultipleObjectsReturned at /ordered-list/
Please help to solve this problem. I have an issue with MultipleObjectsReturned at / ordered-list / get() returned more than one Order -- it returned 2! This is the problem I want to display all the items in the database based on the field "disiapkan"=False order = Order.objects.get(user=self.request.user, disiapkan=False) View.py class OrderedListView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, disiapkan=False) context = { 'order' : order } return render(self.request, 'ordered_list.html', context) except ObjectDoesNotExist: return redirect('beranda') models.py class Order(models.Model): id_order = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) address = models.ForeignKey("Address", on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey("Payment", on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey("Coupon", on_delete=models.SET_NULL, blank=True, null=True) ordered = models.BooleanField(default=False) disiapkan = models.BooleanField(default=False) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total def get_total_after_coupon(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() if self.coupon: total -= self.coupon.amount return total urls.py from django.urls import path from .views import ( HomeView, CheckoutView, ProductDetail, add_to_cart, add_to_cart2, PaymentView, CouponView, remove_from_cart, OrderSummaryView, remove_perUnit_from_cart, ordersummary2, OrderedListView, OrderedListDikirimView, OrderedListDiterimaView, remove_coupon, ) urlpatterns = [ path('beranda', HomeView.as_view(), name='beranda'), path('checkout/', CheckoutView.as_view(), name='checkout'), path('add-coupon', CouponView.as_view(), name='add_coupon'), path('payment/<payment_option>/', PaymentView.as_view(), name='payment'), path('product/<slug>/', ProductDetail.as_view(), name='product'), … -
Get the values of a Polymorphic model and pass it to different serializers
ModelA(PolymorphicModel) ModelB(ModelA) ModelC(ModelA) ModelD(BaseModel) items = models.ManyToManyField(ModelA) def get_items(self): return self.items.all() Now I have to get the list of all the models under the polymorphic through ModelD. serializers.py class ModelDSerializer(serializers.ModelSerializer): items = serializers.SerializerMethodField() class Meta: model = models.ModelD fields = "__all__" def get_items(self, obj): // obj.get_items() Now I have to pass the items to the different serializers. Like, if the item is a ModelB, then I will pass it to ModelBSerializer. If it is a ModelC I will send it to ModelBSerializer. How can I execute this? -
Raising a ValidationError of a Date in Django
I want to raise a validation error in my form. If date is invalid, raise my own message instead of Django's default message. Here is my form.: def clean_birth_date(self, *args, **kwargs): birth_date = self.cleaned_data.get("birth_date") date_valid = False birth_date = str(birth_date) year = birth_date[0:4] month = birth_date[5:7] day = birth_date[8:10] # Check if birth_date is a proper date birth_date = year.zfill(4) + month.zfill(2) + day.zfill(2) print("TEST") try: birth_date = datetime.strptime(birth_date, '%Y%m%d') date_valid = True except ValueError: date_valid = False if not date_valid: print("TEST") raise forms.ValidationError("Something Message Here.") return birth_date If the date is valid, I can see the TEST in my terminal. That means my clean function works(I think). However, if invalid like 123, or Feb 30, I can't see the TEST in terminal and django returns its default message. If you have an idea, please let me know. -
How can I fix styles.css:1 Failed to load resource: the server responded with a status of 404?
i am trying to learn django and my css file cant be linked with the html file idk why ├── images ├── js ├── plugins └── styles └── styles.css This is the tree of the static folder STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] settings.py file ^^ <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>BMI Calculator</title> {% load static %} <link rel="stylesheet" href="{% static './styles/styles.css' %}"> </head> <!-- <script src="../data/script-clac.js" type="text/javascript"></script> --> <body class="body1"> <div class="div1"> <h2>BMI Calculator</h2> <p class="text">Name</p> <input type="text" placeholder="Enter your name" id="name"> <p class="text">Username</p> <input type="text" placeholder="Choose a username" id="username"> <p class="text">Password</p> <input type="password" placeholder="Choose a password" id="password"> <p id="result"></p> <input type="checkbox" onclick="myFunction()">Show Password <button id="btn" onClick="BMI()">Calculate</button> </div> </body> </html> index.html file styles.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) Error in the page console I have been trying to fix the problem since a long time, please help me. -
(1048, "Column 'brand_id' cannot be null") in django rest framework
I am trying to create an api where a user can add their products. I am sending raw json data from postman but it is giving this error. IntegrityError at /api/addproducts (1048, "Column 'brand_id' cannot be null") I am sending brand id in the data. I am not sure what is happening. Here I am sending merchant_id as well as categories ids but why brand field is creating an error I am not sure. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Brand(models.Model): brand_category = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Brands" def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Collections" def __str__(self): return self.name class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) product_id = models.CharField(max_length=70,default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity … -
How to show the progress bar when submitting the form in javascript-ajax
I have already made the brogress bar and everything. But I have problem when I choose the file the file is upload, that's mean the file is uploading twice, once when choosing the file and one once submit the form, and this bad user experince so I wan't show the brogress bar only when submmit the form, I using Django in backend and ajax recall my html form <div id="alert-box"></div> <form id="upload-form" action="." method="post" enctype="multipart/form-data"> {% csrf_token %} <div id="progress-box" class="d-none">progress</div> <div class="custom-file"> <input type="file" class="custom-file-input" id="formGroupExampleInput2" required value="{{V_form.video}}"> <label class="custom-file-label" for="formGroupExampleInput2">Choose Video...</label> </div> <div class="custom-file mt-5 mb-4"> <input type="file" class="custom-file-input" id="file2" required value="{{V_form.video_poster}}"> <label class="custom-file-label" for="formGroupExampleInput2">Choose Poster For Your Video...</label> </div> <div class="d-flex justify-content-center my-3 px-3" > <button class="btn-block btnn-color" id="heel" name="submit_v_form"> Upload</button></div> </form> the javacript-Ajax const file_input_label = document.getElementById('file_input_label') function input_filename(){ file_input_label.innerHTML = input.files[0].name; console.log(file_input_label); } const uploadForm = document.getElementById('upload-form') // const input = document.getElementById('formGroupExampleInput2') const input = document.getElementById('formGroupExampleInput2') console.log(input) const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const progressBox = document.getElementById('progress-box') const canceleBox = document.getElementById('cancel-box') const canceleBtn = document.getElementById('cancel-btn') const csrf = document.getElementsByName('csrfmiddlewaretoken') // whenever choose th file something happen input.addEventListener('change', ()=>{ progressBox.classList.remove('d-none') canceleBox.classList.remove('d-none') var filePath = input.value; var allowedTypes = /(\.mp4|\.mkv|\.avi|\.flv)$/i; if(!allowedTypes.exec(filePath)){ alertBox.innerHTML = `<div class="alert …