Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT FOUND Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js IN A DJANGO PROJECT
Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js while submitting a form in a django project , this comes up and no data is stored in database. GET /docs/4.3/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 3019(this comes in the terminal) -
How do I solve the error on scrapy.clawer
Now, I develop web app with django and scrapy that has function of searching English word. When I input word with form on django, scrapy get the mean of transltated word into Japanese from internet dictionary. After inputting word ,activating scrapy and stop runserver, happning the error following: [scrapy.crawler] INFO: Received SIGINT, shutting down gracefully. Send again to force Error: That port is already in use. I can stop it by using command kill , but it is inconvinient to input command everytime happens error. So I want to know how to solve it like adding code etc. following is my code . def add_venue(request): submitted = False if request.method =='POST': form = VenueForm(request.POST) if form.is_valid(): name = form.cleaned_data['word']#入力した単語 queryset = Newword.objects.filter(word = name) print(queryset) if queryset.exists(): #コード未記入 else: #print(name) process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(WordSpider, query=name)#入力した単語をnameに入れて、スクレイピングを実行。 process.start() # the script will block here until the crawling is finished form.save() return HttpResponseRedirect('/list/') else: form = VenueForm if 'submitted' in request.GET: submitted = True return render(request, 'form.html', {'form':form, 'submitted':submitted}) python3 manage.py runserver --nothreading --noreload django project is in scrapy project. -
How to create and save that file to Django model?
I want to create a file and save it to Django model within a view without creating any temporary files or anything like that. I plan to write a .txt file that contains information and I want to save the .txt file in the Django model. Does anyone know how to do this? Thank you -
How can I model a field to accep structures of the form [{names: [String!]!, scope: String!}]?
I want to add to the existing model myModel, a new field x, which can store structures of the form [{names: [String!]!, scope: String!}]. I also have to model the graphql mutation to update myModel, but I don't know how. I thought about the following solutions, but they don't seem to be the best: class myModel(models.Model): x = ArrayField(JSONField(default=dict), default=list, blank=True, null=True) class MyStructure(graphene.InputObjectType): names = graphene.List(graphene.NonNull(graphene.String, required=True), required=True) scope = graphene.String(required=True) class UpdateMyModel(ClientIDMutation): x = graphene.List(MyStructure) # x = graphene.List(graphene.JSONString) ? # x = graphene.List(GenericScalar) ? -
Stock Reduction
We are selling on an e-commerce platform and there is a part of the system where we have stocks and we want to experience a decrease in stocks in every sale. However, in the current system, for example, if we have 5000 ziplock bags, we use 2 pieces in one product and only one in the other. In such cases, since it would be very amateurish to write if for each product separately, what approach should we take for a more effective solution? My example code is: reduction_qty = { "Handmade": 1, "Vida": 1, "Dübel": 1, "Kilitli Poşet": 2, } other_items = Inventory.objects.filter( name__in=list(reduction_qty.keys())) for item in other_items: qty = reduction_qty.get(item.name) item.quantity = item.quantity - (transaction.quantity * qty) updated_items.append(item) -
How to fastly update field from a related model in django
I wanted to update a few milion records with a value from a related record using Django queryset but I got stuck on django.core.exceptions.FieldError: Joined field references are not permitted in this query Before I did it with a Subquery, but it was too slow. All I want is to execute this simple query, but wasn't able to find a Queryset equivalent for it, so I had to go with raw SQL. update card_cardtransaction set clearing_date = api_invoice.date_activated from card_cardtransaction ct join api_invoice on ct.invoice_id = api_invoice.id where ct.date_created > '2022-05-17' and id in %ids Any ideas how to compose this query using only queryset methods? This is the closest I was able to come with, but still with the error above. CardTransaction.objects.filter(id__in=ids) .select_related('invoice') .update( clearing_date=F("invoice__date_activated") ) -
Django do not auto escape characters
I have a code to play video in a django app <video controls autoplay id='vid' muted > <source src="{% static 'vids/videoplayback.mp4#t=10,30' %}" type="video/mp4"> </video> The problem is that django auto escapes the characters and gives an error GET http://127.0.0.1:8000/static/vids/videoplayback.mp4%23t%3D10%2C30 404 (Not Found) How do I prevent this from happening? -
Why is the entry not being added?
i am trying to add entries without using forms.py. But when saving, it redirects me to a non-existent page and does not save the product. Maybe a simple question but it puzzled me views def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.save() return render(request, 'create.html ') html <form action="save" method="post"> {% csrf_token %} <input type="text" placeholder="Название" name="title"><br> <textarea placeholder="Текст статьи" rows="8" cols="80" name="text"></textarea><br> <input type="date" name="date"><br> <button type="submit">Добавить статью</button> </form> models class Posts(models.Model): title = models.CharField('Название', max_length=100, blank=True) anons = models.CharField('Анонс', max_length=250, blank=True) text = models.TextField('Текст статьи', blank=True) date = models.DateField('Дата публикации', blank=True) -
Django and HTML cannot start video from a specified time
I am trying to start playing a video from a specific location using Django: <video controls autoplay id='vid' muted > <source src="{% static 'vids/videoplayback.mp4#t=10,30' %}" type="video/mp4"> </video> This gives an error GET http://127.0.0.1:8000/static/vids/videoplayback.mp4%23t%3D10%2C30 404 (Not Found) as it seems Django automatically escaping the special characters is the culprit. Removing the #t=10,30 will autoplay the video without any issue. How do I fix this? -
AJAX calling Django view function not only once but for previous attempts as well
I have a code that should delete a list item. // Triggers when the item "element_to_click" is double clicked and calls the // function named show_hide_function() $( element_to_click ).one('dblclick', function(e) { show_hide_function(input_mt_key, update_form_mt, input_mt, button_text, csrfmiddlewaretoken)}); // Creates a button to delete the selected item, then calls delete_function() function show_hide_function(input_key, form, input, button_text, csrf_token){ const del_btn = document.createElement("button") del_btn.name="my_del_btn" form.appendChild(del_btn); const button_text_del = document.createTextNode("X") del_btn.appendChild(button_text_del) del_btn.setAttribute("class", "update_delete_buttons") // On click on del_btn, calls the function named delete_function() $( del_btn ).on('click', function(e) { delete_function(input_key,csrf_token)}); }; // Sends a form to backend (django) and on success, calls another function // named jsonToDict() which I believe, is not part of the problem. So I don't // include it here. function delete_function(input_key, csrf_token){ $(document).on('submit' , function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/posted/delete/', data:{ item_id:input_key.value, projectURL: projectURL_, csrfmiddlewaretoken:csrf_token, }, success: function (data){ jsonToDict(data, "update_delete_form") }; }); }); }; And simplified version of my django view function looks like this: def deleteDictionary(request): print("called") if request.method == 'POST': var2 = request.POST['item_id'] projectURL = request.POST['projectURL'] value_holder = Task.objects.filter(taskID=var2).values_list('taskIdentifier') else: pass This is how my items look This is how they look on double click: When I delete first item, I get no error. When I do the same … -
Check if Django Group has Permission
I am developing a Django website where I can create groups, where permissions can be assigned. I can also assign groups to users. There is a simple way to check if a user has a permission: user.has_perm('app_name.permission_code_name') What I want to know is if there is a simple way to check if a specific group has a permission (without involving the user at all)? -
Model name of objects in django vews.py querysets
I'm trying to use django-taggit package for several applications on the site. I have two taggable models: Article, News (actually, more, but it does not matter). class TagListView(TagMixin, ListView): model = News, Article def get_queryset(self, **kwargs): my_tag = get_object_or_404(Tag, slug=self.kwargs['tag']) news = News.objects.filter(tags__in=[my_tag]).filter(is_published=True) articles = Article.objects.filter(tags__in=[my_tag]).filter(is_published=True) queryset = list(chain(news, articles)) return queryset In my template, I want to know, which model my objects belong to, in order to process them differently. The right place to do this would be add a 'content_type' feature to my objects in the queryset in my views.py. I imagine something like this: news = News.objects.filter(tags__in=[my_tag]).filter(is_published=True).select_related('django_content_type') articles = Article.objects.filter(tags__in=[my_tag]).filter(is_published=True).select_related('django_content_type') However, my models (news, articles) are not explicitly related to the model 'django_content_type'. Please somebody help me, I've got stuck! P. S. I'm aware that the proper way of doing this would be using generic keys, but I do not know how to work with them. If someone teaches me how to transform my example this way, it would be also great. -
Why does my property description get repeated in loop
So i have a for loop to display the every property in properties, I don't get why my property description gets repeated for every property. every other output is not repeated only the property description. {% for property in propertys %} <div class="listing-item"> <article class="geodir-category-listing fl-wrap"> <div class="geodir-category-img fl-wrap"> <a href="listing/{{ property.id }}" class="geodir-category-img_item"> <img src="{{property.header_image.url}}" style=" max-height: 210px;" alt="{{ property.header_image.url}}"> <div class="overlay"></div> </a> <div class="geodir-category-location"> <a href="#1" class="map-item tolt" data-microtip-position="top-left" data-tooltip="On the map"><i class="fas fa-map-marker-alt"></i> {{ property.location }}</a> </div> <ul class="list-single-opt_header_cat"> <li><a href="#" class="cat-opt blue-bg">{{ property.list_type }}</a></li> <li><a href="#" class="cat-opt color-bg">{{ property.home_type}}</a></li> </ul> <a href="#" class="geodir_save-btn tolt" data-microtip-position="left" data-tooltip="Save"><span><i class="fal fa-heart"></i></span></a> <a href="#" class="compare-btn tolt" data-microtip-position="left" data-tooltip="Compare"><span><i class="fal fa-random"></i></span></a> <div class="geodir-category-listing_media-list"> <span><i class="fas fa-camera"></i> 8</span> </div> </div> <div class="geodir-category-content fl-wrap"> <h3><a href="listing-single.html">{{ property.name }}</a></h3> <div class="geodir-category-content_price">$ {{ property.price }}</div> <p>{{ property.description }}</p> <div class="geodir-category-content-details"> <ul> <li><i class="fal fa-bed"></i><span>{{ property.bedrooms }}</span></li> <li><i class="fal fa-bath"></i><span>{{ property.total_bathrooms }}</span></li> <li><i class="fal fa-cube"></i><span>{{ property.lot_size}} ft2</span></li> </ul> </div> <div class="geodir-category-footer fl-wrap"> <a href="agent-single.html" class="gcf-company"><img src="{{ property.agent.profilepic.url }}" alt=""><span>By {{ property.agent.first_name }} {{ property.agent.last_name}}</span></a> <div class="listing-rating card-popup-rainingvis tolt" data-microtip-position="top" data-tooltip="Good" data-starrating2="3.9"></div> </div> </div> </article> </div> {% endfor %} -
mypy and Django type checking
I'm trying to enable type hints for my Django REST project. I installed django-stubs and djangorestframework-stubs and I have the following mypy.ini file: [mypy] plugins = mypy_django_plugin.main mypy_drf_plugin.main [mypy.plugins.django-stubs] django_settings_module = "core.settings.base" Some of the type hints do work; for example, if I have a variable inside of a method whose type is a model class, I get hints when I try to access a field or method defined on it. However, if I try to access a Django-specific field on the model, for example a reverse relation, that does not typecheck and gives me an error. Moreover, if I try to access fields on a related model of my model variable, the related object has type Any For example, with these two models: class User(models.Model): name = models.TextField() role = models.ForeignKey(Role) # definition of Role model not relevant class Badge(models.Model): user = models.ForeignKey(User, related_name="badges") then this will happen: u: User = get_user() print(u.name) # correctly hinted and typechecks print(u.badges.all()) # type error print(u.role.pk) # no hint on role.pk, role is Any How do I get my project to correclty type check all the Django-specific features such as foreign key fields, querysets, and reverse relationships? -
Getting a TypeError while trying to make a unique page in Django
I'm making a picture gallery web-app. I want to make some of displayed photos to belong to a specific collection. Each collection is supposed to have its own page that displays all of the pictures that belong to it. The name of each unique page is supposed to be photo_collection model, which I added to the class Image in models.py. But for some reason, I get TypeError at /projects/sample_collection_name/ - photo_collection() got an unexpected keyword argument 'photo_collection' No idea what's causing this error. I tried renaming the photo_collection function (it has the same name as my model), but it didn't work. models.py class Image(models.Model): title = models.CharField(max_length=300) image = models.ImageField(null=True, blank=True, upload_to='images/') pub_date = models.DateTimeField('Date published', default=timezone.now) photo_collection = models.CharField('Photo collection', max_length=250, null=True, blank=True) views.py def photo_collection(request): image = Image.objects.all() return render (request, 'photo_app/collection.html', context={'image': image}) urls.py urlpatterns = [ #some other patterns here path('projects/<str:photo_collection>/', views.photo_collection, name='photo_collection'), ] gallery.html {% if i.photo_collection != Null %} <a href="{% url 'photo_collection' i.photo_collection %}">{{i.photo_collection}}</a> {% endif %} -
Django template language if tag not working
I have a django template with an update form, for an invoices application. I want to allow to update the record after it was saved. One of the model fields is manager which is a foreign key: class Invoice(models.Model): manager = models.ForeignKey(User, on_delete=models.CASCADE,null=True ,blank=True) The problem is that I don't to display the manager's user id, but his/her first name, so I want to populate the select tag with all manager's first name. I have tried this: <select id="id_manager" name="manager"> {% for manager in managers %} {{ manager }} || {{ initial_manager }} {% if manager == initial_manager %} <option value="{{ manager.user.id }}" selected>{{ manager.user.first_name }}</option> {% else %} <option value="{{ manager.user.id }}">{{ manager.user.first_name }}</option> {% endif %} {% endfor %} </select> This is the views.py part: managers = Profile.objects.filter(Q(role = 'manager') | Q(role = 'cfo') | Q(role = 'ceo') | Q(role = 'sec')) projects = Project.objects.all() form = InvoiceForm(instance = invoice) initial_manager = invoice.manager return render(request, "invoice/update.html", {'form': form, 'managers':managers, 'projects':projects, 'initial_manager':initial_manager}) I have added this to see the values of the variables: {{ manager }} || {{ initial_manager }} and I see for example " 102 || 102 ", which means that they are equal but the if … -
Django won't stop throwing error even though I have removed the problem code [closed]
I replaced this line of code... customer.sources.create(source=token) with customer = stripe.Customer.create_source(userprofile.stripe_customer_id, source=token) in my django project. But the django won't stop throwing error stripe error -
What's a reverse foreignkey and a normal foreignkey
This a question from a Django noob, my question goes thus; What is the difference between a normal foreignkey and a reverse relation and what is the difference. I always thought; method 1 class State(models.Model): name = models.CharField() class Country(models.Model): name = models.CharField() state = models.ForeignKey(State) # normal foreignkey method 2 class Country(models.Model): name = models.CharField() class State(models.Model): name = models.ForeignKey(Country) # reverse relation What is the main difference and what is the benefit, when to use it and how to use it especially if I want to use reverse relation for example; create multiple instance of state in a django form. -
Can help to resolve this issue please? [closed]
enter image description here I upgraded Ubuntu Version, and with that python also upgraded. But my project was running in a lower version, I set a lower python version, and I tried everything but still facing this issue. Help me to resolve this issue. Thank you soo much in advance. -
Deploying Django Project but using Google Cloud SQL
I'm trying to deploy a todo-list django app (https://gitlab.com/learning-python8/django-project) in google app engine I have this error message: ERROR: (gcloud.app.deploy) INVALID_ARGUMENT: could not resolve source: googleapi: Error 403: 1026004585917@cloudbuild.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object., forbidden Now the project is a way for me to study app deployment in GCP. The project is using an sqlite database for user along with it's todo data. If I understand the error right, It asks me to create a Google Cloud SQL. Would that be the correct process? I will be studying SQL to use online database for this project. -
FieldError: Cannot resolve keyword 'get_str' into field while using @property method in values_list() in a QuerySet
I have a model named Invitation, where I have created a property method which returns the value returned by __str__() method, like below: class Invitation(models.Model): @property def get_str(self): return self.__str__() Now, I am trying to use this property method in QuerySet's values_list() method as below: Invitation.objects.values_list("pk", "get_str") But I am getting following error: Cannot resolve keyword 'get_str' into field. Choices are: accepted_at, created_at, created_by, created_by_id, expiration_date, id, invited_to, invitee_first_name, invitee_last_name, is_canceled, secret, sent_to Full Traceback of error is: Traceback Switch to copy-and-paste view /app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/query.py, line 2107, in add_fields join_info = self.setup_joins( … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/query.py, line 1773, in setup_joins path, final_field, targets, rest = self.names_to_path( … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/query.py, line 1677, in names_to_path raise FieldError( … Local vars During handling of the above exception (Cannot resolve keyword 'get_str' into field. Choices are: accepted_at, created_at, created_by, created_by_id, expiration_date, id, invited_to, invitee_first_name, invitee_last_name, is_canceled, secret, sent_to), another exception occurred: /app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/mixins.py, line 73, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars /app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py, line 119, in dispatch … -
How shoud I fix ERROR with pip install psycopg2==2.7.*?
I am trying to put my app that I created on server www using heroku. But when I put to my terminal on Ubuntu pip install psycopg2==2.7.*, I get this error: ERROR: Command errored out with exit status 1: command: /home/marcin/Python/learning_log/ll_env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-c67buptz/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-c67buptz/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-c67buptz/psycopg2/pip-egg-info cwd: /tmp/pip-install-c67buptz/psycopg2/ Complete output (28 lines): running egg_info creating /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info writing /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-install-c67buptz/psycopg2/pip-egg-info/psycopg2.egg-info/SOURCES.txt' /home/marcin/Python/learning_log/ll_env/lib/python3.8/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) /home/marcin/Python/learning_log/ll_env/lib/python3.8/site-packages/setuptools/command/egg_info.py:643: SetuptoolsDeprecationWarning: Custom 'build_py' does not implement 'get_data_files_without_manifest'. Please extend command classes from setuptools instead of distutils. warnings.warn( Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs … -
Django ORM: select until value in column changes
I want to get newest events until the first change. This is my data (sorted by timestamp): # EventModel id | event | timestamp ---+-----------+----------- 1 | birthday | 5 2 | birthday | 4 3 | wedding | 3 4 | null | 2 5 | birthday | 1 This is my desired output: <QuerySet [{'id': 1, 'event': 'birthday', 'timestamp': 5}, {'id': 2, 'event': 'birthday', 'timestamp': 4}]> Please note that there is also event=birthday where id=5, but I don't want it in the output. The newest event can be null and that's ok. I tried with Subquery: from django.db.models import Subquery subquery = EventModel.objects.order_by("-timestamp").values("event")[:1] EventModel.objects.filter(event=Subquery(subquery)) But this gives me also row with id=5. -
DeleteView is missing a queryset
So i'm working on an inventory app, a django-app where you can handle inventory in a company. I've been using mostly class-based so far in my views.py, and i can already create and edit all of my models using class-based views. So when it comes to the generic.DeleteView, i have some problems. This is my function in views.py: class DeleteItemView(DeleteView): model: Item success_url: reverse_lazy('inventory_app:items') template_name = 'inventory/detail_pages/item_detail.html' And this is my URL to the function: path('items/<int:pk>/delete/', views.DeleteItemView.as_view(), name='delete_item') When i call this url with a button, this error appears: DeleteItemView is missing a QuerySet. Define DeleteItemView.model, DeleteItemView.queryset, or override DeleteItemView.get_queryset(). So i heard online that this appears when /<int:pk>/ is missing in the url. But i have it in mine, so whats the problem here? Thank you already -
my css codes does not work on some parts of my django project
So i am building a website with django but my css code working some parts while some parts dont. this is my home.html {% extends 'base.html' %} {% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static '/static/css/home.css'%}"> <script src="{% static 'fontawesomefree/js/all.min.js' %}"></script> <link href="{% static 'fontawesomefree/css/all.min.css' %}" rel="stylesheet" type="text/css"> </head> <body> {% block content %} <div class="container"> <div class="card"> {% for product in product_list %} <div class="image"> <img src="{{ product.image }}" alt="{{product.title}}"> </div> <div class="content"> <div class="product-name"> <h3>{{product.title}}</h3> </div> <div class="price-rating"> <h2>13.40$</h2> </div> <div class="rating"> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> <i class="fa-regular fa-star"></i> </div> </div> {% endfor %} </div> </div> {% endblock %} </body> </html> and this is home.css * { margin: 0; padding: 0; box-sizing: border-box; } body { display: flex; justify-content: center; align-content: center; min-height: 100vh; background: #dcdcdc; } .image { width: 10%; } .container { position: relative; width: 1200px; display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)) } I can change color of page but i cannot change the display or i cannot change sequence of items. image of my site so do you people have any idea to fix this issue? and my codes are not conflicting because i …