Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Counting lines of code in a django project
I use this shell script to count the lines of code in a django project, find . -name "*.py" -type f -exec grep . {} \; | wc -l How can I modify this to not count the migration scripts. Essentially that means not count anything inside any subfolder by the name migrations Can someone help me with this. -
django - Type Error __init__ positional argument
I'm creating a blog by django, this is the error that I got recently: init() takes 1 positional argument but 2 were given Exception Location: C:\ProgramData\Miniconda3\envs\myDjanEnv\lib\site-packages\django\core\handlers\base.py in _get_response, line 124 And this is the 124th line of the code from base.py: if response is None: wrapped_callback = self.make_view_atomic(callback) try: <!-- line 124 --> response = wrapped_callback(request, *callback_args, **callback_kwargs) except Exception as e: response = self.process_exception_by_middleware(e, request) VIEWS.PY CODES: from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from blog.models import Post,Comment from blog.forms import PostForm,CommentForm from django.urls import reverse,reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView,) # Create your views here. class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' # form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' # form_class = PostForm model = Post class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True,).order_by('created_date') ############################################### ############################################### @login_required def post_publish(request,pk): post = get_object_or_404(Post,pk=pk) post.publish return redirect('post_detail',pk=pk) @login_required def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': … -
Django: urls in html form not working correctly
I am building e-commerce website, I have a shopping cart model with items, I want the customer to select the quantity of a certain item they want to buy, this is the reason I am placing everything in a form to later grab the quantity in views.py by request.POST.getlist('quantity') and pass the data to 'Sales:checkout'. But in there I also have button to delete an individual item form the shopping cart (Sales:delete_cart_item) and a button for emptying the whole cart (Sales:empty_cart). Now to the problem, when I press any of the latter buttons, be it Sales:delete_cart_item or Sales:empty_cart they all execute Sales:checkout, please help me figure out what I'm doing wrong from shopping_cart.html: <form action="{% url 'Sales:checkout' %}" method="POST"> {% csrf_token %} {% for item in items %} <td>{{ item.item.item_name }}</td> <td> <input type="number" name="quantity" min="1" max="{{ item.item.stock_level }}"> </td> <td>{{ item.item.id }}</td> <td> <a href="{% url 'Sales:delete_cart_item' item.id %}"><button>Delete row</button></a> </td> {% endfor %} <form action="Sales:empty_cart" method="POST"> <button type="submit">Empty Cart</button> </form> <button type="submit">Continue to Secure Checkout</button> </form> please ask if you need additional details -
How to get user feedback from Django 2.x ModelAdmin Action
I have an action in a ModelAdmin class. The action may have already been applied to the object selected, so I want to give the user a yes/no popup asking if he/she wants to run the action again. The action is a longish running celery task, but it may be beneficial to run the action again, or it may not. Is there a way to ask the user and get the feedback to make the action do the right thing? Thanks! Mark -
How to use alias in column name in Django
I tried several examples to rename column names before formatting result into json but none of them work. My latest code look like below def employee(request): entries = Employee.objects.annotate(First Name=F('FirstName')). only('FirstName','Email') print(entries) return render_to_response('employee.html',{'employees': serializers.serialize("json",entries, fields=('First Name','Email'))}) This code give below result [{"model": "client.employee", "pk": 1, "fields": {"Email": "employe1@gmail.com"}}] So either only() nor annotate() is not working. -
Gitlab CI - Django functional tests - splinter
I want to run some automation tests on github on a project of mine with a Django framework. Therefore I am using a Django functional test. While executing the test on my local pc works fine, my pipeline is always failing with those tests. I assumed, that chromedriver wasn't working correctly and after some research on the internet, I found out, that I need to install chrome as browser, so I modified my requirements.txt for pip like this: applescript==2018.11.19 astroid==2.1.0 autopep8==1.4.3 chromedriver==2.24.1 decorator==4.3.0 detect==2018.11.19 Django==2.1.3 flake8==3.6.0 google-chrome==2018.11.19 google-chrome-cli==2018.11.19 isort==4.3.4 lazy-object-proxy==1.3.1 mccabe==0.6.1 only==2018.11.20 psutil==5.4.8 public==2018.11.20 pycodestyle==2.4.0 pyflakes==2.0.0 pylint==2.2.1 pytz==2018.7 runcmd==2018.11.20 selenium==3.141.0 six==1.11.0 splinter==0.10.0 temp==2018.11.20 urllib3==1.24.1 wrapt==1.10.11 .gitlab-ci.yml image: python:latest before_script: - pip install virtualenv - virtualenv --python=python3 venv/ - source venv/bin/activate - pip install -r requirements.txt - cd src/ - python manage.py migrate stages: - quality - tests flake8: stage: quality script: - flake8 ./ test: stage: tests script: - python manage.py test test_functional.py def setUp(self): # LINUX x64 executable_path = {'executable_path': settings.CHROMEDRIVER_PATH_LINUX64} # chrome self.browser_chrome = Browser('chrome', **executable_path) [..] With this, a chrome browser has been installed, but now I get this error: selenium.common.exceptions.WebDriverException: Message: Service /builds/mitfahrzentrale/mitfahrzentrale/venv/chromedriver unexpectedly exited. Status code was: 127 What do I need to modify in … -
Call property or method of related model in Django
Is it possible to call property or instance method of related object in Django model? One of my models need to access 'parent's' field and show it as it's own property. To check this I've added @property to 'child' model, but unfortunately when trying to call this property in Django Admin I'm receiving: ERRORS: <class 'some_app.admin.AnotherModelAdmin'>: (admin.E108) The value of 'list_display[5]' refers to 'some_app_timestampapplied_operational_mode', which is not a callable, an attribute of 'AnotherModelAdmin', or an attribute or method on 'some_app.AnotherModel'. Simple example: class SomeModel(models.Model): strategy = Charfield(max_length=1, choices=SOME_STRATEGIES) ... class AnotherModel(models.Model): related_parent_model = models.ForeignKey('SomeModel', on_delete=models.CASCADE) @property def applied_strategy(self): return self.related_parent_model.strategy -
Heroku Pipelines and/or Travis CI
We are using Heroku to host our Django application. We also use Heroku Pipelines with continuous integration and tests running after each push to our staging. Is there any advantage/difference in using Travis CI instead? I see it in so many projects but haven't used it before. -
None model related field as SlugRelatedField to Serializer
I've added a view to create a new user, this takes a username, password, email and a slug field to link to a permission. { "username" : "TestUsername", "email" : "TestUsername@outlook.com", "password" : "Password01", "group" : "partial-permission" } The view for this request is; class CreateUserSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField(queryset=CompanyGroup.objects.all(), slug_field='slug_field') class Meta: model = User fields = ['company', 'email', 'username', 'password', 'token', 'group'] read_only_fields = ['token'] write_only_fields = ('password',) def create(self, validated_data): return User.objects.create_user(**validated_data) I'm trying to use the SlugRelatedField to link automatically to the Group passed in the slug field and pass this onto my create_user method in my model. class UserManager(BaseUserManager): def get_queryset(self): return UserQuerySet(self.model, using=self._db).active_and_not_deleted() def create_user(self, username, email, password, group=None, company=None): user = self.model(username=username, email=self.normalize_email(email), company=company) user.set_password(password) return user When doing this I'm getting the exception: AttributeError at /users/ Got AttributeError when attempting to get a value for field `group` on serializer `CreateUserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'group'. I understand that this exception explains exactly what my problem is, but I'm trying to avoid having it on the User object and manually looking … -
Handle POST and GET Mehtods in the same view with Django and Full Calendar JS
first, sorry for my bad english, i'm very redundant with my explanations because i'm newbie in this programming languaje and this community. So, let's begin, I have mounted all structure for the full calendar itself, models, views, forms, URLs, events as JSON and my HTML templates, I use Bootstrap to show a modal pop-up when I click on a empty space in a date to add a new event and works perfectly adding events to my model and rendering in JSON, the real question is: how I can do to update an existing event when I click on it? my models.py from django.db import models from apps.cusomers.models import Person class EventsCalendar(models.Model): title = models.CharField(max_length=200, null=True, blank=True) ##If the event covers all day time allDay = models.BooleanField(blank=True, null=True, verbose_name='All day event?', default=False) start = models.DateTimeField(blank=True, null=True) end = models.DateTimeField(blank=True, null=True) url = models.URLField(max_length=200, null=True, blank=True) ##colors for the events (using clasName option of full calendar) RED = 'RED' GREEN = 'GREEN' BLUE = 'BLUE' YELLOW = 'YELLOW' CIAN = 'CIAN' COLORS = ( (YELLOW, 'Pending'), (BLUE, 'Not Movable'), (CIAN, 'Movable'), (RED, 'Cancelled'), (GREEN, 'Confirmed')) className = models.CharField(max_length=15, choices=COLORS, default=YELLOW) ##If the event is editable or not editable = models.BooleanField(blank=True, null=True, verbose_name='Editable?', … -
Update the attributes of the Django Models.py from views.py
i am working on a booking system project (Django) and i want to make seats decreasing by 1 every time a user books a ticket i made seats as a variable in the train class in the models file and i made a function which decreases the seats by 1 in the same file but i don't know how or where to call it. -
django-avatar form location issue
I'm new to django/python and I'm using the django-avatar plugin (https://github.com/grantmcconnaughey/django-avatar) so users can upload images as avatars on our website. I've been trying to debug this issue for a day and I'm not sure what I'm missing. The issue I'm running into is that I copied the "change.html" form into our myaccount.html page and I get the following: "You haven't uploaded an avatar yet. Please upload one now." That's incorrect since I already have an image uploaded and all I want is the proper change form with the input field to appear that populates once an avatar is uploaded. The form I want generated appears properly when I navigate to "/avatar/change/" when i want it to be "/myaccount/change/". Does anyone have any ideas how to solve this issue? Thanks! myacccount.html <p>{% trans "Your current avatar: " %}</p> {% avatar user %} {% if not avatars %} <p>{% trans "You haven't uploaded an avatar yet. Please upload one now." %}</p> {% else %} {% endif %} <form enctype="multipart/form-data" method="POST" action="{% url 'avatar_add' %}"> {{ upload_avatar_form.as_p }} <p>{% csrf_token %} <input type="submit" value="{% trans " Upload New Image " %}" /> </p> </form> views.py from django.shortcuts import render from django.http import … -
Why does queryset=Post.objects.all() evaluate to Error when queryset is set to Post.objects.all()?
when i set queryset=Post.objects.all() the Post class show error that is"/d:/Programming/Python/Python_WorkPlace/New_django_project/posts/views.py", **"message": "Class 'Post' has no 'objects' member"** -
Issues in creating a dynamic table in report lab that continue printing its values on a next page
I have a table and i want it to print the values on a new pdf page once it reaches maximum page size, i have used report lab canvas and set the table into the canvas. Why we are using Wrapon an DrawOn? My code: buffer = io.BytesIO() p = canvas.Canvas(buffer) data = [ ['begin', 'begin', 'begin', 'begin', 'begin'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['end', 'end', 'end', 'end', 'end'], ] t = Table(data, style=[ # ('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.blue), # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'), # ('ALIGN', (3, 1), (3, 1), 'CENTER'), # ('ALIGN', (3, 2), (3, 2), 'LEFT'), ] ) #What do they mean? t.wrapOn(p, 220, 400) t.drawOn(p, 220, 400) p.save() buffer.seek(0) return buffer -
How to add Tags in place of groups to Django posts
Intro: I have a simple project with User, Post and Group. Users can make posts and they have to choose which group the post will belong to. Members (Users) can join and leave groups. If members join a group they see all new articles in that post on their wall. Members cannot create a new Group. They have to select from Existing groups to which their post will belong example: A post on football will belong to the group Football What I want: I want users to be able to link one post to multiple existing groups example: A post on what to eat before a big game.(This post can belong to 3-5 different groups like Football, Soccer, Rugby, Hockey etc). Similar to the Stackoverflow style where you can choose upto 5 tags for your questions. This way this post will belong to all 5 groups. See image below I want to achieve something exactly like this. My Post and Group Models below: class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() class Group(models.Model): name = models.CharField(max_length=250, unique=True) description = models.TextField(default='', blank=True) members = models.ManyToManyField(User, through='GroupMember') class GroupMember(models.Model): user = models.ForeignKey(User, related_name='membership') … -
How do I prevent Django's admin interface from silently suppressing errors?
Suppose I have a simple Django model: class MyModel(Model): created = models.DateTimeField(default=datetime.utcnow) @property def my_property(self): raise ValueError('Is anyone there') Then in my admin GUI, I show my_property as a read-only field. @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): ... readonly_fields = ['my_property'] To my surprise, if any exception is raised in generating a value in the Django admin GUI, Django suppresses the error and just shows a "-" as the value. It took me some time to realize this was the case. Is there a way to force Django to show exceptions when exceptions occur? -
Django - PubSub or workflows or combined?
I am building a chemistry application with django that focuses on reactions. It bonds an atom to an existing molecule. The reaction event triggers a bunch of (a) validations to make sure the feasibility of the molecule checks out (b) subsequent events as the molecule Nested Functions: So I could have my logic layer just keep feeding Python functions into other Python functions, but my fear is that this will become a tangled mess quickly. I also want to have a record of the steps with success/fail and other basic stats, so one hanging process is probably not the best. PubSub: So I could have multiple functions that subscribe/ listen for a reaction and then run/ don't run based on criteria. Using something like django-redis-pubsub. Workflows: Enter workflows. I suppose I could structure the whole reaction process as a giant workflow which would have better transaction atomicity? Should I combine this approach with a pubsub? rule NAME: input: "path/to/inputfile", "path/to/other/inputfile" output: "path/to/outputfile", "path/to/another/outputfile" script: "path/to/script.py" -
How to update python code and see changes live using daphne, Django Channels?
I just made some changes over 1 python file in my production server, then tested the changes using "runserver" command: python3 manage.py runserver 0.0.0.0:3031 The changes are done correctly, then I try to see the same changes in production but using websockets with Django Channels, but the result seems to be that the server is running the old code. daphne -b 0.0.0.0 -p 3031 asgi:channel_layer What could be the reason, is there any code cache?, what can I do to refresh the code? -
Where do files created in Django go?
I have a view where I create a file (call it .something.txt). I see that I can access it from another view as well. Also, it is in the same folder where I have my manage.py. I am trying to understand whether someone from outside can have access to this unencrypted file and how they can get it? Is what I am doing safe, from a privacy perspective, if I store the data as an encrypted text file in the same way? -
Django ViewSet filtering with Foreign Key name
I have 2 Django models with the following structure: class Title(models.Model): id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=256) class Component(models.Model): id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=256) title = models.ForeignKey('Title', on_delete=models.PROTECT) So i have a ComponentViewSet as follows: class ComponentViewSet(viewsets.ModelViewSet): queryset = Component.objects.all() serializer_class = ComponentSerializer filter_fields = { 'id': ['exact'], 'name': ['exact', 'istartswith'], 'title': ['exact'], } So if i want to filter Components via Title the URL is http://localhost:8010/api/components/?title=1. How can I make a view filtering with Title.code value i.e http://localhost:8010/api/components/?title=Test ? -
utf-8 codec can't decode BinaryField from database
I'm currently trying to get a Binary data from the database using the Django ORM. In addition to CharFields, the model also has a BinaryField. When i get my QuerySet, i cannot convert it to a list, Django trows DjangoUnicodeDecodeError. There is any way to decode the BinaryField and convert the QuerySet into a List? models.py class TBL_Form(models.Model): name = models.CharField(max_length=150, blank=True, null=True) category = models.CharField(max_length=64, blank=True, null=True) geometry = models.BinaryField(blank=True, null=True) class Meta: managed = False db_table = 'Form' views.py query = TBL_Form.objects.filter(TBL_Entity).select_related().values_list('id', 'geometry') [item for item in query ] Error DjangoUnicodeDecodeError at / 'utf-8' codec can't decode byte 0xba in position 14: invalid start byte. You passed in b'\x01\x00\x00\x00\x01\x02\x00\x00\x00\x03\x00\x00\x00"\xba\x07W\xb7\xf2\xf2\xc0\xab\x13\xdcW\xfd}\xfc\xc0\xe6yz\xe9\xbb\xf3\xf2\xc0k\x91f4u~\xfc\xc0\xaeM\r\xa2\xfa\xf3\xf2\xc0,wR\x0e\x92~\xfc\xc0' () -
Django CreateView request pass
I'm using django-better-form. A great tool for multi form support. One problem is I want to pass request to the modelform. Using kwargs.pop("request") I faced KeyError. How to fix this -
Django safe filter breaks jinja template
<p class="card-text"> {{ blog_post.description_from_content|safe}} </p> The above comes from the Django/Mezzanine web framework The above will render an empty p tag, and place the contents outside the p tag. If you remove the safe filter then it renders as expected. (inside the p tag). Any idea why this is happening? I can't just remove safe as the content contains html How it renders -
Django 2.1.3 Error: __init__() takes 1 positional argument but 2 were given
i am trying to develop a website whith Django 2.1.3 and python 3.7.1 When i go to the homepage i get this error: TypeError at / __init__() takes 1 positional argument but 2 were given Here some details about the code i write: Trceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) Exception Type: TypeError at / Exception Value: __init__() takes 1 positional argument but 2 were given core/models.py This is just one table on DB: from django.db import models class Evento(models.Model): titolo_evento = models.CharField(max_length=30) data_inizio = models.DateTimeField() data_fine = models.DateTimeField() def __str__(self): return self.titolo_evento class Meta: verbose_name = 'Evento' verbose_name_plural = 'Eventi' core/views.py Here i want to see the DB "Eventi" on the homepage only if the user is authenticated, i think the mistake is here, but i don't know where: from django.contrib.auth.decorators import login_required from .models import … -
Integrating Oracle JET with Django
I have created / downloaded the Oracle JET NavBar example with NPM. I have copied and setup the CSS and JS assets in Django and setup the baseURL in require.js to get the static files from django the right way. All seems to work fine, except that the DOM Listener (DOMContentLoaded) does not work. Seems to have something to do with Backbone.JS etc. Has anyone an example if how to setup Oracle JET with Django properly? Thanks!