Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago annotate if id is in subquery
I have employers = Employers.objects.all() employers_hired = employers.filter(person__in=get_valid_people()).distinct('id') employers_never_hired_anyone = Employers.objects.exclude(id__in=employers) employers.annotate(never_hired=Exists(employers_never_hired_anyone)) however my never_hired flag does not work as I intended. What am I missing? -
expected an element of ColumnData(String, Seq(Any))
im trying to print a data visualization using bokeh and django, the data that i want to print is int and string, but i got this error, i tried changing the data to string but i still cant get it to work, the data is being outputed from sqlite using filtering in django, here is what i already do views.py def datvis(request, id): usrn = request.user.username fruits = t_nilai.objects.filter(nama=usrn).values('nama_mapel')[0]; counts = t_nilai.objects.filter(nama=usrn).values('nilai')[0]; source = ColumnDataSource(data=dict(fruits=fruits, counts=counts)) p = figure(x_range=fruits, plot_height=350, toolbar_location=None, title="Fruit Counts") p.vbar(x='fruits', top='counts', width=0.9, source=source, legend_field="fruits", line_color='white', fill_color=factor_cmap('fruits', palette=Spectral6, factors=fruits)) p.xgrid.grid_line_color = None p.y_range.start = 0 p.y_range.end = 9 p.legend.orientation = "horizontal" p.legend.location = "top_center" script, div = components(p) return render(None, 'grader/dataVisualisasi.html', {'script' : script, 'div' : div} ) urls.py url(r'^dataVisualisasi(?P<id>\d+)$', datvis, name='datavis') the html file <html> <head> <link href="http://cdn.pydata.org/bokeh/release/bokeh-2.0.2.min.css" rel=”stylesheet” type=”text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-2.0.2.min.css" rel=”stylesheet” type=”text/css”> <script src="http://cdn.pydata.org/bokeh/release/bokeh-2.0.2.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-2.0.2.min.js"></script> {{ script | safe }} <title>Data visualisasi</title> </head> <body> {{ div | safe}} </body> </html> -
Django code changes not reflected without restart
I used python manage.py runserver to start the django server locally. I noticed the change of HTML code is not reflected if I don't re-start the server. Is it normal? Is it possible to see the change without restarting the server? -
Object word is assign to models automatically in Django
How object word is added automatically? It makes difficulty in choosing. How to set different words to it? -
How to get the first child from a recursive relationship
I've been using def get_all_children(self, include_self=True): r = [] if include_self: r.append(self) for c in Cateogory.objects.filter(parent=self): _r = c.get_all_children(include_self=True) if 0 < len(_r): r.extend(_r) return r to get all the children of an object, however it returns all the children of its children as well. How can I can only the first, direct children? -
Django not rendering a template with a raw query
I'm trying to render a custom template with a custom SQL statement with the following code: def get_pms(): with connection.cursor() as cursor: cursor.execute('SELECT p.Id, f.Id, p.description as ProjectName, f.xPMNumber as xNumber from ' 'project_project p LEFT OUTER JOIN xpm_xpm f ON f.ProjectID = p.Id') result = cursor.fetchall() return result and I also tried with this one, which basically does the same thing, except this one is not raw: result = list(Project.objects.values(ProjectName=F('description'), xNumber=F('p_set__xPMNumber'))) Views.py class ListProjectsView(LoginRequiredMixin, ListView): #xpms = Project.objects.values(ProjectName=F('description'), xNumber=F('p_set__xPMNumber')) xpms = get_pms() template_name = 'project/feed.html' model = Project context_object_name = 'xpms' I commented out one variable here to test out if it worked This is the template where I'm trying to render {% extends "base.html" %} {% load bootstrap4 %} {% block head_content %} <title>Projects</title> {% endblock %} {% block container %} <div class="container"> <div class = "list-group"> {% for i in xpms %} <a href=""class="list-group-item list-group-item-action"> <p>{{ i.description }} </p> <p>{{ i.xPMNumber }}</p> </a> {% endfor %} </div> <div class="float-right mt-4"> <a class="btn btn-primary" href="{% url "project:create" %}" role="button">Create a new project</a> </div> </div> {% endblock %} It renders the project name with i.description but it doesn't render the xPMNumber I don't know if I'm accessing wrong into … -
Django REST: Why use LOGIN when you can AUTHENTICATE?
I'm wondering, why use Login when you have an Authentication Token? I mean I'm using Postman to test my urls, serializers and views. I can log in and I have to use a different urls to get my access token and my refresh token. Login: POSThttp://localhost:8000/login/ { "username":"Max", "password":"Yolo1234" } ----- { "id": 2, "username": "Max", "is_a": true, "is_e": false } Token: POSThttp://localhost:8000/api/token/ { "username":"Max", "password":"Yolo1234" } ----- { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU4Nzc1OTQ5NCwianRpIjoiOWUzNjg1OTZhZWViNDRiNWE2Nzg3Y2E0ZDhkODQ5OWQiLCJ1c2VyX2lkIjoyfQ.W9a2fCxUF9Hrf51l-Ecx7nt2tmt2QvLhr4pp2DBUuvE", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTg3NjgwMjk0LCJqdGkiOiIwNDI3MmJhMjljNmM0ODk3ODg4YTI5YTBkZjViZDljZCIsInVzZXJfaWQiOjJ9.0sid4rSbDUX3LHX7X74Cw1H9_lSlwD5ppfC3ctLGFSo" } And when I'm trying to POST an article, I need to authenticate with my access token. But when I log out, I can still POST an article by using my access token without being logged in. So I have some difficulty understanding the need to have the two in the project. Thanks for your answers! -
Djnago, is it possible to create hierarchical status choice with a model?
I would to create a form that give the possiblity to the users to select a choice from a multiple choices and based on your choice can select the second form. The latter changes based on the first choice. The structure of my dataset is the following: -ProductA: -->sub_product_a_1 -->sub_product_a_2 -->sub_product_a_3 -ProductB: -->sub_product_b_1 -->sub_product_b_2 -->sub_product_b_3 So if the client choose in the first box form Product A, in the second box can choose only sub_product_a_1, sub_product_a_2 sub_product_a_3. Finally I have the necessity to create this hierarchical status choice with models, to give the possibility to the user to customize the list. I only just managed to create the first level of choice (Product A and Product B), but I haven't been able to create the second level of hierarchy in the same form. I attached below my code: models.py class Product(models.Model): slug = models.SlugField() product_category = models.CharField() class Inventory(models.Model): category= models.ForeignKey(Product, blank=False, on_delete=models.CASCADE) -
How to debug Django Project inside Docker Compose project (Cannot retrieve debug connection: Debug mode is not supported for...)
I've installed a docker-compose project and I am running it from IntelliJ. docker-compose django project database project nginx project I achieved to run it succesfully, and I already can deploy from IntelliJ IDE. I configured a setting for debugging with docker-compose as in the following image. When I click the debug icon to start debugging, I am getting the following error: Deploying 'Compose: docker'... /usr/local/bin/docker-compose -f /home/someone/project/docker-compose.yml up -d django db nginx pr_django_1 is up-to-date pr_db_1 is up-to-date pr_nginx_1 is up-to-date 'Compose: docker' has been deployed successfully. Cannot retrieve debug connection: Debug mode is not supported for 'Docker-compose: docker' I can't find what I missed to configure it, the django webpage and whole project is visualized good, I just can't start debugging. -
How to customize django-rosetta admn page
Since when I open django-rosetta on the admin page by setting ROSETTA_SHOW_AT_ADMIN_PANEL = True in the settings file. I am able to open it on the admin page, but when it opens it takes full-page, and I am unable to go back to the homepage(as there is no button) except when I press the back button of the browser. Is there any solution for this, or do I have to override the rosetta home page? -
Django 3 doesn't load css file
I am testing my django project locally. The templates and static files are as listed: When I run the server, the html file is loaded but Google Chrome indicate that: Google Chrome My settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstapp', ] ................................ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "Hello/static"), ] Urls.py from django.contrib import admin from django.urls import path, re_path from firstapp import views urlpatterns = [ path('', views.index), path('admin/', admin.site.urls), ] django not displaying image I cannot understand why? -
Django REST Framework - API Authentication - Authorize Apps instead of Users
Being new to Django, i was wondering if there's a "fast" and "elegant" way to replace the default model against which Django creates access tokens for API authentication ? I use plugins like "django-rest-framework-simplejwt", and by default they work only with the user model. The point is to let users create apps, and each app has its own API access and refresh tokens ! Thank you. -
heroku h13 error code when using postgresql
Problem I have a Django app that I host on heroku. It's not the first that I do, so much so that I pretty much use the same config for the 4 apps that I have hosted there. However, I have a problem with the latest one, when I deploy with the default sqlite3 setup, everything works as it should, but if I use the prod settings that I usually use on my other projects, it crashes and I get an H13 error code. What I tried I obviously tried the server settings locally, and everything works as it should. I couldn't test directly with gunicorn however, and I'm wondering if there is a problem there. I tried removing the heroku settings, hardcoding the env variables (in case I miss-typed). The code I'll add some code if needed, but basically when I replace this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USR'), 'PASSWORD': os.environ.get('DB_PWD'), 'HOST': os.environ.get('DB_IP'), 'PORT': os.environ.get('DB_PORT'), 'OPTIONS': {'sslmode': 'require', }, } } by this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } it works. Just that I can't run with that in production, especially on Heroku. I have three settings files, a … -
Django-Select2 Heavy Widget
I was trying to implement Django-select2 for the first time.... I referred their documentation and some of the stack overflow solutions to implement it.... I managed to get ajax functionality work properly, also i am able to select multiple choices... however when I submit and validate the form, I am getting error like -> "Select a valid choice. 34425 is not one of the available choices." I am not understanding what I am doing wrong.... here is my form. class MyCustReqForm(forms.ModelForm): initial_customer = forms.MultipleChoiceField( widget=HeavySelect2MultipleWidget(data_view='customer_ajax', attrs={'data-minimum-input-length': 4, 'delay':200}, model=Customer), ) end_customer = forms.MultipleChoiceField( widget=HeavySelect2MultipleWidget(data_view='customer_ajax', attrs={'data-minimum-input-length': 4, 'delay':200}, model=Customer), ) class Meta: model = Workflow_Customer fields = [ 'initial_customer', 'end_customer' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['initial_customer'].widget.attrs.update({'style': 'width:100%', 'data-placeholder': 'Select Customer'}) self.fields['end_customer'].widget.attrs.update({'style':'width:100%', 'data-placeholder':'Select end customer'}) and customer_ajax view calls below function... def customer_select2(request): term = request.GET.get("term", None) if term: res = list(Customer.objects.filter(Q(customer_number__contains=term) | Q(customer_name__contains=term)).values('id', 'customer_number', 'customer_name'))[:10] if res: result = [{'id': value['id'], 'text': value['customer_number'] + ' ' + value['customer_name'] } for index, value in enumerate(res)] return JsonResponse({'err': 'nil', 'results': result}, safe=False) return JsonResponse(data={'success': False, 'errors': 'No mathing items found'}) I appreciate for the quick help... if possible, please provide one complete example which explains how form defined and view used … -
Django / Model image field asks for default image
I do not want to add default image for my model in Django. But when I delete default image from the model it says image attribute has no file associated with it. How should I fix it that it would not ask for the image when user does not add an image? class MainPost(models.Model): title = models.CharField(max_length = 50,verbose_name= ('Başlık')) content = models.TextField(verbose_name= ('Yazı')) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(default='profile_pics/default.jpg',upload_to = 'images',blank=True,null=True,verbose_name = ('Resim')) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def save(self,*args, **kwargs): super(MainPost,self).save(*args,**kwargs) img = Image.open(self.image.path) if img.height > 500 or img.width > 500: output_size = (500,500) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('comment', kwargs={'pk':self.pk}) -
CSRF verification failed. Request aborted. Even with {% crsf_token %}
I'm getting CSRF verification failed. Request aborted. after I try signing in, even though I've provided the {% csrf_token %} template tag. templates/registration/login.html {% extends "base.html" %} {% block content %} <div class="container"> <div class="card"> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success"><i class="fas fa-sign-in-alt"></i> Login</button> <input type="hidden" name="next" value="{{ next }}" /> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> </div> </div> {% endblock content %} -
How to call one serializer in another serializer and vice versa using serializers.Serializer in django rest framework?
I want to perform POST rest api call to validate my data in serializer. my JSON data is { "operator": { "type": "or", "query_list": [ { "operator": { "type": "inclusion", "query_list": [ { "operator": { "type": "or", "query_list": [ { "query": { "index": "test", "fields": [ { "field": "name" } ] } } ] } } ] } }] }, "group_by": "name", "severity": 100 } Using minimal serializers.Serializer how can I validate the same nested data? -
AttributeError: 'module' object has no attribute 'model' while model word is not written anywhere,
In djnago I have created Download model and it worked as expected but later when I tried to add new model 'Model' it just showing '''AttributeError: 'Music' object has no attribute 'model'''' . from django.db import models # Download/models.py. class Download(models.Model): name = models.CharField(max_length=50) discription = models.CharField(max_length=50) link = models.CharField(max_length=50) imgages = models.ImageField(upload_to='media/') def __str__(self): return self.name class Music(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.name and here is an admin file from django.contrib import admin from .models import Download,Music # Register your models here. admin.site.register(Download,Music) -
HTML Page gets downloaded on link click
I have created a django web application were I have about 8 html pages. All the html pages seem to work fine, but on some local machines one of the pages gets downloaded upon clicking on the link. It worked fine in my machine. When I deployed it in a private server and tried to click on the same link online, it got downloaded instead of going to the actual page. In linux instead od downloading, it displays the html page. Can anyone tell me what the real issue is? My apologies as I can't post the html page due to issues associated with privacy. However can anyone tell me as to what might be the issue? In other posts I was told that if you'd clear the local machines browsing history this would solve it, but this is not the case when it's in the server. I need a permanent solution. Thanks in Advance -
Overriding Bulk Delete of Models in Django
I wrote a custom delete method for a model. It appears to work with two caveats. When I enter into the model instance inside the Django Admin and click delete, then the file is deleted from AWS S3 bucket (that was the purpose of overriding the method in the first place). The model itself gets removed as well. If I delete via "Delete Selected" bulk feature, then the file lingers in S3, but the instance gets removed from the list of instances of this type. It is my understanding that in the bulk delete, a different (queryset) method is invoked. My question is what is the most effective method of making both single and bulk deletes act the same? Should I be trying to create a custom manager for this model? The model declaration and delete method: from boto3.session import Session from django.conf import settings class Video(models.Model): title=models.CharField(max_length=500) description=models.TextField(default="") creation_date=models.DateTimeField(default=timezone.now) videofile=models.FileField(upload_to='videos/', null=True, verbose_name="") tags = TaggableManager() actions = ['delete'] def __str__(self): return self.title + ": " + str(self.videofile) def delete(self, *args, **kwargs): session = Session (settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) s3_resource = session.resource('s3') s3_bucket = s3_resource.Bucket(settings.AWS_STORAGE_BUCKET_NAME) file_path = "media/" + str(self.videofile) response = s3_bucket.delete_objects( Delete={ 'Objects': [ { 'Key': file_path } ] }) … -
Receiving a text file instead of html file In Django
I currently have a model named Order in models.py class Order(models.Model): order_item = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) order_name = models.CharField(max_length=200) def __str__(self): return self.order_name In the views.py file I have def ordering(request): latest_order = Order.objects.all() context = {'latest_order':latest_order} return render(request, 'users/ordering.html', {'title':'Ordering'}, context) I wanted to show the orders on the html page but all im getting back is a txt file Image of the html file Is there a better approach for me to keep track of a user's order? -
Json Post from Django to Camunda
Further to my earlier post yesterday: Post request to external Rest Service using Django - use returned json to update model I have managed to post data to camunda using Django - request.post. Using the following script: payload = "{\n \"businessKey\": \"SomeValue\",\n \"variables\": {\n \"Organisation_ID\": {\n \"value\": \"SOmeUUID\",\n \"type\": \"String\"\n },\n \"UserID\": {\n \"value\":\"Some User ID\",\n \"type\": \"String\"\n }\n }\n}" However when I start to use variables from the form and format my payload using class StartProcessView(View): template_name = 'startdeliveryphase.html' def get(self,request, *args, **kwargs): form = IntStartDeliveryPhase return render(request, self.template_name,{'form':form}) def post(self,request, *args, **kwargs): form = IntStartDeliveryPhase(request.POST or None) if form.is_valid(): data = form.cleaned_data OrganisationID = data['Form_Field_OrganisationID'] UserID = data['Form_Field_User_ID'] BusinessKey = data['Form_Field_Business_Key'] url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start" payload = {"businessKey":BusinessKey,"variables":[{"Organisation":[{"value":OrganisationID, "type":"String"}]},[{"Startedby":[{"value":UserID,"type":"String"}]}]]} headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data = payload) #print(repsonse.errors) print(response.text.encode('utf8')) return render(request) else: return render(request,self.template_name,{'form':form}) I get an error from the camunda engine:- b'{"type":"JsonParseException","message":"Unrecognized token \'businessKey\': was expecting (\'true\', \'false\' or \'null\')\\n at [Source: (org.camunda.bpm.engine.rest.filter.EmptyBodyFilter$1$1); line: 1, column: 13]"}' the local vars shows the following: ▼ Local vars Variable Value BusinessKey '1qaz' OrganisationID <Organisation: Some Local Authoristy> UserID <Actor_User: me@me.com> args () data {'Form_Field_Business_Key': '1qaz', 'Form_Field_CamundaInstanceID': 'sss', 'Form_Field_Camunda_HRef': 'ss', 'Form_Field_Camunda_TenantID': '22', 'Form_Field_DateCreated': datetime.datetime(2020, 4, … -
How can I retrieve an up-to-date reference to a many-to-many field in an object's save() method in django?
I have a model: class Camera(models.Model): users_allowed_to_view = models.ManyToManyField(User, ...) def save(self, *args, **kwargs): print(self.users_allowed_to_view.all()) super().save(*args, **kwargs) If I use Django Admin to modify a Camera, changing which list of users is allowed to view my camera, and hit Submit, the print statement above returns an old list of users (before the save currently in progress). Even if I move the print statement after super(), I still get an old list of users. Is there a way to get the new list of users that's about to be saved? Also, a related question - I'm pretty sure the .all() above does a DB query. Can I just get a list of IDs referenced by the field without doing a DB query, like you can for a ForeignKey field (by doing foreignkeyfield_id)? -
Django model testing
I want to create some tests in my app, but all the time i got some errors. Now i have information errors Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: setUpClass (comments.tests.test_models.ReplyCommentModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\madas\OneDrive\Pulpit\Code\git-projects\django_tutek\djangoenv\lib\site-packages\django\test\testcases.py", line 1137, in setUpClass cls.setUpTestData() ....... raise TypeError( TypeError: Tried to update field comments.ReplyComment.author_reply with a model instance, <User: >. Use a value compatible with CharField. ---------------------------------------------------------------------- Ran 2 tests in 0.170s FAILED (errors=1) Tests from django.test import TestCase from django.contrib.auth.models import User from blog.models import Post, get_default_user from comments.models import Comment, ReplyComment class CommentModelTest(TestCase): @classmethod def setUpTestData(cls): cls.user = User(first_name='adam', is_staff=True, is_active=True, is_superuser=True) cls.user.save() cls.post = Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) cls.post.save() cls.comment = Comment.objects.create(post=Post.objects.get(title='Pierwszy post'), author='robot', text='ok') cls.comment.save() def setUp(self): self.post = Post.objects.get(title='Pierwszy post') self.comment = Comment.objects.get(id=1) def test_str(self): self.assertEqual(self.comment.text, 'ok') def test_approve(self): self.assertFalse(self.comment.is_approved) self.comment.is_approved = True self.assertTrue(self.comment.is_approved) class ReplyCommentModelTest(TestCase): @classmethod def setUpTestData(cls): cls.user = User(first_name='adam', is_staff=True, is_active=True, is_superuser=True) cls.user.save() cls.post = Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) cls.post.save() cls.comment = Comment.objects.create(post=Post.objects.get(title='Pierwszy post'), author='robot', text='ok') cls.comment.save() cls.reply_comment = ReplyComment.objects.create(comment_reply=Comment.objects.get(author='robot'), text_reply='not_ok') cls.reply_comment.save() def setUp(self): self.post = Post.objects.get(title='Pierwszy post') self.comment = Comment.objects.get(id=1) self.reply = ReplyComment.objects.get(id=1) def test_str(self): self.assertEqual(self.reply.text_reply, 'not ok') Models from django.db … -
Using Django to Query a SQL database
I am very new to Django, but just ran into an issue at work that hopefully we can use Django to resolve. Currently we have a outdated ticketing system that is using sql for the database. We are working on updating the ticketing system. When trying to import the data into the new system (same manufacture just newer system) it does not work. There Tech stated it is something with the way we set up our active directory. They said we can go forth with not updating it and start from scratch or call Microsoft on the issue. Would there be a way I can use Django to quary the ticketing systems database and pull the information to where I can display it using Django?