Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replacing function attribute with variable containing string
I want to write code in a singe line to replace the following if-else code. Can I somehow use the status variable in the filter function directly as an attribute ? status = request_queries.get('status', None) if(status = 'saved'): queryset = queryset.filter(saved = True) elseIf (status = 'shortlisted'): queryset = queryset.filter(shortlisted = True) elseIf (status = 'accepted'): queryset = queryset.filter(accepted = True) elseIf (status = 'rejected'): queryset = queryset.filter(rejected = True) -
How to set default image from not from media directory
I don't know how to correctly set default path to none-media image. I've tried to add /, but it doesn't help: ... image = models.ImageField(... default='/static/course_lesson/resources/images/default.jpg') ... And in HTML page image.url looked as follows: ... src="/media/static/course_lesson/resources/images/default.jpg" ... -
where `form.as_p`in django templates come from?
I have a generic view and a form template. my view is: class BlogCreateView(CreateView): model = Post template_name = "post_new.html" fields = "__all__" and my form template is: {% extends "base.html" %} {% block content %} <h1>New Post</h1> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock content %} now my question is about form.as_p or specifically form. Where did that come from? help me please. thanks a lot -
Writing script tag outside or inside block?
Please Consider the following pieces of code. <!--templates/home.html--> {% extends 'base.html' %} {% load static %} {% block content %} {% for post in object_list %} <div class = 'post-entry'> <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</h2> <p>{{ post.body }}</p> </div> {% endfor %} <script type = "text/javascript" src = "{% static 'js/test.js' %}"></script> {% endblock content %} and <!--templates/home.html--> {% extends 'base.html' %} {% load static %} {% block content %} {% for post in object_list %} <div class = 'post-entry'> <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</h2> <p>{{ post.body }}</p> </div> {% endfor %} {% endblock content %} <script type = "text/javascript" src = "{% static 'js/test.js' %}"></script> The first one executes successfully but the second one does not. Is it necessary to load an external static file from inside a django template block and if not then why does the second code not execute? PS: I am new to django. For purpose of clarity i am also providing the code for the base template here. <!--templates/base.html--> {% load static %} <html> <head><title>Django Blog</title> <link href = "{% static 'css/base.css' %}" rel = "stylesheet"> </head> <body> <header><h1><a href = "{% url 'home' %}">Django Blog</a></h1></header> <div> {% … -
How to manage change Emailid and Change Password for user logged in using Social Media in Django all-auth?
How can I give the option to change Email-Id and change Password for users logged in through AllAuth [Gmail / Facebook]. -
How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip
I am trying to install django-heroku using pip but it keeps running into an error. I have seen suggestions telling me to make sure my python version in heroku is up to date. I have already done that. After pushing to heroku master, i ran the install command but it gives me the following errors. pip install django-heroku Error: ERROR: Command errored out with exit status 1: command: /Users/user/Dev/trydjango/new_env/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/xl/s533dc515qs8sd3tpg7y5ty80000gp/T/pip- install-xqsix26g/psycopg2/setup.py'"'"'; egg_info --egg-base pip-egg-info cwd: /private/var/folders/xl/s533dc515qs8sd3tpg7y5ty80000gp/T/pip- install-xqsix26g/psycopg2/ Complete output (23 lines): running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg- info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg- info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add t . he 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 for full … -
How to serialize foreign key from model X in model Y, where model X has the relation to model Y?
I need to serialize my Contracts view in my Registration view. I understand how to do it if there was a foreign key in the Registration model relating the Contract model, but in this case there is a relation from the Contract model to the Registration model. I need to do this in a bigger project, this is just a simple boiler plate. Basically, I want my output to be this: [ { "id": 1, "client": "John Doe", "contract": { "id": 1, "client": "John Doe", "name": "New Identity", "registration": 1 } }, { "id": 2, "client": "Jane Doe", "contract": { "id": 2, "client": "Jane Doe", "name": "Identity theft", "registration": 2 } } ] Models: class Client(models.Model): name = models.CharField(max_length=250) address = models.CharField(max_length=250) email = models.EmailField() class Registration(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) class Contract(models.Model): name = models.CharField(max_length=150) client = models.ForeignKey(Client, on_delete=models.CASCADE) registration = models.ForeignKey(Registration, on_delete=models.CASCADE) Viewsets: class ClientViewSet(viewsets.ModelViewSet): queryset = Client.objects.all() serializer_class = ClientSerializer class RegistrationViewSet(viewsets.ModelViewSet): queryset = Registration.objects.all() queryset = queryset.select_related("client") serializer_class = RegistrationSerializer class ContractViewSet(viewsets.ModelViewSet): queryset = Contract.objects.all() queryset = queryset.select_related("registration").prefetch_related( "client" ) serializer_class = ContractSerializer Serializers: class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" class ContractSerializer(serializers.ModelSerializer): client = NameSerializer() class Meta: model = Contract fields = … -
Django models many to many relations
I'm moving my first steps with django and I'm trying to figure out a thing. Suppose that we have a model.py made like this where NameEffect has a many to many relation class Name(models.Model): nameid = models.IntegerField() name = models.CharField(max_length=255) class Effect(models.Model): effectid = models.IntegerField() effect = models.TextField() class NameEffect(models.Model): nameid = models.IntegerField() effectid = models.IntegerField() start = models.PositiveIntegerField() strand = models.PositiveIntegerField() and I want to create a QuerySet where every entry contains name,effect,start,strand of the researched name. Fact is that the only solution I found was using raw SQL queries but I can't understand how to do it with the django models approach -
Django RawQuerySet Subtraction with raw query
I'm trying this query in postgres it working select (SELECT sum(amount) FROM expense_expense WHERE flow='INFLOW')- (SELECT sum(amount) FROM expense_expense WHERE flow='OUTFLOW') AS balance; Getting Out Put balance| -------| 6370.77| But when i try with Django RawQuerySet It is asking for primary key In [168]: r = Expense.objects.raw("select(select sum(amount) FROM expense_expense where flow='INFLOW') - (select sum(amount) FROM expense_expense where flow='OUTFLOW') as balance;") In [169]: r.columns Out[169]: ['balance'] In [170]: r[0] --------------------------------------------------------------------------- InvalidQuery Traceback (most recent call last) <ipython-input-170-8418cdc095ae> in <module> ----> 1 r[0] ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in __getitem__(self, k) 1433 1434 def __getitem__(self, k): -> 1435 return list(self)[k] 1436 1437 @property ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in __iter__(self) 1393 1394 def __iter__(self): -> 1395 self._fetch_all() 1396 return iter(self._result_cache) 1397 ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in _fetch_all(self) 1380 def _fetch_all(self): 1381 if self._result_cache is None: -> 1382 self._result_cache = list(self.iterator()) 1383 if self._prefetch_related_lookups and not self._prefetch_done: 1384 self._prefetch_related_objects() ~/Desktop/workspace/projects/python/django/expenditure/venv/lib/python3.7/site-packages/django/db/models/query.py in iterator(self) 1408 model_init_names, model_init_pos, annotation_fields = self.resolve_model_init_order() 1409 if self.model._meta.pk.attname not in model_init_names: -> 1410 raise InvalidQuery('Raw query must include the primary key') 1411 model_cls = self.model 1412 fields = [self.model_fields.get(c) for c in self.columns] InvalidQuery: Raw query must include the primary key In [171]: Is there anything I'm missing or anything I need to do, please let me know how can … -
Django coverage on travis-ci returns ModuleNotFoundError
This is my first project where I setup an CI test coverage analysis. My django project has some tests and settings files for various environmens. The layout looks like ├── manage.py ├── papersquirrel │ ├── __init__.py │ ├── __pycache__ │ ├── settings │ │ ├── base.py │ │ ├── ci.py │ │ ├── example.py │ │ ├── __init__.py │ │ └── __pycache__ │ ├── urls.py │ └── wsgi.py ├── readme.md ├── requirements.txt ├── res ├── squirrel │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── management │ │ └── commands │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ ├── models.py │ ├── __pycache__ │ ├── templates │ │ └── squirrel │ ├── tests │ │ └── basic-html.html │ ├── tests.py │ ├── urls.py │ ├── utils.py │ └── views.py ├── static When I execute the coverage analysis on my local virtualenv, it works by invoking coverage run manage.py test --settings papersquirrel.settings.ci . But when I invoke this command via .travis.yml I get only ModuleNotFoundError: No module named 'papersquirrel.settings.ci' I tried various combinations and reviewed a lot of docs and howtos, but it seems, that my travis virtualenv seems to have problems … -
Change span text when clicked
I'm creating a social media page, and I am adding a functionality where if a posts characters is greater than 50, show a shorter version, and append a ...more at the end. In my models.py i have a function that displays 50 characters and beyond, and I want to use this when the ...more is presses. Currently when pressed the text just completely disappears. models.py class Post(models.Model): file = models.FileField(upload_to='files/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user.username def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def summary_pretty(self): return self.summary[:50] def summary_rem(self): return self.summary[50:] home.html {% extends 'accounts/base.html' %} {% block content %} {% load widget_tweaks %} {% load static %} {% for post in posts %} <div class="container pl-5"> <div class="row pt-3"> <img src="{% static 'rect.jpg' %}" width="600px" height="60px"> <div class="pt-3 pl-5" style="position: absolute;"> <b> {{ post.user.username }} </b> </div> <br> <div class="card" style="width: 600px;"> <img src="{{ post.file.url }}" width="599px"> </div> <br> <img src="{% static 'rect.jpg' %}" width="600px" height="150px"> <div class="col-6"> <script> function addMore(e) { e.innerText = "{{ post.summary_rem }}"; } </script> {% if post.summary|length > 50 %} <div class="" style="position: absolute; bottom: 75px; left: 35px;"> <b> {{ post.user.username }} </b> {{ post.summary_pretty }} <span … -
deleted all migrations with __init__.py file django
I have accidentally deleted all of my init.py files while trying to reset migrations i have recreated the migrations file on each of my apps with a blank init.py file but some errors seem to pop up like: no module named "myprojectname.users". -
No handler for message type websocket.group_send, how tofix?
i switch from one user websocket connection to make chat room, that 2 people can connect each other, but on switch, in recieve method, need now group_send, and after that it stoped work, how to fix? Full Traceback > Exception inside application: No handler for message type > websocket.group_send File > "D:\Dev\Web\Chaty\lib\site-packages\channels\sessions.py", line 183, > in __call__ > return await self.inner(receive, self.send) File "D:\Dev\Web\Chaty\lib\site-packages\channels\middleware.py", line 41, > in coroutine_call > await inner_instance(receive, send) File "D:\Dev\Web\Chaty\lib\site-packages\channels\consumer.py", line 59, in > __call__ > [receive, self.channel_receive], self.dispatch File "D:\Dev\Web\Chaty\lib\site-packages\channels\utils.py", line 52, in > await_many_dispatch > await dispatch(result) File "D:\Dev\Web\Chaty\lib\site-packages\channels\consumer.py", line 75, in > dispatch > raise ValueError("No handler for message type %s" % message["type"]) No handler for message type websocket.group_send > WebSocket DISCONNECT /messages/dildo/ [127.0.0.1:58910] Consumer import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('Connected', event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] thread_obj = await self.get_thread(me, other_user) chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ 'type':'websocket.accept' }) async def websocket_receive(self, event): print('Recive', event) front_response = event.get('text', None) if front_response is not None: compiled_response_data = json.loads(front_response) if 'FormData' in compiled_response_data: … -
run tika python with django in docker
I've a django site that parses pdf using tika-python and stores the parsed pdf content in elasticsearch index. it works fine in my local machine. I want to run this setup using docker. However, tika-python does not work as it requires java 8 to run the REST server in background. my dockerfile: FROM python:3.6.5 WORKDIR /site COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . EXPOSE 8000 EXPOSE 9200 ENV PATH="/site/poppler/bin:${PATH}" CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] requirements.txt file : django==2.2 beautifulsoup4==4.6.0 json5==0.8.4 jsonschema==2.6.0 django-elasticsearch-dsl==0.5.1 tika==1.19 sklearn where (dockerfile or requirements) and how should i add java 8 required for tika to make it work in docker. Online tutorials/ examples contain java+tika in container, which is easy to achieve. Unfortunately, couldn't find a similar solution in stackoverflow also. -
Fastest way to iterate over django queryset and trigger post_save signal
I have a project that has lots of models and some of these models have over +9.5M entry. I should iterate over whole entry and trigger post_save method. How can I do this in a fastest way? -
how to change the format of date in django validation error
class Registration(models.Model): Date_of_birth=models.DateField(blank=True, default='', null=True) class Meta: db_table = "gym_registration" -
why my django framework shows me this error in terminal?
every time i want to start my django project developement server its shows me error ? (base) C:\Users\asus\PycharmProject\textutils\textutils\textutils>python manage.py runserver python: can't open file 'manage.py': [Errno 2] No such file or directory -
Migration fails trying to add a constraint to db
I'm trying to use django models to create constraints on my database, what am I doing wrong here? I'm using django 2.2.2 on Python 3.7.3 Here is my model meta: class Meta: db_table = 'Client' constraints = [ models.CheckConstraint(check=models.Q(cnpj__exact='\\d{14}'), name='valid_cnpj'), ] Error message: AttributeError: 'str' object has no attribute 'connector' -
Django tries localhost on Mysql but I say otherwise
I'm trying to make Django work under Windows 10 but connecting with my (often used) off-site Mysql server I get django.db.utils.OperationalError: (2006, "Can't connect to MySQL server on 'localhost' (10061)") While (like I used to do) state in my config file (mysql.conf) to which is pointed to by my settings.py like I used a thousand times before: [client] host = 10.8.0.1 database = sitesv user = niels password = xxx port = 3306 default-character-set = utf8 Whether I use the ip within '' or I use a name which is known in my hosts file I still get the same stupid error.... I'm not trying localhost! -
How to import something from one directory above in a Django project?
In my Django project, I have split models. The project directory kinda looks like this: myproject/ app1/ validators.py views.py __init__.py models/ __init__.py model1.py model2.py And of course, the models work properly thanks to this: #myproject/app1/models/__init__.py: from .model1 import Model1 from .model2 import Model2 Anyway, in my model1.py module, I want to import a validator from the validators.py module. But as you can see, its one directory above. How can I do this? Preferably, I would want a solution that works in all types of filesystems. Thanks for any answers. -
Why is my base navbar doesn't show the groups that I have at /groups/?
I am trying to do a dropdown list in the base navigation bar of the groups that are available inside the /groups/ which is a ListView. The navigation bar shows the groups only when I am at /groups/ on my website. in views.py at Groups application class ListGroups(generic.ListView): model = Group context_object_name = 'All_Groups' def get_queryset(self): return Group.objects.all() in the main templates, base.html {% for group in All_Groups %} <li> <a href='{% url "groups:single" slug=group.slug %}' class='my-dropdown-list' style='color: white !important; background-color: inherit !important;'> {{group.name}} </a> </li> {% endfor %} I expect it to iterate to all the available groups that inherit from the Group class, but it only does that when I am at the directory of Groups. -
How to update a field on it's own in few days?
I am working on a project where I am accepting payments from users. The due date is 30 days from the payment date . Initially the is_due field is false but I want it to change to true without updating manually when due date is just seven days away. I have got no solution even after looking up everywhere. I am stuck with this problem. Please Help me and tell me a way to do this. Thanks. models class Payment(models.Model): username = models.ForeignKey(UserProfile,on_delete = models.CASCADE, related_name='name') amount = models.IntegerField() date = models.DateField(blank=False, default = datetime.datetime.now()) due_date = models.DateField() payment_mode = models.CharField(max_length=50, choices=PaymentModes,null=True,blank=True) collected_by = models.ForeignKey(UserProfile,on_delete = None, related_name='collected_by') is_due = models.BooleanField(default = False) def __str__(self): return self.username.user.username def save(self, *args, **kwargs): self.due_date = self.date + monthdelta(1) dt = self.due_date-datetime.date.today() if dt.days <=7: self.is_due = True else: self.is_due = False super(Payment, self).save(*args, **kwargs) -
Error during changing quantity of goods in the shopping cart
I want to add goods changing quantity functionality to my project. But I have a problem with it. It's possible to change the just only the first item in the cart. How can I make it possible to change quantity of the all goods? I think I need to get info about specific cart-item on clicking on appropriate number-plus or number-minus button? Any help or tip please. I'm a newbie Here is my template {% for item in cart.items.all %} <td class="text-center cart-table-info"> <form method="GET"> <div class="number-style"> <span class="number-minus disabled"></span> <input class="cart-item-quantity" type="number" name="quantity" value="{{ item.quantity }}" min="1" data-id="{{ item.id }}"> <span class="number-plus"></span> </div> </form> </td> {% endfor %} <script> $('.number-minus, .number-plus').on('click', function(){ quantity = $('.cart-item-quantity').val() item_id = $('.cart-item-quantity').attr('data-id') data = { quantity: quantity, item_id: item_id, } $.ajax({ type: "GET", url: '{% url "ecomapp:change_item_quantity" %}', data: data, success: function(data){ $('#cart-item-total-'+item_id).html(parseFloat(data.all_items_cost).toLocaleString(undefined, {'minimumFractionDigits':2,'maximumFractionDigits':2}) + ' руб.' ) $('#cart-total-price').children('strong').html( parseFloat(data.cart_total_price).toLocaleString(undefined, {'minimumFractionDigits':2,'maximumFractionDigits':2}) + ' руб.' ) } }) }) </script> Here is my view def change_item_quantity_view(request): cart = getting_or_creating_cart(request) quantity = request.GET.get('quantity') item_id = request.GET.get('item_id') cart_item = CartItem.objects.get(id=int(item_id)) cart_item.quantity = int(quantity) cart_item.all_items_cost = int(quantity) * Decimal(cart_item.item_cost) cart_item.save() new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': … -
Convert a function view to a Class Based View Django
I am trying to write a a Function-based View (FBV) as a Class-based View (CBV), specifically a CreateView. So far I have the Class based view created but the FBV I use takes a request and an ID so not sure how to handle that. The FBV works fine but as a CBV I think its more complicated as I need to change the data being passed to the HTML I think I shouldn't be using context but I don't know how to do it without Thanks for any help FBV def pages(request, id): obj = programas.objects.get(id=id) script = obj.script script_eng = obj.script_eng zip_scripts = zip(script , script_eng) zip_scripts_eng = zip(script_eng , script) random_zip = list(zip(script , script_eng)) random_ten = random.choices(random_zip) context = {'title': obj.title, 'show_date': obj.show_date, 'script' : obj.script, 'script_eng': obj.script_eng, 'description': obj.description, 'description_eng': obj.description_eng, 'show_id':obj.show_id, 'url': obj.url, 'random_ten': random_ten, 'zip_scripts' : zip_scripts, 'zip_scripts_eng ' : zip_scripts_eng , } return render(request, 'rtves/pages.html', context) CBV class PagesContentView(ListView): model = programas context_object_name = "show_info" template_name = 'pages/index.html' def pages(request, id): obj = programas.objects.get(id=id) script = obj.script script_eng = obj.script_eng zip_scripts = zip(script , script_eng) zip_scripts_eng = zip(script_eng , script) random_zip = list(zip(script , script_eng)) random_ten = random.choices(random_zip) context = {'title': obj.title, … -
Is there a way to query over a range based key cached object in django redis cache?
I'm working on a game server matchmaking and I have a room object which has a range that has two field and other extra fields : min_score = IntegerField (help = 'minimum score that user should have to join this room.') max_score = IntegerField (help = 'maximum score that a user can have to join this room.') I'm going to cache this object and then if a user request to join a room with a range that user can join. Is there a way that I can do something like this query on redis-cache: Room.objects.get( room__min < user.score < room__max) ? I already have some algorithms that should do .get('key') n times. But I wonder if there's a better solution.