Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use a button to point to an existing url
I'm new to django, here i've to point a button to an existing url <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li><button type='submit'> Result</button> here i've created a button. how to point this button to the results in url.py urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] -
How can we separate equation smaller separated equation in sympy
Hello I am new to Python and Sympy. i have created small project That working like sympy gamma but i want to separate my equation in to smaller sub parts.is it possible using sympy function. I am Attaching one image for more information about my Problem. -
Django: Order by Aggregate Count in ArrayField
I have a complex problem hope your helps please. I have a model named Place. In this model I have a field named address_component. This field contains array of self: Example, two objects like: Place(id=1, name="USA", types="country", address_components=[]) Place(id=2, name="San Doria", types="city", address_components=[1]) class Place(models.Model): PLACE_TYPES = ( ('country', "Country"), ('city', "City"), ('street', "Street") ) name = models.CharField(max_length=255) types = models.CharField(max_length=100, choices=PLACE_TYPES) address_components = ArrayField(models.CharField(max_length=100), size=10, default=list, blank=True) Now I want to order place queryset by counting the number of places which have the most address_component in it This is my try to get countries queryset order by number of cities in it, but not success Place.objects.filter(types='country').annotate(cities_in_count=Count('address_components')).order_by('cities_in_count') -
Using different content object passed from Views to Template depending on what button user presses
I currently have one model called Comments. After entering in a youtube Channel in a form, the user is taken to the index template that shows all the comments on that youtube channels videos that includes one of three key words (Keyword A, Keyword b , Keyword C). I would like to add a feature so there are three links/buttons on the top of the page (each for one of the keywords). The user can press that link and (without page reload (does this mean I will for sure need ajax?))just see the comments with that keyword instead of all comments with any of the three keywords. I am currently sending four content variable objects from views to the template (one with all the comments, and three other objects each that just contain the comment objects for that keyword). So the template has access to the data I need, I just need to make it so that when one of the links/buttons are clicked it only shows that content. Views def addTodo(request): new_item =Channel(channel=request.POST['channel']) #if channel exists render page with comments if Channel.objects.filter(channel=new_item.channel).exists(): channel_obj=Channel.objects.get(channel=request.POST['channel']) comments_object=Comments.objects.filter(channel=channel_obj) comments_objectA=Comments.objects.filter(channel=channel_obj, key="keywordA") comments_objectB=Comments.objects.filter(channel=channel_obj, key="keywordB") comments_objectC=Comments.objects.filter(channel=channel_obj, key="keywordC") return render(request, 'todo/index.html', {'comments_all': comments_object, 'commentsa': comments_objectA,'commentsb': comments_objectB,'commentsc': comments_objectC}) … -
Problem with creating odject after mirgation from Django1.4 to Django 1.5
After updated django version my tests are not success. Error traceback looks like ERROR:mobile.tokenapi.http:: Traceback (most recent call last): File "/home/y700/projects/otipo-upd/otipo/as_site/apps/mobile/decorators.py", line 12, in wrapped response = func(*args, **kwargs) File "/home/y700/projects/otipo-upd/otipo/as_site/apps/assignation/assignmentstats/views.py", line 75, in settings rate_settings = serializer.save(data, uws) File "/home/y700/projects/otipo-upd/otipo/as_site/apps/assignation/assignmentstats/serializers.py", line 75, in save settings = HourRateSettings.objects.get_or_create(user_settings=uws) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 146, in get_or_create return self.get_query_set().get_or_create(**kwargs) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/query.py", line 501, in get_or_create six.reraise(*exc_info) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/query.py", line 491, in get_or_create obj.save(force_insert=True, using=self.db) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save force_update=force_update, update_fields=update_fields) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/base.py", line 650, in save_base result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/manager.py", line 215, in _insert return insert_query(self.model, objs, fields, **kwargs) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/query.py", line 1675, in insert_query return query.get_compiler(using=using).execute_sql(return_id) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 943, in execute_sql cursor.execute(sql, params) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 127, in execute six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2]) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 120, in execute return self.cursor.execute(query, args) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/home/y700/Env/otipo_upd/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 226, in query _mysql.connection.query(self, query) IntegrityError: (1048, "Column 'rate' cannot be null") For some reason, the rate field value is not passed to the new instance creation function. creation function @token_required @mobile_response def settings(request, workspace_id): uws = get_object_or_404(UserWorkspaceSettings, workspace_id=workspace_id, user=request.user) serializer = RateSettingsSerializer() if … -
Does Django create useless migrations?
When I change the verbose_name attribute of a Django Model, Django will generate a related migration (running make migrations command). However, without applying the migration (migrate command), the change seems to be applied all over the Django project. I think this is because verbose_name is something used at Django level rather than at database level. This makes me wonder: what is the purpose of this migration file? -
Django across joint filter ManyToMany relationship
My models.py: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField() def get_all(): return Question.objects.all() def get_detail(question_id): return Question.objects.get(pk=question_id) class Choice(models.Model): question = models.ManyToManyField(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) my views: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse import datetime from .models import Question, Choice def DetailView(request, question_id): q = Question.get_detail(question_id) choices = Choice.objects.filter(question__question_text = q.question_text) #I also try question__pk == question_id context = {"qs":q, "choices":choices} return render(request, "detail_question.html", context) My url: path('detail/<int:question_id>', views.DetailView, name = 'detail'), My templates: {% extends "base.html" %} {% block content123 %} {% if Questions %} {% for item in Questions %} <p style="color: red;"><a href="{% url 'detail' item.id %}">{{ item.question_text }}</a></p> {% endfor %} {% else %} <h3 style="color: red;">There is nothing</h3> {% endif %} {% endblock %} I try to make a page in which it will display the question and the related vote. I have succeed with ManyToOne relationship with question.choice_set_all in the template. With those code when I run the server it shows the error enter image description here I tried in django shell choice.objects.filter(question__pk = 3/or question_question_text ...) The shell states alo "no such table: polls_choice_question" -
python django url shows old image when exachanging
when running the djangoserver and calling http://127.0.0.1:8000/media/pictures/h2.jpg I get shown the requested image (jpg). Now I exchange the jpg by a file, which is also calles "h2.jpg". BUT when I call the following url again:http://127.0.0.1:8000/media/pictures/h2.jpg it still shows the old picture. How to handle that? Django version 2.1.7 -
Get image before active image in carousel
I want to always display the image before the active image. Here is my code for the carousel. <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ul class="carousel-indicators"> {% for item in page.blogpage_images.all %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ forloop.counter|add:"-1" }}" class="{% if forloop.counter == 1 %}active{% endif %}"></li> {% endfor %} </ul> <div class="blog"> <div class="carousel-inner"> {% for item in page.blogpage_images.all %} {% image item.image fill-650x650 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" alt="{{ img.alt }}"> </div> {% endfor %} </div> </div> </div> /*Add image before here*/ Im sure I need to alter this code below. I have tried changing forloop.counter to 0,2,3 etc but is there a way to make it -1 from active? {% for item in page.blogpage_images.all %} {% image item.image fill-650x650 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-25" alt="{{ img.alt }}"> </div> {% endfor %} -
How I can get chained objects in my project
I have chained models -> Category - Brand - Type. For example : Category : Light vehicle Brand : Volkswagen Type : Passat And I have an Post Model. Question : How i can get chained objects in the form? Code: class Category(models.Model): title = models.CharField(max_length=32) slug = models.SlugField(max_length=32) def __str__(self): return "%s" % self.title class Brand(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=32) def __str__(self): return "%s" % self.title class Type(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = ChainedForeignKey( 'Brand', chained_field="category", chained_model_field="category", show_all=False, auto_choose=True ) title = models.CharField('Модель автомобіля', max_length=32) slug = models.SlugField(max_length=32) def __str__(self): return "%s" % self.title Post Model : class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) ...... def __str__(self): return "{} {}".format(self.brand, self.type) I need to create a form with chained objects. How I can get it ? or how to edit my Post model? -
Expected view Client_view to be called with a URL keyword argument named "pk". Fix your URL conf
Error While using Generic view in Django it Showing Error while using DELETE function.Please anyone give me the syntax of generic views in model set i didnt find any problem but no Delete function **Views.py** *from django.http import Http404, HttpResponse from rest_framework import viewsets, status, generics from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import ClassSerializer from .models import Client class Client_view(viewsets.ModelViewSet, generics.RetrieveUpdateDestroyAPIView): queryset = Client.objects.all().order_by('-Name') serializer_class = ClassSerializer* *lookup_fields = ['Name', 'UserName', 'Mobile', 'Email', 'Address']* **urls.py** *from rest_framework import routers from .views import Client_view router = routers.DefaultRouter() router.register('', Client_view) urlpatterns = router.urls* **models.py** *from django.db import models class Client(models.Model): Name = models.CharField(max_length=15) UserName = models.CharField(max_length=15) Email = models.CharField(max_length=20) Mobile = models.CharField(max_length=10) Address = models.CharField(max_length=20)* **serializer.py** *from rest_framework import serializers from .models import Client class ClassSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Client fields = ['Name', 'UserName', 'Email', 'Mobile', 'Address']* -
How to connect to 3rd party snowflake database using django?
How to create an engine to connect the snowflake db? On Configuring the settings.py, it errors out with below message. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
connection aborted error by Django at "...\python36-32\Lib\wsgiref\handlers.py"
During getting image data(which is in binary) from the mongodb atlas into my Django project , I am facing two kind of problems. In first situation whenever the http://127.0.0.1:8000/ is searched, the data will gets populated in the html template as required along with a long trace like shown here. In second situation whenever the a GET request is sent, the browser keeps loading infinitely by showing nothing in either cmd nor in browser. And before posting here, I googled the error and visited github's django helpdesk and from that I am unable to figure out the root of the problem. Here is a code to review views.py from django import template from django.shortcuts import render import gridfs import pymongo import random register = template.Library() client = pymongo.MongoClient('mongodb+srv://danial:1234@wearit-qyueb.mongodb.net/test?retryWrites=true&w=majority') db=client.scraped_data.all_brands fs = gridfs.GridFS(client.scraped_data) # Create your views here. def index(request): template='products/products.html' return render(request,template,{'documents': get_random()[:20], 'categories':categories(), 'brands': brands()}) def categories(): raw_data=get_random() all_categories=[] for doc in raw_data: if doc.get('cat_name') not in all_categories: all_categories.append(doc.get('cat_name')) return all_categories def query_form(request): if request.method == 'GET': query_dict=request.GET select_category= query_dict.__getitem__('category-selected') min_price=query_dict.__getitem__('min-price') max_price=query_dict.__getitem__('max-price') listOfDocumets=[] if min_price!='' or max_price!='': listOfDocumets=range(min_price,max_price, db.find({'cat_name': select_category})) else: listOfDocumets=list(db.find({'cat_name': select_category})) random.shuffle(listOfDocumets) return render(request, 'products/products.html',{"documents": listOfDocumets, 'categories':categories(), 'brands': brands()}) def search_query(request): if request.method == 'GET': query_dict=request.GET select_brands= … -
Django Jinja How to check whether the user has any rights through the template?
I have a menu whose parts are displayed depending on the rights. I configured it. I want to check if the user has any rights in principle, if they do not, then the menu will not reach the moment of drawing. Something like this: {% if perms.registration2 == NUll %} # render something {% endif %} This code returns set() not NULL or '': {{ perms.registration2 }} How can I do such a check? -
How to resolve this error 407 during login?
I tried to check by printing where could be the cause of the problem. It shows that user_id and password were there but it cannot proceed after that. def login_request(request): if request.method == 'POST': user_id = request.POST['user_id'] password = request.POST['password'] user = authenticate(user_id=user_id, password=password) if user is not None: login(request, user) return redirect("/index") else: messages.info(request, 'Invalid Credentials') return redirect('login_request') else: return render(request, 'login.html') urls.py path('login_request/', views.login_request, name='login_request'), -
how to include JavaScript class name in django html tag
i want to show slider images in the Django template page using javascript. i tried to adding java script code and html code in django template page Javascript code: var slideIndex = 1; showDivs(slideIndex); function plusDivs(n) { showDivs(slideIndex += n); } function showDivs(n) { var i; var x = document.getElementsByClassName("mySlides"); if (n > x.length) {slideIndex = 1} if (n < 1) {slideIndex = x.length} for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } x[slideIndex-1].style.display = "block"; } HTML Code <img class="mySlides" src="{% static "images/cropped-foodimage3.jpe" %}" style="width:100%"> <img class="mySlides" src="{% static "images/cropped-foodimage3.jpe" %}" style="width:100%"> <img class="mySlides" src="{% static "images/cropped-foodimage3.jpe" %}" style="width:100%"> <button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">&#10094;</button> <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#10095;</button> </div> -
How to check if items in cart exists or not
I have a Cart model like this class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='items', null=True) quantity = models.PositiveIntegerField(default=1) serializers.py class CartSerializer(serializers.ModelSerializer): image = serializers.ImageField(source='product.image', read_only=True) name = serializers.CharField(source='product.name', read_only=True) price = serializers.DecimalField(source='product.price', read_only=True, max_digits=10, decimal_places=2) class Meta: model = Cart fields = ['id', 'user', 'product', 'image', 'name', 'price', 'quantity'] views.py class CartApiView(generics.ListCreateAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer I have used a number of methods that check whether product in cart exists or not, but Any of them did not work in my case. Can you suggest any methods please that check product in cart? Here in the Cart model quantity is default if user does not want to add quantity it should take 1 automatically. Thanks in advance! -
Maintain the media files after build with Docker Container - Django
I am using Django as a Web Framework. Azure NGINEX as WebServer. My Project is deployed with Docker Containers. In my Django project root structure will be as follows: root: - app1 - app2 - media whenever saving images, it will correctly save under media folder. But whenever doing "docker-compose up" it will replaces the source code, so that my media folder will be cleaned up everytime. In my settings.py file, I have added as follows: MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = 'media/' Kindly help me to maintain the media files with Docker based Environment -
Extracting a Outer Join from Django ORM
I have the following two models in my Project. class Blog(models.Model): title=models.CharField(max_length=20, blank=False, default='') content=models.CharField(max_length=2000, blank=False, default='') class UserLikedBlogs(models.Model): blog=models.ForeignKey(TTSServiceModel.TTSService, on_delete=models.CASCADE, blank=True, null=True) user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) All Users who login are able to see blogs of other users. The current logged in user can "like" a certain blog, which adds an entry in the UserLikedBlogs table. I wish to now display all the blogs present in the system to a logged in User, but I also wish to show blogs that the User has liked. I understand that this should get all entries from the Blog table, with additional columns from the UserLikedBlogs table, where the data is present only for blogs liked by the user, not otherwise. This is a classic case of a Outer Join where, common elements between two sets are associated with all elements from one of the tables participating in the join. I have been reading documentation from django and on SO, but i cant seem to find the right syntax to do this. My current hacky way of doing this is to user Pandas and join the two data sets in Python, rather than a query. I am certain there is a better way, but … -
How to calculate video length and Thumbnail of video in django
I doing django project. I'm trying to calculate length of upload video and tring to create Thumbnail of the video. How to do this. models.py class Video(models.Model): video_format = models.CharField(max_length=15, blank=True, null=True) video_name = models.CharField(max_length=15, blank=True, null=True) video_size = models.CharField(max_length=15, blank=True, null=True) video_duration = models.IntegerField(blank=True, null=True) created_date = models.DateTimeField(default= datetime.now(), blank=True, null=True) status = models.CharField(max_length=15, blank=True, null=True) thumbline = models.CharField(max_length=15, blank=True, null=True) views.py def home(request): if request.method == 'POST': video = request.FILES.get('video') video_file = FileSystemStorage() file_upload = Video(video_file= video_file.save(video.name, video)) file_upload.save() return render(request, 'home.html', {}) -
Cannot see 'self' reference options for some of my model fields in Admin backend
I have an application that holds a number of posts/documents. I have a model class of Document and this document has multiple self-reference fields such as parent_document, related_checklist and explanatory_material which are a ManyToMany. When accessing the model from the backend to do edits on documents, I found that I cannot select a 'self' field anymore, the options have disappeared! I had not touched related_name and they definitely used to work and show up, I am unsure what have happened to cause this. I tried changing related_name afterwards, but that still did not work. To make matters stranger, when I added a test_fieldthat also has a 'self' reference, it worked just fine, as shown in the attached screenshot. Additionally, documents that had documents referenced to those fields remain added to the list (check Explanatory Material in screenshot) but I cannot select anymore values, because they are not there! I have tested that when I uncheck anything and save, that option disappears from the list. Also, if I added a document using the "+", it adds the new document to that list just fine, too. One thing to note is that I have a different application attached to that Django app … -
How to design data-model for dynamic user structure in Django?
I have a client who wants a dynamic data-model structure in their web-application and I would like to know how to design the data-model structure for this, or if I am doing it correctly. This was actually pretty well built out but they changed their mind and wanted to add dynamic employee types (employee types which can be added/removed by the company admin). They would like for a casino to register for their site and have one casino admin that can create unlimited employee types. For this I am restricting the Admin page so they can edit certain attributes. Each employee type will be assigned one of two Groups: Supervisor or Non-Supervisor. From there I will handle authentication and permissions. class Casino(models.Model): """ Store casinos, casino info and meta-data, related to: :model: 'casino.CasinoStyle' """ name = models.CharField( max_length=128 ) employee_type = models.ManyToManyField( EmployeeType, blank=True ) class EmployeeType(models.Model): """ Stores user employee type. """ employee_type = models.CharField( max_length=32, default='Dealer' ) group = models.ForeignKey( Group, on_delete=models.CASCADE ) class User(AbstractUser): """ Store users, user-settings and meta-data, related to: :model: 'casinos.Casino' :model: 'auth.Group' :model: 'users.EmployeeType' """ name = models.CharField( max_length=50 ) casino = models.ForeignKey( Casino, on_delete=models.CASCADE ) employee_type = models.ForeignKey( EmployeeType, on_delete=models.CASCADE, blank=True ) … -
How to fix crontab in Django?
I had a problem when implementing django-crontab in virtualenv. I have created a cron.py file in my Django app to send an email every minute, and when I ran it, I saw the running processes but the script was not executed. I'm using macOS Catalina and python3.7.4. I ran my django app in a virtualenv. In the past, I've tried: in 'django_crontab', ...) CRONJOBS = [ ('*/5 * * * *', 'mypapp.cron.send_email', '>> /tmp/file.log') ] CRONTAB_COMMAND_SUFFIX = '2>&1' this is my cron.py file (I have tested the script without crontab and it worked). import smtplib, ssl def send_email(): port = 465 smtp_server = "smtp.gmail.com" sender_email = "sender@gmail.com" receiver_email = "receiver@gmail.com" password = "" message = """\ Subject: Hi there This message is sent from Python.""" context = ssl.create_default_context() with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: # server.login(sender_email, password) # server.sendmail(sender_email, receiver_email, message) Then I run python manage.py crontab add and python manage.py runserver. I saw the contab was running when I typed crontab -l and this line showed up on the terminal: */1 * * * * /Users/james/Documents/pj_django/myenv/bin/python /Users/james/Documents/pj_django/myenv/manage.py crontab run 6da410d117f9ce8casc7c6cd8c8dc78 >> /tmp/file.log 2>&1 # django-cronjobs for firstproject But the script was not running. After that, I checked my file.log … -
How to keep fields in user model in Django and add some extra field
Hi I want to add some extra fields to my user model and I read custom user model with inherit from abstractuser class but when I implement user model Django username field and etc was gone. a solution is use another model like profile but I want add extra fields to Django user model. Is this possible? Thanks , please don't give me down vote for this question -
django-admin: postgresql trigger function
i have this 3 table in django admin, if i select the section in table (student enrollment record), it will search the section in another table name (subject section teacher) then it will automatic save the search result in the another table name (student enrolled subject) using trigger function in postgres or is there any solution?