Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get the url for a model?
Given the following situation: # models.py class Book(Model): pass # views.py class BookDetail(DetailView): model = Book # books/urls.py urlpatterns += [path('detail/<int:pk>', BookDetail.as_view(), 'book_detail')] # page/urls.py urlpatterns += [path('books/', include('books.urls'))] I can load the detail view for the object with the private key id 42 at /books/detail/42/. If I am in another request with a completely different path and hold a reference to the object with the private key id 42, is there an "official" or builtin way to generate the url /books/detail/42/? Preferably outside of templating, so I can respond with a JSON. Or is the idiomatic way to parametrize the path elements (books and detail) and just rebuild it myself? -
How do i make multiple images upload in django (2.2) in one form with two data methods?
How do I make a multiple images upload to database in django? I have 2 models: Ads, Images models.py class Ads(models.Model): title = models.CharField(max_length=85, blank=False) class Images(models.Model): ad = models.ForeignKey(Ads, related_name='images', on_delete=models.CASCADE) image = models.ImageField(blank=True, upload_to='') thumbnail = models.BooleanField(default=False) views.py class CreateAd(CreateView): model = Ads form_class = CreateAdForm success_url = reverse_lazy('index') forms.py class CreateAdForm(forms.ModelForm): class Meta: model = Ads fields = ('title',) class ImageForm(forms.ModelForm): class Meta: model = Images fields = ('image', ) -
How to update queryset value in django?
I have written a python script in my project. I want to update the value of a field. Here are my modes class News_Channel(models.Model): name = models.TextField(blank=False) info = models.TextField(blank=False) image = models.FileField() website = models.TextField() total_star = models.PositiveIntegerField(default=0) total_user = models.IntegerField() class Meta: ordering = ["-id"] def __str__(self): return self.name class Count(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE) rate = models.PositiveIntegerField(default=0) def __str__(self): return self.channelId.name class Meta: ordering = ["-id"] This is my python script: from feed.models import Count, News_Channel def run(): for i in range(1, 11): news_channel = Count.objects.filter(channelId=i) total_rate = 0 for rate in news_channel: total_rate += rate.rate print(total_rate) object = News_Channel.objects.filter(id=i) print(total_rate) print("before",object[0].total_star,total_rate) object[0].total_star = total_rate print("after", object[0].total_star) object.update() After counting the total_rate from the Count table I want to update the total star value in News_Channel table. I am failing to do so and get the data before the update and after the update as zero. Although total_rate has value. -
How can we make a conformation dialogue box using JavaScript and Django?
Can any one help me in completing the javascript conformation box when ever we click the delete comment anchor tag? <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'comment-update' comment.id %}">Update Comment</a> <a class="btn btn-danger btn-sm mt-1 mb-1" id="delete-object" href="{% url 'comment-delete' comment.id %}">Delete Comment</a> <script type="text/javascript"> var elm = document.getElementById('delete-object'); var objectID = elm.getAttribute('comment.id'); var resultDiv = document.getElementById('result'); elm.addEventListener('click', function() { var ask = confirm('Are you sure want to delete the comment?'); if (ask && objectID) { var r = "Page will be redirected to </object/delete/" + objectID + "/>"; resultDiv.textContent = r; } else { resultDiv.textContent = "User cancelled the dialog box..."; } return false; }); </script> {% endif %} -
Django Celery how to have more than one CELERY app
Using Django 2.2, python 3.6 and celery 4.3.0 I have an external module that defines a celery app to communicate to a worker on server A with rabbitMQ (AMPQ with it's own user, password and vhost) If I use this celery app OUTSIDE the django project, it works as intended. For reference here is the external module tasks.py: import traceback from celery import Celery from worker_functions import cluster_call BROKER = "amqp://user:password@serverA_ip/vhost" app = Celery('lsworker', backend='amqp', broker=BROKER) app.conf.update(CELERY_ACCEPT_CONTENT = ['json']) app.conf.update(CELERY_TASK_SERIALIZER = 'json') app.conf.update(CELERY_RESULT_SERIALIZER = 'json') @app.task def bridge(account, cmd, params): return cluster_call(account, cmd, params) I have a celery app within the django project. It follows that structure: proj/settings.py app/tasks.py with the following tasks.py: # Create your tasks here from celery import shared_task @shared_task def test_comm(string): return string Where CELERY_BROKER_URL='amqp://user:password@serverB_ip/vhost' in settings.py If the django app does NOT use the external module mentionned earlier, it works as intended. However, if I try to use both within the django project, it does not work. The app from the external module overrides the one from django so regardless of which function tasks is called, all tasks gets sent to the same external worker, the one from the external module rather than it's respective … -
Django: setting class variable instead of working with redundant local variables in 'CreateView'
I am new to python django. I have created a view class inherit from django.views.generic.CreateView All is working fine, but I have two times the following line of code in two different class methods: event = get_object_or_404(Event, pk=self.kwargs['pk']) I have already tried to set a class variable in the init method, but all I have tried end up in error messages. Here is my class with the redundant two lines: class StaffCreateView(CreateView): model = Staff form_class = StaffForm def get_initial(self): """ Returns the initial data to use for forms on this view. """ initial = super().get_initial() event = get_object_or_404(Event, pk=self.kwargs['pk']) initial['country'] = event.default_country_of_staff initial['max_number_of_shifts'] = event.default_max_number_of_shifts_per_staff return initial def form_valid(self, form): event = get_object_or_404(Event, pk=self.kwargs['pk']) form.instance.event = event return super().form_valid(form) Can someone guide me how to do it the correct way? -
Configure Nginx to serve Angular front end, Django Rest Framework backend on same server
My site's frontend is built with Angular 7, and the back end is built with Django Rest Framework. It's all running docker-compose, and I'm trying to serve the entire site through Nginx. The basic premise of my configuration is this: If the request includes a url with /api/ or /admin/ in it, allow gunicorn to handle the request. If the url is anything else, send it to the root index.html so that Angular can handle the routing. The root url / should serve my pre-compiled javascript via the index.html. With the following Nginx config, I can visit all of the Angular routes. I can visit the admin page and my browsable API. However, when I go to /admin, all of the static files return a 404 error. Do you see the issue? Thanks! upstream my_app { server django:8000; } server { listen 80; location /staticfiles/ { alias /usr/src/app/staticfiles/; } location ~ (api|admin) { proxy_pass http://my_app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location / { root /usr/src/app/staticfiles/; try_files $uri $uri/ /index.html; } } -
How to link one page to another by hyperlink in Django?
I want to create a Home page through which i could go to the other pages that i have created. Suppose i have a home page in which i have two options: 1.My achievements 2.My work Now, from this home page by click onto the My work option i want to go to another page where i have the information related to my work, how can i do so? My home page html is : {% extends 'base.html' %} {% block content %} Home Page My Achievements My Work {% endblock %} The base.html: {% block content %} {% endblock %} </body> </html> -
Django (DRF) - Filter parent in recursive field based on child properties
I have a model that's recursive. class Organization(models.Model): business_name = models.CharField(max_length=100, unique=True) # recursive relationship organization = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='organizations') I have another model that is a child of this recursive model and it can be a child at any point in the tree. class Store(models.Model): registration_no = models.CharField(max_length=8, default=increment_registration_no, unique=True) organization = models.OneToOneField(Organization, on_delete=models.PROTECT, related_name='store', null=True) In the UI for this application the list of stores is listed in a recursive table with the organization headers above. We have a serializer specifically designed for this list. When the user is looking at this list they can filter by Organization and Store properties. class StoreSerializer(serializers.ModelSerializer): registration_no = serializers.CharField(read_only=True) class Meta: model = Store fields = ('id', 'registration_no') class StoreFilterSerializer(serializers.ModelSerializer): registration_no = serializers.CharField(read_only=True) def to_representation(self, value): # Turn single object into a query so that we can use django filters queryset = Store.objects.filter(pk=value.id) registration_no = self.context['request'].query_params.get('registration_no', None) if registration_no is not None: queryset = queryset.filter(registration_no__icontains=registration_no) if queryset: # Represent object with serializer defined above return StoreSerializer(queryset[0]).data else: return {} class Meta: model = Store class OrganizationsSerializer(serializers.ModelSerializer): store = StoreFilterSerializer(read_only=True) organizations = RecursiveField(many=True) class Meta: model = Organization fields = ('id', 'business_name', 'organization', 'organizations', 'store') As you can see above, … -
How to indicate which model's field raised a ValidationError?
Let's say I have a simple Django model: class Transaction(models.Model): description = models.CharField('description', max_length=150, validators=[MinLengthValidator(2, 'Description\'s min length is 2'), ]) amount = models.DecimalField('amount', max_digits=10, decimal_places=2, validators=[MinValueValidator(1, 'Min value is 1'), ]) user = models.ForeignKey(User) And I'd like to have a unit test, which precisely checks whether ValidationError is raised by description field and not by amount field (or any other). So I have this piece of test, which in a primitive way checks if description field is present in e.exception: def test_model_requires_description_min_2_characters(self): with self.assertRaises(ValidationError) as e: Transaction.objects.create(description='a', amount="50", user=self.user1) err_dict = eval(str(e.exception)) self.assertIn('description', err_dict.keys()) But I don't really like to use eval() and I believe there is more elegant way to indicate the source of ValidationError. How can I do this? -
Using Django with a legacy database (mysql) - is it possible to import data after creating a model
I have a Django project and have been trying, with varied success to connect to a legacy database. As Django is best used with new models and implementing a project from scratch, I assume it is possible to create models based on the legacy database (manually) and once they have been set up, import the data from the legacy database directly to the database, but that for some reason, this is not advised. Assuming, however, that the above is possible and perfectly acceptable, what is the benefit of using the python manage.py inspectdb command to retrospectively create models. Is it because creating it manually will not provide a correct model, or is it simply to save time and is just another option? My main question is regarding the viability of creating models manually, and then importing large amounts of legacy data directly into the mysql database. In this case, creating a model, based on the legacy data, for a 'student table', and then importing in mysql all the student data. Will this cause any issues, or am I missing something fundamental here? Any advice would be gratefully received. -
Include HTTPResponse object with template? Trying to displaay pyplot to webpage
I am trying to display a pyplot chart to a webpage along with a template including other variables. Right now the pyplot image is being saved with PIL to the response object, however, I want more than just the image to be in the response. Is there a way to append the HTTPResponse object as a variable on a template? I've tried using Jquery to request the plot after loading the rest of the template but the plot takes a while to render and ends up being displayed a long time after the rest of the template. I want the image to be loaded with the rest of the template buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) im = Image.open(buf) response = HttpResponse(content_type="image/png") im.save(response, "PNG") buf.close() plt.close(fig) return response -
Reverse lookup value of ForeignKey (Child to Parent)
I'm in need of accessing a value the reverse way using ForeignKey. I want to go from child model Category to parent model Post and grab the value title into my template I've tried category.posts.title but it isn't showing any success for me. The main purpose of this is to create a <div> for each Category and list the blog posts with that category down below. Models: class Category(models.Model): name = models.CharField(max_length=30) class Post(models.Model): slug = models.SlugField(max_length = 250, null = True, blank = True) title = models.CharField(max_length = 250, default="Blog Post") body = models.TextField() created_on = models.DateTimeField(null=True) last_modified = models.DateTimeField(null=True) categories = models.ForeignKey('Category', related_name='posts', default="2", unique=False, on_delete=models.CASCADE) View: def blog_index(request): posts = Post.objects.all().order_by('-created_on') categories = Category.objects.all() context = { "posts": posts, "categories": categories, } return render(request, "blog_index.html", context) Template <div class="row"> <div style="padding: 0px;" class="col l12"> {% for category in categories %} <div class="col l3"> <div style="background-color: white; box-shadow: 0 1px 15px 1px rgba(62,57,107,.07); border-radius: .6rem;" class="card "> <div class="card-body text-center"> <div class="mb-4 pb-3"><i class="ti-briefcase text-muted font-40"></i></div> <h5 class="mb-3"> <a href="{% url 'blog_category' category %}">{{ category.name }}</a></h5> <div><a class="d-inline-flex align-items-center text-danger" ><a href="{% url 'blog_detail' category.name category.posts.slug category.posts.pk %}">{{ category.posts.title }}</a><i class="material-icons"> keyboard_arrow_right </i></a></div> </div> </div> </div> {% endfor … -
Update records with list of data in django model
I want to update the list of records in the my model. These are my data and my model: #list that capture from website admin: {'1': ['present', 'study'], '2': ['study'], '3': ['present'], '4': ['no-present', 'no-study']} #models.py class Rollcall(models.model): student = models.ForeignKey(User) session = models.ForeignKey(CurriculumSession) is_present= models.BooleanField(default=False, ) is_study = models.BooleanField(default=False,) In dict: Key: is user ID, value: is the data that I receive from user. Each user can be present(in something like course) and can study. So we can have 4 situation. I want to save all of item in dict as a records in my model. (Notice: that I wnat this update for specific rollcall that have specific session) How can I do this? -
how can I check two date-time are equal in django templates
I am trying to check this condition that some date-time equal with date-time that come from db before that i check one time is larger or smaller from another but i can't find out two time are equals or not here is my code that not working: {% for order in orders %} {% if order.hour_id.open == dic and order.status == 'Reserved' %} <div class="col late pastDate" data-dayid="22" data-timeid="38" data-price="65000" data-time="38" data-day="1" data-start="3" data-end="9" data-date="1398/2/14">reserved </div> {% set x = False %} {% elif order.hour_id.open == dic and order.status == 'Reserving' %} <div class="col late onrezerv" data-dayid="22" data-timeid="41" data-price="65000" data-time="41" data-day="1" data-start="39" data-end="45" data-date="1398/2/14">reserving {% set x = False %} {% endif %} {% endfor %} -
NoReverseMatchat /
I've got this problem. When I comes to home I get NoReverseMatch at /. Please help. After I get this I went back to my old code (before I done it) but I still get it. # urls urlpatterns = [ url(r'^$', v.index, name='index'), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) def index(request): # posts = Post.objects.filter(published=True).order_by('-pub_date')[0:3] return render(request, 'index.html',) # add {'post': posts} -
How to align spans in one line
Hello guys I have divs in a django template which are created by a Django for loop I have 2 spans in one div divided by a lot of whitespace, what I want to do is to align the second spans the spans with the tab class in one line , how do I accomplish this ? I have tried adding padding, margin but it did not work HTML: <div> {% for entries in mylist %} <div class="ladder"> <span class="player"> {{ entries.0 }}</span> <span class="tab"> {{ entries.1 }} </span></div> {% endfor %} </div> CSS: player { margin-left: 20px; border-right: solid 2px red; } .ladder{ width: 30%; border: solid 2px blue; margin-left: 20px; margin-bottom: 30px; } .tab { margin-left: 40%; margin-right: -10px; background-color: red; } -
ValueError at /accounts/profile/ The 'image' attribute has no file associated with it
This error occurs when a user is either not a superuser or doesn't have a profile image submitted via userprofile in admin. ValueError at /accounts/profile/ The 'image' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ Error during template rendering In template /Users/joseph/Documents/django/tutorial/accounts/templates/base.html, error at line 17 The 'image' attribute has no file associated with it. 7 8 9 10 11 12 13 14 15 16 Currntly 17 18 19 20 {% if user.is_authenticated %} 21 22 23 24 Explore 25 26 27 models.py: class UserProfile(models.Model): user = models.OneToOneField(User, models.CASCADE) description = models.CharField(max_length=100, blank=True, default='') city = models.CharField(max_length=100, blank=True, default='') website = models.URLField(blank=True, default='') contactNumber = models.IntegerField(blank=True, default=0) image = models.ImageField(upload_to='profile_image', blank=True) def __str__(self): return self.user.username Why does this happen? It can't actually be base.html? If there is anything else that needs adding to help solve the problem, please let me know .Thanks -
Saving Json datas into manytomany relationship in postgresql
I have set up a Jupyter Notebook for a Machine learning project using Ibm Watson-Studio and I'm trying to find a way to save my predictions which are in a Json format into a ManyToMany relationship in my Postgresql database. For better understanding the goal is to do this: Based on the description of a product, predict in which categories(which I call tags) this product should fit into and for each classes, if the confidence score is equal or higher than 0.30, save the classes as a tag into the ManytoMany table to his related product. ps; I use the Django-taggit modules to generate this ManytoMany relation and to create the tags. I have a text classifier that is connected to my Postgresql database so that I can apply this model to my datas from the description column. I'm able to get accurate predictions for each descriptions that I have in a Json format as you can see below. My Notebook: from watson_developer_cloud import NaturalLanguageClassifierV1 import pandas as pd import psycopg2 import json # Connect to my Postgresql database conn_string = 'host={} port={} dbname={} user={} password={}'.format('151.201.17.226', 5432, 'dbsearch', 'locq', 'mysecretpass***') conn_cbedce9523454e8e9uyt455d4c1a52e = psycopg2.connect(conn_string) # Select the description column with the … -
Login with diferent response
For requests from the programmer who is consuming my API, I requested that in the login in case of not adding the email and password in the correct way I returned an error 401 instead of a 400. -
How to create a pop up in django?
I have a subscribe button in my page. When the subscribe button is clicked, a pop up window should be generated asking for email, name. When the email is entered and is submitted, the email goes to the database and is redirected to previous page. Here is something I tried but the subscribe button doesn't respond when clicked. models.py class Subscription(models.Model): fullname=models.CharField(max_length=30) mailid=models.EmailField() forms.py from .models import Subscription from bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin class SubscriptionForm(PopRequestMixin, CreateUpdateAjaxMixin): class Meta: model = Subscription fields = ('fullname', 'mailid') widgets = {'fullname': forms.TextInput(attrs={'placeholder': 'Full Name'}), 'mailid': forms.TextInput(attrs={'placeholder': 'Email'}), } views.py from django.contrib.messages.views import SuccessMessageMixin from django.urls import reverse_lazy from django.views import generic from bootstrap_modal_forms.mixins import PassRequestMixin from .forms import SubscriptionForm class SubscriptionView(PassRequestMixin, SuccessMessageMixin, generic.CreateView): form_class = SubscriptionForm template_name = 'subscribe.html' success_message = 'You are now subscribed!' success_url = reverse_lazy('home') urls.py urlpatterns = [... path('signup/home/',views.home, name='home'), path('subscribe/', views.SubscriptionView.as_view(), name='subscribe'), ...] subscribe.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% load widget_tweaks %} <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h3 class="modal-title">Subscribe</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ form.as_p }} </div> <div class="modal-footer"> <button type="button" class="submit-btn btn btn-primary">Subscribe</button> </div> </form> </head> <body> </body> </html> At the place where the … -
ModuleNotFoundError: No module named 'django' set PYTHONPATH but same error
I am following a tutorial found at: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment I have installed Python 3.7.1. When I try to install Python 3.7.2 the terminal tells me I already have the latest version. I set up a virtual environment then install Django 2.2.1. Following the instructions in the tutorial I run: $ python3 manage.py runserver and I get this message: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc 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? then I set: $ export PYTHONPATH=/home/<username>/Desktop/Django-Applications/django_test/mytestsite1 but I still get the same error. -
How to fix 'Post with this User already exists' error on Django while trying to add a new post?
I have a create_post view through which I try to add a new post to the blog I am working on. However, when I hit 'Submit' after filling out the form which includes User(a dropdown menu of all of the registered Users), Title, and Text, I get Post with this User already exists. As can be seen below, post.user has a foreignkey, User. Isn't suppose to mean that one Post can have only one user(author), and A User may have many posts. Why am I not allowed to add another post the same user? Also, how do I utilize Django's built-in components to display a message such as 'Posting as {{user.username}} or Commenting as {{user.username}}' if user is authenticated. Instead of having to write down a username in a textbox while leaving a comment, I would like to fetch username if user's logged in and not ask user to write a username in a textbox for I believe it makes no sense. I am thinking I may need to use widgets in forms.py and use HiddenInputs() maybe? I apologize if I violate any community rules since I have recently joined this community and am still trying to figure out the … -
Python3: f-string {} symbols screening
i want to use f-string in my python code to write some json, but got a problem with screening {} symbols. What the correct way to screen lonely { } symbols? For example i want to write: data = f'{[{{prod_id},{quantity},{size}}]}' I cant get how to write it correctly, and basic python screening not working for me for some reason here. -
Setting up Django in Heroku database error
Is my first time using django, and i wanted to deploy it in heroku. i am getting the next error "config['DATABASES']['default'] = dj_database_url.config(conn_max_age=MAX_CONN_AGE, ssl_require=True) TypeError: config() got an unexpected keyword argument 'ssl_require'" when i run heroku run python manage.py migrate I have tried doing the deployment following this guide that sould make the local database be sqlite3 and production postgresql https://medium.com/@BennettGarner/deploying-django-to-heroku-procfile-static-root-other-pitfalls-e7ab8b2ba33b i would actually like to set up both databases to postgresql, because i have it install in my local machine This is settings.py import os import dj_database_url import dotenv import django_heroku DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'users.apps.UsersConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myapp.urls' WSGI_APPLICATION = 'myapp.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = {'default': {}} db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' AUTH_USER_MODEL = 'users.CustomUser' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' CRISPY_TEMPLATE_PACK = 'bootstrap4' django_heroku.settings(locals()) del DATABASES['default']['OPTIONS']['sslmode'] This is the .env …