Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NUMBER_GROUPING is not applying THOUSAND_SEPARATOR
I'm using Django (1.11.7) with Python (2.7.1) and I have this set in my settings file. USE_I18N = False USE_L10N = False USE_TZ = False DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' USE_THOUSAND_SEPARATOR = True NUMBER_GROUPING = 3 I would expect Django to group numbers in groups of 3 and add a THOUSANDS_SEPARATOR in between. When I print out variable in template I get 5172,00 where I'm expecting to get 5.172,00 How can I solve this and is this a bug in Django itself or a settings misconfiguration? -
how to wordpress theme customization with python backend
I have a job interview.Interviewer told me to prepare for a practical test related to WordPress theme customization with back-end and front-end development.That company vacancy is for python developers with Django knowledge. I have no previous python web developing experience. So, I need to know how to use python with wordpress in this matter. Please give me a help/tutorial/link to learn this before the practical test. -
How to navigate from current html page to another html page in django
I'm working on django app and i'm facing a problem when i need to navigate from my index.html page to another about.html page. I'm setting everything in this way below: urls.py (myproject) from django.urls import path, include urlpatterns = [ path('', include('weather_app.urls')), path('about/', include('weather_app.urls')) ] urls.py (myapp) from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name="about") ] In index.html, everything is working well, so i will not put the code. and in view.py: from django.shortcuts import render import requests def about(request): return render(request, "about.html") i have the code below in my index.html: <a href="/about.html/">About </a> and i cannot get about.html page when click About link as you can see above. Can anybody help me? Thanks in advance.. -
Add items to manytomany field from views.py
I have a situation where i need a model that has a manytomany field that references other objects of the same class. This is because i have devices that have dependencies, which are each other. Is there a way to update an objects linked class manytomany field? models looks like this: class Device(models.Model): hostname = models.Charfield(max_length=50) class Dependency(models.Model: device = models.ForeignKey(Device, related_name='dependencies', on_delete=models.CASCADE) In the view it open a .yml file that has all the data of each device including which dependencies each device has. views.py def new_build(request): if request.method == 'POST': devices = Device.objects devices.all().delete() with open('device.yml', 'r') as data: device_data = yaml.load(data) for device in device_data: device.hostname = device_data[device]['hostname'] if device_data[device]['dependencies']: device.dependencies.add(device_data[device]['dependencies']) However, clearly this isn't working or i wouldn't be posting on here. Is there another way to achive this? can i have a manytomany field within the same 'Device' class referencing other objects of the same class? -
Raising a custom 400 bad request in a Rest API using django and django rest framework
I want to return a custom error when a HTTP 400 Error is raised. this is my model : class User(models.Model): fullname = models.CharField(max_length=100) phone = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=50, default='SOME STRING') this is my serializer class : class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'fullname', 'phone', 'password') this is my class in the views class : class RegisterUsers(generics.CreateAPIView): . . . serializer = UserSerializer(data={ "fullname": fullname, "phone": phone, "password": password } ) if not serializer.is_valid(raise_exception=True): return if I try to register with the same number twice, a 400 bad request error is raised like the screenshot below : I want to catch the error and parse it in to a custom response that looks like that : can anyone help me with this issue ? thanks in advance. -
django not returning request response
i am using this code to make an api which return the post request so i can test and modify them according to my needs. I have tried two codes by searching on SO. from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def some_view(request, username): json_data = json.dumps(request) return JsonResponse(json_data, safe=False) This code give me the error of is not JSON serializable. If i applied a list attribute to it. Like from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def some_view(request, username): json_data = json.dumps(list(request)) return HttpResponse(json_data) it did not give me an error but return the empty output.[] I am testing this api through POSTMAN. -
Project Object has no attribute "review_set"
Getting an error that says "Project object has no attribute review_set" when trying to get the mean of ratings using Numpy. HTML looks something like this, what could be the problem? Please have a look below and let us know what you think: <h5>{{ project.review.count }} reviews ({{ project.average_design | floatformat }} average rating of design)</h5> <h5>{{ project.review.count }} reviews ({{ project.average_content | floatformat }} average rating of content)</h5> <h5>{{ project.review.count }} reviews ({{ project.average_usability | floatformat }} average rating of usability)</h5> class Project(models.Model): title = models.TextField(max_length=200, null=True, blank=True, default="title") project_image = models.ImageField(upload_to='picture/', null=True, blank=True) description = models.TextField() project_url=models.URLField(max_length=250) def average_design(self): design_ratings = list(map(lambda x: x.design_rating, self.review_set.all())) return np.mean(design_ratings) def average_usability(self): usability_ratings = list(map(lambda x: x.usability_rating, self.review_set.all())) return np.mean(usability_ratings) def average_content(self): content_ratings = list(map(lambda x: x.content_rating, self.review_set.all())) return np.mean(content_ratings) class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), ) project = models.ForeignKey(Project, null=True, blank=True, on_delete=models.CASCADE, related_name="review") user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='user') image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name="project", null=True, blank=True) comment = models.TextField() design_rating = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True) usability_rating = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True) content_rating = models.IntegerField(choices=RATING_CHOICES, null=True, blank=True) -
Docker + Django, docker-compose up does not seem to run migrate command
I am currently creating a Django app that is supposed to run a web scraping code as soon as it starts and then respond with certain data on requests via REST API. The requirement is that it must run on Docker which is causing me a following problem: when using docker-compose up the image is being built properly, db service runs but then I get an error saying that relations in my DB do not exist. I can rectify this by running docker-compose run [service] manage.py migrate but this is a manual solution and won't work when someone clones the app from git and tries to run it via docker-compose up. I have used command: python /teonite_webscraper/manage.py migrate --noinput in my docker-compose.yml but it does not seem to run for some reason. docker-compose.yml: version: '3.6' services: db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /teonite_webscraper/manage.py migrate --noinput command: python /teonite_webscraper/manage.py runserver 0.0.0.0:8080 volumes: - .:/teonite_webscraper ports: - 8080:8080 environment: - SECRET_KEY=changemeinprod depends_on: - db volumes: postgres_data: Dockerfile: # Use an official Python runtime as a parent image FROM python:3.7 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory WORKDIR /teonite_webscraper # … -
Django Web application
I am a beginner and trying to learn the creation of web applications using Django so I have watched Corey Schafer tutorial for that,I was able able to create a project successfully as per 1st video of tutorial,but I got stuck at displaying the message on website which was 2nd video of tutorial.I have followed all the instructions and made the changes accordingly but no result I have tried making the changes by going through the documentation of Django version which am currently using--Django(2.1.2) and am using pycharm editor of version 2018.2 am getting the Error as attached in the reference documents FYI,am using python version--3.7 Kindly help me get through this,will be so grateful to u all... webapp tutorial Am getting the error as :: ModuleNotFoundError: No module named 'blog.urls' -
Url not found in server
I have written a function on paypal when user would cancel payment then it would redirect to paypal-cancel page which i have defied in my app level url.py. But problem is it is showing error that Not Found The requested URL /paypal-cancel was not found on this server. BuT I have defined this function in url. web/urls.py urlpatterns = [ url(r'^paypal-payment$', ApiPaymentPayPalView.as_view(), name='paypal-payment'), url(r'paypal-cancel', PaypalCancelView.as_view(), name='paypal-cancel'), ] whatever i do r'paypal-cancel' or r'^paypal-cancel$' nothing is working project/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('web.urls')), ] So,where am i doing wrong? I think i have given wrong regex probably! -
getfeatureinfo display dropdown instead of column value
Hello guys I would like to output in the map the dropdown description for a certain material. Example no 1 for me is concrete and no 2 is PVC. I would like that when the attribute table opens to appear concrete not 1. This is my code: content.ftl <#list features as feature> <dl class="dl-horizontal"> <dt>Layer-ww_manholes:</dt> <dt>Gis_Id:</dt> <dd class="text-info">${feature.gis_id.value}</dd> <dt>Y:</dt> <dd class="text-info">${feature.y.value}</dd> <dt>X:</dt> <dd class="text-info">${feature.x.value}</dd> <dt>Y_Geo:</dt> <dd class="text-info">${feature.y_ge.value}</dd> <dt>X_Geo:</dt> <dd class="text-info">${feature.x_ge.value}</dd> <dt>Z:</dt> <dd class="text-info">${feature.z.value}</dd> <dt>Material:</dt> <dd class="text-info">${feature.material.value}</dd> <dt>Comments:</dt> <dd class="text-info">${feature.comments.value}</dd> </dl> </#list> -
'block' tag with name 'item_content' appears more than once
{% if item_counter != 0 %} <div id="main"> <div id="side"> {% block item_content %} {% endblock %} </div> </div> {% else %} {% if request.resolver_match.view_name == 'new_item' %} <div id="new_item_first"> {% block item_content %} {% endblock %} </div> {% else %} {# TODO #} {% endif %} {% endif %} I have a template where I want to display the item_content in different div's. The structure looks different if there is no item in the list. How can I solve the error "'block' tag with name 'item_content' appears more than once" -
How to connect field of template with forms.py and with views.py so that values pass in template field can go through functions
I am new to django. I making an login and register page using django .In this i have the templates files called login.html.In registration i have given the field of name,email and password .Now my issues is how to connect those values of name field in form.py and views.py.I didn't what to write in form.py and why we use that I have tried my best to do.But don't know it is correct or not. login.html <input type ="text" placeholder="name" id="name" name ="name" onblur="name_check(this.value)" style="margin-bottom: 05px;" required /> <span id="errorname"style="color: red;"></span> <input type ="email" placeholder="email id" id="email" name="email" onblur="email_check(this.value)" style="margin-bottom: 05px;" required /> <span id="erroremail"style="color: red;"></span> <input type ="password" placeholder="password"id="password-input-0" name="password" onblur="password_form(this.value)" style="margin-bottom: 05px;" required /> <span id="errorpassword"style="color: red;"></span> <input type ="password" placeholder="confirm password" id="password-input-1" name="confirm_password" required/> <button type="submit" onclick="password_form(); name_check(); email_check();">sign up</button> <p style="color:#6F53C3;font-family:cambria;"class="message">Already Registered? <a href="#"> login </a> views.py def StudentRegister(request): form_var = form.StudentRegister() if(request.method == "POST"): form_var = form.StudentRegister(request.POST) if(form_var.is_valid()): Student_Name1 = request.POST['name'] Email1 = request.POST['email'] Password1 = request.POST['password'] Confirm_PassWord1 = request.POST['confirm_password'] if(Password1 == Confirm_PassWord1): form_var.save(commit = True) count = AddEnquiry.objects.filter(Student_Name=Student_Name1).count() return render(request,"DashBoard.html",{'count':count}) return render(request,"login1.html",{'form':form_var}) -
Where is the best place to send email in django-rest-framework?
I want to send emails in django rest framework, for example when someone creates an account,or comments something and etc. I found this in django documents. But I don't know where to use it. maybe in Viewset but in which method. so what is the best way and where is the best place to send emails in Django Rest Framework? -
Python - Update HTML automatically when variable change
I want to use python to create a web-based user interface for an app. I've already worked with flask, but I would also change to Django or something similiar if necessary. The app I'm working on has got a background loop, that changes some global variables sometimes. I want my interface (webpage) to react to the variable changes, but just can't figure out how to do this. Again, I'm not limited to any specific framework. This should happen in real-time, so I don't want to periodically send AJAX-Requests to make this happen. Can someone help me out? Thanks in advance. -
Use Ajax response script into a Django HttpResponse
I am trying to pass the ajax response obtained from view to the template using HttpResponse but I don't have any idea , how to do that? My view.py analyzer=SentimentIntensityAnalyzer() def index(request): return render(request, "gui/index.html") @csrf_exempt def output(request): sentences = request.POST.get('name',None) senti = analyzer.polarity_scores(sentences) context_dict = {'sentiment': senti} return render(request,"gui/index.html", context = context_dict I want the senti to be printed after the score on the page but I am unable to obtain it. My template file <!doctype html> <html> <head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head> <body> <form action = Post> Enter Sentence:<input id = "name" type = "text" name = "EnterSentence" encoding = "utf-8"><br> <input onclick = "testfunction()" type = "button" value = "Submit" > </form> <div><strong>Score is {{ sentiment }}</strong></div> </body> <script> var testfunction = () => { var test = document.getElementById("name").value console.log(test) $.ajax({ type: "POST", dataType: "json", url: 'output/', data:{ csrfmiddlewaretoken: '{{ csrf_token }}', 'name': test }, success: function(response) { console.log("Succesful return firm ajax call"); }, error: function(result){ console.log("Failure"); } }); } </script> </html> -
POST request with nested JSON parameters malformed in request.POST
Inside integration tests, I try to make a POST request with a nested JSON parameter (this is just one of the approaches I tried): test_function(admin_client): admin_client.post(some_url, json.dumps(some_nested_json), content_type='application/json', headers={'Content-type': 'application/json; charset=utf-8'}) I've also tried all sorts of different combinations for the parameters etc., everything I could find on the web, but I can't get the proper JSON output in the received request.JSON. I get one of these three cases: request.POST contains the first level of JSON plus the arrays of second level JSON keys request.POST contains the first level of JSON plus an empty second level JSON request.POST is empty, but request.body contains the whole nested JSON, in expected format What am I missing here? I'm using Python 2.7. -
How to implement RPC pattern in celery?
I use Django, Celery and rabbitmq. I found this tutorial: https://www.rabbitmq.com/tutorials/tutorial-six-python.html, and i need make the same with Celery instead pika. Where can i see example how this do? -
'NoneType' object has no attribute 'has_header' in django
I use windows 7, python 2.7 and Django 1.11. I have already created a custom button in the Django admin interface. I want to bond a custom funtion to this button. the button is called call_exe ang the function is called when_call_exe def response_change(self, request, obj): if "call_exe" in request.POST: when_call_exe() return HttpResponse but error occurs: 'NoneType' object has no attribute 'has_header' How to call the when_call_exe function when I click the call_exe button in the django admin interface? -
Missing default model permissions during unit testing in Django app
There are default model permissions for view/add/update/delete in database when applying migrations(it's working with my main DB): sadmonad=# select count(*) from auth_permission; count ------- 32 (1 row) But in django.test it is not so: it only creates permissions for django modules like auth, session, contenttype, etc: test_sadmonad=# select count(*) from auth_permission; count ------- 24 (1 row) I'm using Django 2.1.1(in my models I didn't specify custom permissions), so what should I do to fix this behaviour? -
Django Execute Function When DateTimeField Equals Current Date and Time
So I have implemented a subscription product to my website. When they start the subscription, the current date and time is stored into the database. When they cancel the subscription, a period of time is added onto the start date so I know when to cancel the subscription and change some values elsewhere. This is fine, I know how to use Django and Python, however, I am stuck on the last bit of, when the cancel date comes around in the future. Question: How do I execute a function when the cancel date (in the db) is equal to current date and time. Below is an simple example of the model I will be using: models.py class Subscriptions(models.Model): subscription_id = models.AutoField(primary_key=True) start_date = model.DateTimeField(auto_now_add=True) cancel_date = model.DateTimeField(auto_now_add=False) person_id = model.ForeignKey('Persons') class Persons(models.Model): person_id = models.AutoField(primary_key=True) value_to_change = models.BooleanField() Before you ask I have not attempted any code as I couldn't find a solution for this problem. Thanks <3 -
Removing built-in fields from wagtailstreamforms
I'm trying to remove the date, time, and multiselect fields from the wagtailstreamforms Admin page, such that they can't be used in any form site-wide. I've tried calling register('<field_name>', None) to get rid of it, but this doesn't work: # wagtailstreamforms_fields.py from wagtailstreamforms.fields import register @register('date', None) @register('time', None) @register('multiselect', None) And creating an AppConfig to manually purge the wagtailstreamforms.fields._fields dict of the entries, but that doesn't seem to work either. I've made sure that this AppConfig is part of an app that loads after wagtailstreamforms. class UpdatedConfig(AppConfig): name = 'my_new_app' def ready(self): from wagtailstreamforms.fields import _fields _fields.pop('date') _fields.pop('datetime') _fields.pop('multiselect') for x in _fields.keys(): print('{}: {}'.format(x, _fields[x])) Is there any way to do this, hacky or otherwise? I'm using Wagtailstreamforms 3.1 and Wagtail version 2.2.2. -
Change the uploaded image format in django
This is the model I am using to upload and rename image files in Django, @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename): ext = filename.split('.')[-1] filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(self.path, filename) class Diagram(models.Model): diagram = models.FileField(upload_to=PathAndRename("diagrams/")) text = models.CharField(max_length = 48) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) Now the images are saved in both .jpg and .png as per its original format. My question is how to make all the uploads, be it .jpg file or .png file to store in common format e.g. all images in .png file. -
Django REST framework not looking for URL encoded detail views
I have a model whose Primary Key is a TextField. This is a minimalistic reproduction of my issue: Model: class Filename(models.Model): path = models.TextField(primary_key=True) Serializer: class FilenameSerializer(ModelSerializer): class Meta: model = Filename fields = '__all__' View: class FilenameViewSet(ModelViewSet): queryset = Filename.objects.all() serializer_class = FilenameSerializer I'm using a DefaultRouter for URLs. Here is the problem: If I sent {"path":"test"} with a POST /filename/ I can perfectly retrieve my object with GET /filename/test/ as you would expect. However, if I POST /filename/ something like {"path":"c:\\test"} I would expect either GET /filename/c%3A%5Ctest/ or GET /filename/c%3A%5C%5Ctest/ to be the proper way to get it, but none of those works. Does anybody knows what's going on? -
Django, looking to change html for a variable class after Ajax function is successful. How can I pass a variable into the css class?
My button code is currently: <script type="text/javascript"> var forLoopCounter = '{{forloop.counter}}' function toggleLike(){ $.ajax({ url: "{% url 'photo_blog-post_like_api' post.id %}", success: function() { $("#likeCount").html(data.like_count + ' likes'); $('.imageElement').html(data.img); console.log(data); } }); }; </script> On the $('.imageElement') I actually want to pass in the forLoopCounter variable, so for the first loop it reads $('.imageElement1'), the second loop it reads $('.imageElement2'), etc. How do I pass this variable into the string? Thanks!