Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cannot submit formset in django
I have a formset which takes two select values and I can add or remove formsets with the help of jquery. I am able to submit the formset and I can see the post request in the server output but I am unable to save the formset in the DB. There are no errors or exceptions raised by the debug output also. Can you please look at the following and find the problem? views.py def ActivityCreateView(request): ActivityFormSet = modelformset_factory(Activity, form=ActivityForm, extra=2) if request.method == "POST": formset = ActivityFormSet(request.POST) if formset.is_valid(): instances = formset.save(commit=False) for form in instances: form.instance.department = request.user.facultyusers.department form.instance.branch = request.user.facultyusers.branch form.instance.author = request.user.facultyusers.user form.instance.yearandmonth = request.session["yearandmonth"] form.instance.approved = False form.instance.freezed = False formset.save() return HttpResponseRedirect("addoredit") else: formset = ActivityFormSet(queryset=Activity.objects.none()) return render(request, "activities.html", {"formset": formset}) forms.py class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ["key_area", "metric"] widgets = { "key_area": Select(attrs={"class": "custom-select"}), "metric": Select(attrs={"class": "custom-select metric"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["metric"].queryset = Metric.objects.none() template <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Untitled</title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"></script> </head> <body> <div class="container"> <div class="table-responsive table-bordered text-left"> <form id="myform" … -
How can i filter products by price range in same page in django [duplicate]
i want to filter products in a range of prices. i am makeing a ecommerce site and there is a price range system like this: price range image and the html code is here: <!-- Start Range --> <div class="htc-grid-range"> <h4 class="section-title-4">FILTER BY PRICE</h4> <div class="content-shopby"> <div class="price_filter s-filter clear"> <form action="#" method="GET"> <div id="slider-range"></div> <div class="slider__range--output"> <div class="price__output--wrap"> <div class="price--output"> <span>Price :</span><input type="text" id="amount" readonly> </div> <div class="price--filter"> <a href="#">Filter</a> </div> </div> </div> </form> </div> </div> </div> <!-- End Range --> How can i solve this problem? -
Django email registration forum
I have tried searching on google and on here as well. Tried looking through Django documentation as well. I only found how to send a email confirmation after signing up. i am trying to build a web app in Django. Only certain people can sign up though. I want to email the registration forum. How would i go about doing that? -
Django ImageField rename image [duplicate]
class Word(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to="cover/")) Word.image.path should be like "cover/<Word.title>.jpg". Is there any solutions? -
Progress bar in Django [duplicate]
How can I show a progress bar or something like that while a python script is running. Currently I am able to render the result in a new page, however I am seeking to show the user some feedback while the process takes place. Will I have to use a reactive front end like Vue? Is there any other way? -
Convert special character to ascii while passing to onclick (JavaScript, Django)
Here is my html code: <table id="myUpgradeTable" class="userform" > <tr> <td> <label for="" style="width:150px;" name='upgrade_title'><span>Upgrade Service</span></label> <td> <select name='upgrade_services' style="width:150px;" class="custom-select custom-select-sm" id="upgrade_services"> <option value="" selected style="background-color:lightgrey">NA</option> {% for entry in Services_List %} <option value="{{ entry }}">{{ entry }}</option> {% endfor %} </select> </td> <td> <input type="text" name="upgrade_version" style="width:150px;"> </td> <td> <button type="button" id="add_btn" class="newbutton_Style add" name="Trigger_upgrade" style="width:51px; height:30px;" title="Add Row" onclick="add_new_row({{Services_List}});" ></button> </td> </tr> </table> Here is the onclick method: function add_new_row (selections) { alert(selections) var myTable = document.getElementById("myUpgradeTable"); var currentIndex = myTable.rows.length; var currentRow = myTable.insertRow(-1); var linksBox = document.createElement("text"); linksBox.setAttribute("name", "upgrade_title" + currentIndex); linksBox.setAttribute("style", "width:150px"); var keywordsBox = document.createElement("select"); keywordsBox.setAttribute("name", "upgrade_services" + currentIndex); keywordsBox.setAttribute("style", "width:150px"); keywordsBox.setAttribute("class", "custom-select custom-select-sm"); var OPT1 = document.createElement('OPTION'); OPT1.setAttribute('value', ''); OPT1.setAttribute('selected', 'selected'); OPT1.appendChild( document.createTextNode( 'NA' ) ); keywordsBox.appendChild(OPT1); for (var i=0; i<selections.length; i++) { //alert(selections[i]) var OPT = document.createElement('OPTION'); OPT.setAttribute('value', selections[i]); OPT.appendChild( document.createTextNode( selections[i] ) ); keywordsBox.appendChild(OPT); } var violationsBox = document.createElement("input"); violationsBox.setAttribute("name", "upgrade_version" + currentIndex); violationsBox.setAttribute("style", "width:150px"); var addRowBox = document.createElement("input"); addRowBox.setAttribute("type", "button"); addRowBox.setAttribute("value", "+"); addRowBox.setAttribute("onclick", "add_new_row({{Services_List}});"); addRowBox.setAttribute("class", "newbutton_Style add"); addRowBox.setAttribute("style", "width:51px; height:30px;font-size:18px;"); var addRowBox1 = document.createElement("input"); addRowBox1.setAttribute("type", "button"); addRowBox1.setAttribute("value", "-"); addRowBox1.setAttribute("onclick", "remove_row(this);"); addRowBox1.setAttribute("class", "newbutton_Style remove"); addRowBox1.setAttribute("style", "width:51px; height:30px;font-size:18px;"); var currentCell = currentRow.insertCell(-1); currentCell.appendChild(linksBox); currentCell = currentRow.insertCell(-1); currentCell.appendChild(keywordsBox); currentCell = currentRow.insertCell(-1); currentCell.appendChild(violationsBox); … -
Why does my Django registration form is not rendered?
I have default Django registration form. It is sent to render to the page based on type of request and user login status. This logic is implemented in views.py file. Somehow, if user is not logged in and GET request is sent to the page, my view returns UnboundLocalError: local variable 'form' is referenced before assignment. How could this happen? P.S. Here's my view. def EmplRegisterView(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name = 'Employers') user.groups.add(group) login(request, user) return redirect('ProfileSetup') else: if request.user.is_authenticated: logout(request) form = UserCreationForm() else: form = UserCreationForm() context = { 'form':form, } return render(request, "registerPage.html", context) -
How to construct Django API to retrieve and parse files from S3?
I have a React webapp and an S3 bucket with text files, and I need the web app to play around with the text in those files. However, because you cannot access the files' contents without downloading it first, I think I'll need a backend server that downloads and parses it instead (and the web app would make HTTP requests to the REST api to get the text in json format). How would I set up a Django Rest Framework backend server to do this? Would I have to make models? Thank you! -
Image field is not updating in DJango forms while other non image fields are updating
I am trying to update classifieds Ads posting form (Django form) and all fields are updating except image field. Here is snippet of my code. views.py def save_all(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True books = vk_classifieds.objects.all() print(books) # messages.success(request, 'Your Ad successfully updated.') data['book_list'] = render_to_string('classifieds_adv.html', {'books2': books, 'success_Ad': 'Your Ad successfully updated.'}) else: data['form_is_valid'] = False context = {'form': form,} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def adv_update(request, id): book = get_object_or_404(vk_classifieds, id=id) print(book) if request.method == 'POST': form = PostAdEditForm(request.POST, request.FILES, auto_id="id_for_%s", instance=book) print("Files", request.FILES) # if form.is_multipart(): # save_file(request.FILES['image']) else: form = PostAdEditForm(instance=book, auto_id="id_for_%s") return save_all(request, form, 'classifieds_update.html') models.py class vk_classifieds(models.Model): cust_id = models.IntegerField() title = models.CharField(max_length=60) type = models.CharField(max_length=200) description = models.TextField(max_length=600) # cat_id = models.IntegerField() price = models.FloatField() state = models.CharField(max_length=100) zip = models.CharField(max_length=50) email = models.EmailField() # phone = models.CharField(max_length=60) image = models.ImageField(default=default_img) image2 = models.ImageField(default=default_img) image3 = models.ImageField(default=default_img) image4 = models.ImageField(default=default_img,null=True) added_date = models.DateTimeField(editable=False) modified_date = models.DateTimeField() class_status = models.IntegerField() username = models.CharField(max_length=100, null=True, blank=True) favourite = models.IntegerField(default=0) views_c = models.IntegerField(default=0,null=True) fav_email = models.CharField(max_length=100, default="none") # slug = models.SlugField(unique=True, max_length=100) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') ajax code for loading show data in … -
Django annotate on float field is not working properly
I'm using Django 2.2 I have the following model structure class Location(models.Model): name = models.CharField(max_length=200) country_name = models.CharField(max_length=200) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) class TrackingData(models.Model): location = models.ForeignKey(Location) I want to select latitude and count of the number of same latitudes data = TrackingData.objects.filter(locaiton__latitude__isnull=False).values(latitude=F('location__latitude')).annotate(count=Count('latitude')) I'm getting the results as <TrackingDataQuerySet [{'latitude': 28.6324823, 'count': 1}, {'latitude': 28.6324823, 'count': 1}, {'latitude': 28.6324823, 'count': 1}, {'latitude': 28.6324823, 'count': 1}, {'latitude': 28.6324823, 'count': 1}, {'latitude': 28.6324823, 'count': 1}, {'latitude': 28.6324823, 'count': 1}]> All latitudes are same, still getting separate results, instead, I want <TrackingDataQuerySet [{'latitude': 28.6324823, 'count': 7}]> -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured
I've already had a MySQL database. And I wanna use this to generate models.py in Django 3.0. And that's my configuration in settings.py: DATABASE = { 'default':{ 'ENGINE':'django.db.backends.mysql', 'NAME':'movies', 'HOST':'127.0.0.1', 'USER':'root', 'PASSWORD':'password', 'PORT' : '3306' } } Then I try this $ python3 manage.py inspectdb But it fails and remains these Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/inspectdb.py", line 33, in handle for line in self.handle_inspection(options): File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/inspectdb.py", line 46, in handle_inspection with connection.cursor() as cursor: File "/usr/local/lib/python3.6/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/usr/local/lib/python3.6/dist-packages/django/db/backends/dummy/base.py", line 20, in complain raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. But I don't know why. Are there some mistakes in my configuration of MySQL engine? -
uuid4() gives the same code again and again in Django
In my model I want to generate a random code when the model object is created but it gives me the same code again and again. If I use CharField it will gives me the same codes and if I use UUIDField it will gives me an error ['“5e3928” is not a valid UUID.']. I only want 6 digit code. here is my models.py class Class(models.Model): def hex_uuid(): return uuid.uuid4().hex[:6] random_code = models.UUIDField(default=hex_uuid(), editable=False, unique=True) # if i use CharField I will get the same code. -
Django filter has_key generates wrong SQL
I need to filter some objects that have no specific value in the field. I tried to do it like this: MyModel.objects\ .filter(<some filters>)\ .exclude(json_field__has_key='some_field', json_field__some_field=True) But this code generates wrong SQL query: ... AND NOT ( "my_model"."json_field" ? some_field AND ("my_model"."json_field" -> 'some_field') = 'true' AND "my_model"."json_field" IS NOT NULL) ) ... On the first line some_field used without qoutes. I fixed it by adding single qoutes to the string like this: json_field__has_key="'some_field'" but I dont think it's a good solution. Does anyone have an idea why it works this way and how I should fix it? -
how to get local ip not public ip in django?
so i have this website to manage the local network of my business i have 2 project inside it one is the callback server one is the main app that manage the local network. so i want to restrict to only people that can access the technician router can access the main app. i already make the view to get the client ip address but it return public ip but what i want is my local ip that is in range "192.178.1.x ~ 192.178.50", can anyone help me?, if anyone have suggestion how can i used different method for this cases please just share it out. thanks :) here's code views.py def ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') print(ip) return HttpResponse(ip) -
How to create folders in django admin?
Currently, I want to create a folder whenever I try to add a new tag in Django admin. But I don't know how to realize this function. my model.py code is as below: class Tags(models.Model): Tag_name = models.CharField('Tag Name', max_length=10, default='NA') Description = models.TextField('Tag Description', max_length=100, blank=True) class Meta: verbose_name = 'Tags' verbose_name_plural = verbose_name def __str__(self): return self.Tag_name The function I want is, for example, if I create a tag named "test", the system will automatically create a folder named "test" in a specific place. -
Django drf-yasg ViewSet Error: AttributeError: 'list' object has no attribute 'items'
I am using ReadOnlyModelViewSet for my API and I keep on getting an error: My ViewSet: class CartItemViewSet(viewsets.ReadOnlyModelViewSet): """ ViewSet for Cart functions """ queryset = CartItem.objects.all() serializer_class = CartItemSerializer permission_classes = [IsAuthenticated] Serializer: class CartItemSerializer(serializers.ModelSerializer): # product = UserSerializer(read_only=True) model = CartItem fields = ['uuid', 'product', 'quantity', 'cart_item_price'] Error Message: File "/usr/local/lib/python3.8/site-packages/drf_yasg/inspectors/field.py", line 102, in make_schema_definition for property_name, child in serializer.fields.items(): AttributeError: 'list' object has no attribute 'items' -
Django state sharing between server processes
I am building a Django project that one the of the apps has a state that I want to keep (a complex rate limiter as a Python Object that is hard to implement through something like Redis). By making the server to spawn new processes like WSGIDaemonProcess localhost processes=2 threads=25 Will it cause to lose sync of the state between processes ? In standard python one will spin a Manager that proxies the state in multiple processes. -
Login with Token
The goal is to be able to authenticate users to our website just with a string of memorizable token. I'm thinking of using django-token, or django-rest-framework to create an authentication token, create a memorizable string related to each token, and use that string to login user. I'm not very sure if it is going to work. Please, suggest me the best approach to achieve this or any other alternative methods. -
How to perform detection of breast cancer on Wisconsin dataset using a web app in Django, especially implmenting the backend side?
This is my front end of the web app. -
Unable to Understand the below statements of models in Django
I am naive in Django, I have done a sample E-commerce application that is present online. I am unable to understand the highlighted statements, I searched online but unable to understand the statements. Can someone please explain me like below productitems = self.name_set.all() From where this name_set.all() came ????????? orderItems = self.orderitem_set.all() likewise from where orderitem_set.all() ????????? from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, null=True,blank=True) name = models.CharField(max_length=200,null=True) email = models.CharField(max_length=200,null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7,decimal_places=2) digital = models.BooleanField(default=False,null=True,blank=False) image = models.ImageField(null=True,blank=True) #image def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url @property def get_product_total(self): **productitems = **self.name_set.all()**** total = sum([item.get_total for item in productitems]) return total print('total:',total) class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.SET_NULL,blank=True,null=True) date_ordered=models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False,null=True,blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderItems = **self.orderitem_set.all()** for i in orderItems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item … -
Django crate custom reusable app that include some changes on manage.py
I'm following this documentation to create a reausable Django application, but the main implementation is on manage.py e.g: #!/usr/bin/env python import os import sys from foo import bar #Need to append this import if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'educat_erp.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc is_testing = 'test' in sys.argv ## This lines if is_testing: ## needs to append bar() ## when add the aplication execute_from_command_line(sys.argv) Theres any way to create a reusable package that only need to be added on INSTALLED_APPS and modify the manage.py or any other way to check if tests are running to change some test configurations before run. -
Replicate Production Django Server + Postgres Database to Identical Linode server as a backup
I am trying to make an identical copy of a production server hosted on Linode. This is a Python/Django/Postgres implementation with tenant model. I am quite new to the implementation done by another developer who has since left. Current site is live with tenant1.prodlive.info tenant2.prodlive.info The steps I have carried out to take a backup within the linode dashboard and then created a new linode instance with that backup. After logging in, I am seeing all files have been copied correctly. However, I am missing steps on configuring some specifics due to which the server is showing 404 error when I try to access tenant1.backup.info tenant2.backup.info. The DNS is setup correctly to have A records for both. Server does respond to the main server url www.backup.info. The only file that I have changed is the \project_dir\django_project\middleware.py and changed the mention of the domain name and IP address prodlive.info and ip.prod.live.info to backup.info and ip.back.up.info. I may be missing some configuration items hence need help with some pointers and best practices to maintain an exact copy of the live production. Thanks in advance for all your suggestions and help. Here's the exact message I get when accessing the subdomain URL. Page … -
Way to implement CI test to check if function argument is valid?
Let's say I have a python function and dictionary as follows: d = {"a": 1, "b": 2, "c": 3} def foo(input): return d[input] Is there a way when I push my code to GitHub (presumably with some sort of continuous integration) to check that all calls of foo only use one of the keys of d as the input argument, and if there is a call with an invalid argument, to flag it or raise an alert? For example: foo("a") # no flag foo("d") # flag/alert I know how I would raise an exception or ValueError at runtime, but I'm looking for a CI solution to include in our GitHub workflow. Right now we are using Travis-CI for our custom tests and the standard CodeQL tests provided by LGTM. I looked into using custom CodeQL via LGTM, but I couldn't quite figure it out. I'd be fine implementing it in either of those continuous integrations or implementing a third. -
Django inlineformset not validating forms correctly
I am using inlinemodelformset to create bunch of financing forms, simple enough. But, when I submit the forms without inputting any value for all the fields, the form clean method does not raise ValidationError. Even the browser does not require the fields to be populated when they are set to required = True in the forms.py # In models.py class Financing(models.Model): loan_name = models.CharField(max_length = 30, null = False, blank = False) loan_type = models.CharField(max_length = 25, choices = ( ('interest_only', 'Interest-only), ('mortgage', 'Conventional Mortgage') ), blank = False, null = False) loan_amount = models.PositiveIntegerField(null = True, blank = True) loan_ratio = models.DecimalField(max_digits = 4, decimal_places = 2, blank = False, null = False, default = 70) # This is how much of the total cost the loan is covering interest_reserve = models.PositiveIntegerField(null = True, blank = True) application_fee = models.PositiveIntegerField(null = False, blank = False) interest_rate = models.DecimalField(max_digits = 4, decimal_places = 2) term = models.PositiveIntegerField(null = False, blank = False) term_unit = models.CharField(max_length = 25, null = False, blank = False, choices = ( ('years', 'Years'), ('months', 'Months'), ), default = 'years' ) compounded = models.CharField(max_length = 20, choices = ( ('annually', 'Annually'), ('semi-annually', 'semi-annually'), ('quarterly', 'Quarterly'), ('monthly', … -
Django Admin: Dropdown selecting ContentTypes & Generic Relationships
I have a generic relationship in my model: class Foo(models.Model): content_type = ... object_id = ... content_object = ... admin.site.register(Foo, FooAdmin) I understand with GenericTabularInline I could insert this as an inline generic object into a different admin form. To clarify, this is not what I am looking for. My question is: Given a FooAdmin above, now can I have the detail admin view provide a dropdown selector for object_id/content_object instead of having it as a raw ID field (which is very inconvenient)?