Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am i getting Uncaught SyntaxError: unexpected token: identifier
for (post of posts){ //Posts are returned from a python django function let readMore = ''; let postDesc = post.fields.description if (post.fields.description.length > 227) { readMore = `<p class="btn btn-link" onclick="this.innerHTML = ${postDesc}"> Read more</p>`; }; output += ` <p class="card-text" style="white-space: pre-line;"> ${post.fields.description.substring(0, 227)} ${readMore} </p> ` }; } But when i click the read more button: Uncaught SyntaxError: unexpected token: identifierlocalhost:8000:1:22 I tried to remove the onclick and replace it with this at the end: $('#mainPosts').append(output) function showMore() { $('.readMore').click(function (e) { e.preventDefault(); $(this).parent().html(`<br> ${post.fields.description}`) }) } let g = document.createElement('script'); let s = document.getElementsByTagName('script')[0] g.text = showMore(); s.parentNode.insertBefore(g, s) But the problem is it's not replacing the substring current post description with the full one, it's replacing it with the very last post full description in the list! -
How to have a list of Fields in django models?
I have a models like this: from django.db import models class Article (models.Model): author = models.ForeignKey('Users.User') title = models.CharField() text = models.TextField() stars = [ models.IntegerField(), # 0 stars models.IntegerField(), # 1 stars models.IntegerField(), # 2 stars models.IntegerField(), # 3 stars models.IntegerField(), # 4 stars models.IntegerField(), # 5 stars ] but the problem is it the stars Fields won't be recognized in 000x_initials.py. What I have to do? I want to use it like this: if request.method == 'POST': post_data = request.post star = int(post_data['star']) article.stars[star] += 1 article.save() -
Unable to start django site
I have been trying to run my django application/site by using python manage.py runserver But the command line just does not show any output. I have selected the python env as the interpreter already but still, nothing happens -
Upload Document in Django Rest Framework Dynamic Form
In my Djago-React Application I am creating a form which has dynamic fields as well as an option to upload the document For that I am using multipart/form-data and its working fine when I am using it only to upload the document but as soon as I enter the data in dynamic fields the serializer stops handling the data. Example data: Form Data: transaction_no: 2341 document: (binary) items[0][product]: 5 items[0][quantity]: 1 items[0][fault]: Repairable items[1][product]: 4 items[1][quantity]: 2 items[1][fault]: Return allotment: 122 Response: {"items":[{"product":["This field is required."]},{"product":["This field is required."]}]} Serializer: class DeliveredItemsSerializer(serializers.ModelSerializer): class Meta: model = DeliveredItems fields = "__all__" class DeliveredSerializer(serializers.ModelSerializer): items = DeliveredItemsSerializer(many=True,required=False) class Meta: model = Delivered fields = "__all__" def create(self, validated_data): items_objects = validated_data.pop('items', None) prdcts = [] try: for item in items_objects: i = DeliveredItems.objects.create(**item) prdcts.append(i) instance = Delivered.objects.create(**validated_data) print("prdcts", prdcts) instance.items.set(prdcts) return instance except: instance = Delivered.objects.create(**validated_data) return instance def update(self, instance, validated_data): items_objects = validated_data.pop('items',None) prdcts = [] try: for item in items_objects: print("item", item) fk_instance, created = DeliveredItems.objects.update_or_create(pk=item.get('id'), defaults=item) prdcts.append(fk_instance.pk) instance.items.set(prdcts) instance = super(DeliveredSerializer, self).update(instance, validated_data) return instance except: instance = super(DeliveredSerializer, self).update(instance, validated_data) return instance Models: class DeliveredItems(models.Model): choices = (('Repairable', 'Repairable'),('Return', 'Return'), ('Damage', 'Damage'), ('Swap Return', 'Swap Return')) product … -
is serializer necessary in Django RestFramework when operating with external db
I have requirement where in, I am suppose to build REST API, Database that i have to use is MongoDB and is not a part of the current Django project, it is managed and handled by some other team. for current Django project, I use MySQL. below is how i write API's with current django project with MySQL views.py class UserViewSet(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) serilaizers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' but for MongoDB new requirement, i use PyMongo to interact with MongoDB views.py import pymongo class EmpViewSet(viewsets.ViewSet): def list(self, request): myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["external_database"] mycol = mydb["employee"] result = mycol.find_one({'emp_id': 123}) return Response({"result": result}, status=status.HTTP_200_OK) it is working fine with above code(it is not the exact code, similar implemention). i need to do all CRUD operation on MongoDB. I am unaware that serialzers is needed for this or not? if needed then, how will i write the serializer for it, since the result from the mongo query may give dynamic schema. any help will be greatly appreciated ! Thanks in advance ! -
Separate Django Restful API into two servers
I am developing an API server which is written in Django framework, and using Nginx and uWSGI to implement the web server. There are several APIs contain in this project, some of them are related to billing service, which are relatively important that we are thinking about to separate these APIs to run on another server. The two API servers are going to use the same files, all the models and database are the same. The following is my nginx.conf: user nginx; worker_processes 2; worker_rlimit_nofile 8192; events { worker_connections 3000; } http { upstream myapp { server unix://tmp/myapp.sock; } server { listen 80; location / { include uwsgi_params; uwsgi_pass myapp; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; } } } I had found several solutions that adding another server block inside of the nginx.conf, and also provide a uwsgi.ini config file for it. But I still don't know how to implement it exactly. I am really new to the Nginx, and have pretty blur concept about it now. Appreciate for any help! -
Unable to bind data in tables with one view function
def index(request): indexdata = Customer.objects.all() return render(request, 'index.html',{ "Customer":indexdata }) indexdata2 = home.objects.all() return render(request, 'index.html',{ "home":indexdata2 }) -
django model _meta.get_fields() just datettime fields
I have want gather just fieldname type is datetime by _meta.get_fields() Model.py : class testmodel (models.Model): name = models.CharField(max_length=200) field = models.CharField('field', max_length=50, choices=(), default=None) create_time = models.DateTimeField(null=True,blank=True) complete_time = models.DateTimeField(null=True,blank=True) admin.py : all_fields = [f.name for f in testmodel._meta.fields] class myform(forms.ModelForm): field = forms.ChoiceField(choices=all_fields) name = forms.TextInput() class MyModelAdmin(admin.ModelAdmin): fields = ('name', 'field',) list_display = ('name', 'field',) form = myform admin.site.register(testmodel,MyModelAdmin) what is solution for this ? -
Json keyerror python
This is the error I am facing While trying to "POST" views.py file def scent_data_pass(request): if request.method == 'GET': response = {} response["data"] = "Data has been saved" return JsonResponse(response, status=200) if request.method == 'POST': response = {} json_data = json.loads(request.body.decode('utf-8')) name = json_data["name"] uuid = json_data["datatuuid"] saved = Scent_raw( name=name, device_uuid = uuid ) saved.save() try: response['result'] = 'Success' response['message'] = saved.datatuuid except: response['result'] = 'Ouch!' response['message'] = 'Script has not ran correctly' return JsonResponse(response) models.py file class Scent_raw(TimeStampedModel): name = models.CharField(max_length=100, default="", editable=False) datatuuid = models.UUIDField(max_length=100, default="", editable=False) class Meta: verbose_name = 'Scent raw data' verbose_name_plural = "Scent raw data" def __str__(self): return f'{self.id}' Why I am facing keyerror here ? -
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'