Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Better way to delete unused tag. / django taggit python
Hi i'm python django beginner. I'm creating a simple blog and i want to delete tags that are not used while deleting a post class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=500) create_date = models.DateTimeField(auto_now_add=True) modify_date = models.DateTimeField(auto_now=True) tags = TaggableManager(blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='owner', blank=True, null=True) class PostDelete(WriterCheckMixin, DeleteView): model = Post success_url = reverse_lazy('blog:list') def delete(self, request, *args, **kwargs): temp = Post.objects.get(pk=kwargs['pk']) for tag in temp.tags.all(): if tag.taggit_taggeditem_items.count() <= 1: tag.delete() return super().delete(request, *args, **kwargs) I just follow tutorial so don't know what happens behind DeleteView. It worked as intended but seems inefficient. Do i need "temp = Post.objects.get(pk=kwargs['pk'])"? Please give me advices. -
Django template how to look for a dictionary value while iterating another dictionary?
Template code snippet: {% for stock in portfolio %} <tr> <td>{{ stock.stock_name }}</td> <td>{{ stock.trans_price }}</td> <td>{{ stock.trans_quantity }}</td> <td>{{ stock.trans_date }}</td> <td>{{ stock_ltps.stock.stock_name }}</td> <!-- This value doesn't get fetched. --> </tr> {% endfor %} View code snippet: portfolio = Portfolio.objects.all() # another dictionary to hold live stock prices from api stock_ltps = {} for stock in portfolio: stock_ltps[stock.stock_name] = 12 #static number for debugging/trial return render(request, 'portfolio_management/index.html', context={"stc": stock_name, "stock_add_form": stock_add_form, "portfolio": portfolio, "stock_ltps": stock_ltps}) This doesn't fetch the value from another dictionary. How to fix this? -
How to do mongodb ACID transaction in django with djongo as database backend?
I'm using mongodb in django with djongo as database backend. Right now it does not support ACID transactions but mongo and pymongo do. Is there a way to tweak this library to support ACID transactions with using ORM and without making queries by pymongo? -
How to return JSON only when request API with Django Rest Framework?
what i want to achieve is when i trigger an URL, i need my rest api only return JSON data. for now when i trigger my URL api, it open a HTML page which is like an API Documentation, i think this is default feature from django, then i have to add ?format=json at the back of the url to get real JSON response, how do i get to do thos without adding ?format=json <-- this here is what my code looked like : Models.py from django.db import models # Create your models here. class Post(models.Model): categoryList =(('drama','Drama'),('action','Action')) title = models.CharField(max_length=255) category = models.CharField(max_length=6,choices=categoryList,default='drama') content = models.TextField() is_featured = models.BooleanField(default=False) def __str__(self): return self.title Serializer.py from ..models import Post from rest_framework import serializers class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('title', 'category', 'content', 'is_featured') Views.py from ..models import Post from . import serializers from rest_framework import generics, status from rest_framework.response import Response class PostListView(generics.ListAPIView): queryset = Post.objects.all() serializer_class = serializers.PostSerializer then i try to change my code in this : (i am not really know this is the right way, i am new with python and django, just trying read from the documentation) from ..models import Post from … -
How can I have multiple forloops on my Django template?
I am a Django / Python newbie & trying to create multiple forloop on my template. The result that I want is: <ul> <li data-target="food-fruit1-0">Banana</li> <li data-target="food-fruit1-1">Apple</li> <li data-target="food-fruit1-2">Orange</li> <li data-target="food-fruit1-3">Mango</li> </ul> <ul> <li data-target="food-fruit2-0">Banana</li> <li data-target="food-fruit2-1">Apple</li> <li data-target="food-fruit2-2">Orange</li> <li data-target="food-fruit2-3">Mango</li> </ul> How do I achieve it with Django Template forloop? I have tried <ul class='h-clearlist'> {% for item in object.fruits %} <li class='fruit__list' data-target="food-fruit{{ forloop.counter1 }}-{{ forloop.counter0 }}"> <h3 class='fruit__title'>{{item.name}}</h3> <p class='fruit__description'>{{item.description}}</p> <span class="fruit__cost"> <strong data-currency>{{item.price}}</strong></span> </li> {% endfor %} </ul> But of course it's incorrect:( I tried using {% with outer=1 inner=0 %} but also not working. Can someone please help me out? -
i am stucked i please help me i cant install pip package installer
me [2]: the pip python installer is telling me that pip was already installed and it shows the below error; Collecting pip Using cached https://files.pythonhosted.org/packages/00/b6/9cfa56b4081ad13874b0c6f96af8ce16cfbc1cb06bedf8e9164ce5551ec1/pip-19.3.1-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 19.3.1 Uninstalling pip-19.3.1: Successfully uninstalled pip-19.3.1 [33m WARNING: The scripts pip.exe, pip3.8.exe and pip3.exe are installed in 'C:\Users\ABUBAKAR SADIQ\AppData\Local\Programs\Python\Python38-32\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.[0m Successfully installed pip-19.3.1 -
how to used css @media in django?
I am making a django project with dynamic scree using css @media but it does not work. .... @media screen and (max-width: 500px) .... The html will take eithe one of them or not at all. Or do we have to do in a different way in django. Thanks in advance -
I have two CKEditor in same page. I want to hide one of them. How can I do that?
I have 2 editors displayed when the HTML page is loading. I just need 1 editor to be displayed and want to hide one. I have tried <script> $(document).ready(function () { $('form.sms-comm-template').on('submit', function (elem) { elem.preventDefault(); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), dataType: 'json', data: $(this).serialize(), success: function (data) { $('#comm-update').css({'display': 'none'}); $('#Communication').css({'display': 'block'}); CKEDITOR.replace( 'editor1' ); $('.template_body').each(function(e){ CKEDITOR.replace( this.id, { scayt_autoStartup : true, }, display: none,); }); }, error: function (xhr, err) { } }); }) }); </script> -
TypeError for getting month wise data in django ORM
error: TypeError at /production/dashboard-report not all arguments converted during string formatting I don't know why I am getting this kind of error. It works for contains, range, gte, lte but it's giving me error if I write to year or month. Here is my model: class Production(models.Model): bcb = models.ForeignKey(BCBarcode, on_delete=models.CASCADE, null=True) process = models.ForeignKey(Process, on_delete=models.CASCADE, null=True) part = models.ForeignKey(Part, on_delete=models.CASCADE, null=True) quantity = models.IntegerField(default = 0) accepted_qty = models.IntegerField(default = 0) rejected_qty = models.IntegerField(default = 0) remarks = models.TextField(null=True) scan_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) scanned_at = models.DateTimeField(default=timezone.now) And here is my code: this_months_data =Production.objects.filter(process=process,part=1,scanned_at__month=12,bcb__bc__company=company).aggregate(total_last_weeks_data=Sum('accepted_qty')) Please suggest me, solution guys. -
Python / Django from Terminal results in syntax error
Hi I'm quite new to Programming so this is probably an easy question but I can't figure it out. So I'm trying to build a simple website using Python and Django. In PyCharm I use the local Terminal and have a virtualenv set up. I can run commands such as "python manage.py runserver" and such. However when I start my normal Terminal window (not in PyCharm but the normal Mac Terminal app) and navigate to my project I can't execute any Django commands. I get the following error message: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax Is it a problem with the venv? I just want to use the normal Terminal application instead of the build-in one in PyCharm. -
Django GraphQL endpoint testing unable to use `variables` dictionary
How to use variables in django-graphql-jwt? I can use mutation in the iGraphQL with variables normally. Then it supposed to be working as well in my TestCase from django.contrib.auth import get_user_model from graphql_jwt.testcases import JSONWebTokenTestCase from model_mommy import mommy from multy_herr.commons.tests import JCMixin from multy_herr.objections.models import Objection from multy_herr.tweets.models import Tweet User = get_user_model() class UsersTest(JCMixin, JSONWebTokenTestCase): def setUp(self) -> None: super().setUp() mommy.make(Objection, _quantity=3) def test_authorized_user_hide_success(self): """ Hide success :return: """ tweet = Tweet.objects.first() query: str = ''' mutation{ objection(input: { tweet: $tweetId hidden: $hidden }){ id hidden report tweet errors{ field messages } } } ''' variables = { 'tweetId': str(tweet.id), 'hidden': True, } self.client.authenticate(self.jc) res = self.client.execute(query, variables) Here is res.error res.errors Out[3]: [graphql.error.base.GraphQLError('Variable "$tweetId" is not defined.'), graphql.error.base.GraphQLError('Variable "$hidden" is not defined.')] Workaround: I use .format() in Python to assign value to my variable, but I don't like that hackish way Question: Is it bug? -
_frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('django.test.signals') at 140668266856120
I am getting this error when I go for python manage.py runserver error - _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('django.test.signals') at 140668266856120 Error doesnt not occur for makemigrations or migrate. These commands works properly with no error but on runserver it gives error. Please help me out. I saw other questions but it says that same model is called multiple times or same Database Table has been called multiple times. -
Django cannot recognize mysqlclient installed
Trying to connect Django to Mysql. Django is not able to recognize the mysqlclient installed? How to fix this? mysqlclient #pip3 install -U mysqlclient Collecting mysqlclient Installing collected packages: mysqlclient Found existing installation: mysqlclient 1.3.13 Uninstalling mysqlclient-1.3.13: Successfully uninstalled mysqlclient-1.3.13 Successfully installed mysqlclient-1.4.6 Django django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
folder design when using ariadne in django
I am trying to explore ariadne in my django project. However, I am feeling extremely tough to create a folder structure as I don't see much example mainly focused on that. Also I did not find any single tutorial. Everywhere the same way is done that is having every code in schema.py. Here is an example from ariadne import QueryType, make_executable_schema type_defs = """ type Query { hello: String! } """ query = QueryType() @query.field("hello") def resolve_hello(*_): return "Hello world!" schema = make_executable_schema(type_defs, query) How would you design your folders in a large django application where there are say more than 10, 15 apps like accounts, products, reviews etc? If we use plain django then it already gives following structure app_name views.py urls.py models.py but if we want to use ariadne in django and consider each app's crud features how would you now design your project? -
How to provide an external database connection that can be used in views in Django?
For example, how to setup sqlalchemy, so views can use an external database that is not used with Django? And views won't have to initiate connection every time it is called? -
django response without client request
in normal situation all of http responses occurs after client requests. is it possible having a response and have browser reaction without client request? for example in whats-app web client logout in browser occurs immediately after android app command "Logout all devices". -
Django handling foreign keys to multiple models
class Product(models.Model) class InventoryItem(models.Model) class Warehouse(models.Model) class Store(models.Model) class Office(models.Model) class Lab(models.Model) (... and many more) class ProductImage(models.Model): image = models.ImageField() product = models.ForeignKey(Product, on_delete=models.CASCADE) class InventoryItemImage(models.Model): image = models.ImageField() inventory_item = models.ForeignKey(InventoryItem, on_delete=models.CASCADE) (... and many more) I'm trying to add the ability to attach multiple images to a model. The problem is, there are more than 10 models and adding every <modelname>Image does not quite suit me. I tried searching and there were a few options. Create every <modelname>Image model for <modelname>. This seems quite not right. Use Django's GenericForeignKey. I thought of this, but after reading this blog article I'm not so sure. One Image model, and ManyToManyField in all models. Promising, but not so sure. Also Django admin is not properly showing image upload fields. Create dummy model, models foreignkey to it and Image model foreignkeys to it too. Seems overly complicated. What would be the right way to do this? Any new suggestions or guides welcome! -
Failed install mysqlclient on ubuntu 18.04 64bit, python 3.7 for Django
Unable to install mysqlclient on, I tried installing all previous versions of mysqlclient, they all fail. How to solve this? Django django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. ubuntu 18.04 64bit python 3.7 pip3 install mysqlclient==1.4.6 building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/MySQLdb x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 -I/usr/include/mysql -I/usr/include/python3.7m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.7/MySQLdb/_mysql.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.7/MySQLdb/_mysql.o -lmysqlclient -lpthread -lm -lrt -lssl -lcrypto -ldl -o build/lib.linux-x86_64-3.7/MySQLdb/_mysql.cpython-37m-x86_64-linux-gnu.so /usr/bin/ld: cannot find -lssl /usr/bin/ld: cannot find -lcrypto collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-32wb3d8c/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-k3k9psc1-record/install-record.txt --single-version-externally-managed --compile: /usr/lib/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running install running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py … -
Here post method is not working properly ,when it push to the server,but in local host it is working properly
Here post method is not working properly when it push to the server,but in local host it is working properly.When it run in server,it will produce else case response like 'return HttpResponse("faild")',but run in localhost it will produce, response like 'return HttpResponse(received_json_data)',can solve this issue. values [ { "user": 3, "news_category": 1, "sub_category": [1, 2] } ] urls.py url(r'savesubcategory', csrf_exempt(views.savesubcategory), name='savesubcategory') views.py import json def savesubcategory(request): print "===============================" if request.method == 'POST': print "++++++++++++++++++" received_json_data = json.loads(request.body) store_list = [] for item in received_json_data: id = item['user'] name = User.objects.get(id=id) print name id = item['category'] categ = Category.objects.get(id=id) for ite in item['sub_category']: subcat = SubCategory.objects.get(id=ite) print subcat # print name ," -- ", categ , "--",ite savecat = SavingCategoryandPreferences(user = name ,category = categ ,subcategories = subcat) savecat.save() return HttpResponse(received_json_data) return HttpResponse("faild") Response in case of server faild I want response like , { 'sub_category': [1, 2], 'user': 6, 'news_category': 3 } -
Convert sql query into Django query set?
SELECT * from quiz_quiz where subject_id=(SELECT subject_id from general_subject_assignment where grade_id =(SELECT grade_id from general_student where user_id =2)) Tanks in advance! -
How to handle activation url with Django Djoser?
I'm unable to activate users via the activation link. How can I correctly configure the path to process their request? My config: DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': 'api/v1/auth/users/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'api/v1/auth/users/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'api/v1/auth/users/activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SEND_CONFIRMATION_EMAIL': True, 'SERIALIZERS': {}, # 'USER_ID_FIELD': '', 'LOGIN_FIELD': 'username', 'USER_CREATE_PASSWORD_RETYPE': True, 'SET_USERNAME_RETYPE': True, 'USERNAME_RESET_CONFIRM_RETYPE': True, 'SOCIAL_AUTH_ALLOWED_REDIRECT_URIS': [], 'HIDE_USERS': True, 'EMAIL': { 'activation': 'api.email.ActivationEmail', 'confirmation': 'api.email.ConfirmationEmail', 'password_reset': 'api.email.PasswordResetEmail', 'password_changed_confirmation': 'api.email.PasswordChangedConfirmationEmail', 'username_changed_confirmation': 'api.email.UsernameChangedConfirmationEmail', 'username_reset': 'api.email.UsernameResetEmail', } } path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('auth/', include('djoser.urls.authtoken')), -
Whitenoise not working for django-admin on heroku
I have been struggling with this for a bit now and I have tried almost everything within my abilities. Followed this which actually is my issue but no luck: https://github.com/pydanny/cookiecutter-django/issues/1527 Tried following this as well: Django on Heroku - Broken Admin Static Files no luck! What's happening is that all of my projects look and work great except the Django-admin site which is important for my project. Here's the Github repo: https://github.com/Zamy97/Explain_Algorithms I used cookiecutter-Django to build my project. I would appreciate any type of guidance here please. -
How to use pylint_django?
I am new to linting, using python 2.7 and pylint-django 0.7.2 for linting my django code. pylint --load-plugins pylint_django [..other options..] <path_to_your_sources> I didn't understand the path_to_your_sources in the above command? Do I've to give a .py file or the django directory? I tried running with a .py file, getting the below error: ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings Can anyone please let me know what this error is saying and how to use pylint_django. -
Django Regex URL Issue
Any idea how to match the django URL to Status=1 in the URL below http://example.com/?Status=1&Checksum=641577506237&Id=100201936203143476&Date=2019-12-28+07%3A11%3A17&Variable1=&Variable2=&Variable3=&Variable4=&Variable5=&Method=1 -
django:Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['detail/(?P<pk>[0-9]+)/$']
I am trying to develop a web system in python3 and Django using the local environment. when I try to use a DetailView and add pk in URL, I got stuck and I don't know why it's showing this error. I searched a lot and can't find an answer. my condition Mac: mojave 10.14.6 Python: 3.7.5 Django: 2.2.2 error message Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['detail/(?P<pk>[0-9]+)/$'] detail.html {% for vegetable_info in object_list %} <a href="{% url 'main:detail' vegetable_info.pk %}”> detail </a> {% endfor %} views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic class DetailView(LoginRequiredMixin, generic.DetailView): model = DbVegetableInfo template_name = 'detail.html' urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'), ] *I've already tryied this case but it has been still not solved... Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['articles/edit/(?P<pk>[0-9]+)/$']