Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass active user to Django ModelForms
In my form, I must filter the "tenant" choice field so that it displays only tenants associated to the active user's organization. So I'm simply passing an extra argument to the form constructor. This works as expected when I load (GET) the form. But when I submit (POST) the form, I keep getting the following error: AttributeError: 'NoneType' object has no attribute 'organization_profile' Any idea what's provoking this? Views.py def create_booking(request): if request.method == "POST": form = BookingCreateForm(data=request.POST) if form.is_valid(): data = form.cleaned_data booking = Booking.objects.create( status=data['status'], tenant = data['tenant'], apartment = data['apartment'], check_in = data['check_in'], check_out = data['check_out'], rent = data['rent'], ) booking.save() return redirect('dashboard:dashboard') else: form = BookingCreateForm(user=request.user) return render(request, 'accounts/booking_form.html', {'form': form}) Forms.py class BookingCreateForm(forms.ModelForm): class Meta(): model = Booking fields = '__all__' def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(BookingCreateForm, self).__init__(*args, **kwargs) organization = self.user.organization_profile self.fields['tenant'] = forms.ChoiceField(choices=[ (tenant.id, tenant.name)) for tenant in TenantProfile.objects.filter(organization=organization) ]) -
Is it possible to add values to context into a for loop?
I have a for loop to iterate a list. In every iteration i have a different value, and i want to add this value to my context. I'm trying using context.update, but every time this returns an empty context. def get_context_data(self, **kwargs): context = super(Board_dets_view, self).get_context_data(**kwargs) id_board = self.object.id context['column_list'] = Column.object.filter(board_id=id_board) clist = Column.object.values_list('id', flat=True).filter(board_id=id_board) cCard = Card.object print(clist) for i in range(0, clist.count()): print('i=%s',i) cCard = Card.object.filter(column_id = clist[i]) print('cCard=%s',cCard) context.update({'card_list': cCard}) print(context) return context cCard returns correct data. The only thing I need is to store what come from cCard to context['card_list'], but evert attempt i made, was an empty result. -
What is the best method to change an img src using javascript with django?
I can get the img src to change using onclick and a hard path without django template tags. It's my impression this is bad practice. How can I get "{% static 'indv_proj\Metron Pres\Slide3.JPG' %}" format injected/changed into the html img src everytime I click the image? JavaScript: $(document).ready(function(){ $("#indv-ppt").click(function(){ // Change src attribute of image $(this).attr("src", "{% static 'indv_proj\Metron Pres\Slide3.JPG' %}"); }); }); HTML: <div class="ppt-slides"> <img id= indv-ppt src="{% static 'indv_proj\Metron Pres\Slide1.JPG' %}" alt="Error"> </div> -
How do I get django "Data too long for column '<column>' at row" errors to print the actual value?
I have a Django application. Sometimes in production I get an error when uploading data that one of the values is too long. It would be very helpful for debugging if I could see which value was the one that went over the limit. Can I configure this somehow? I'm using MySQL. It would also be nice if I could enable/disable this on a per-model or column basis so that I don't leak user data to error logs. -
Does Django have a Migration History separate from the django_migrations DB table?
I'm in the process of changing an app name in Django and running into this InconsistentMigrationHistory exception. The first thing I did, described in this SO answer, was change the name of the app directory and all references to the app. I made some SQL statements to rename account to authentication in the django_content_type table and the django_migrations table. After doing these things, I try python manage.py makemigrations and get the InconsistentMigrationHistory exception shown below. Traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "/Users/ramonaspence/.local/share/virtualenvs/chefs-notebook-2vB4UyAE/lib/python3.7/site-packages/django/db/migrations/loader.py", line 306, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration account.0001_initial is applied before its dependency authentication.0001_initial on database 'default'. Here, account is the old app name and authentication is the new app name. With this exception, my first idea was that there must be a migrations file in account that uses the authentication.0001_initial migration as a … -
I have Syntax Error When I edit django messages
I want to edit django error mesages like class error mesages.But when I add if controller in HTML documents, I meet syntax error Note: (just when I use if controller I have syntax error) Views content; from django.contrib import messages if request.method=="POST": form = RegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("passowrd") newUser = User(username = username) newUser.set_password(password) newUser.save() login(request,newUser) messages.success(request,"Kayıt Başarılı") messages.warning(request,"DANGER") return redirect(index) context ={ "form":form } return render(request,"register.html",context) Note: I added 2 messages for try when I don't add if controller its working Layout content; {% if messages %} {% for message in messages %} {% if message.tags=="warning"%} <div class="alert alert-danger">{{ message }}</div> {% else %} <div class="alert alert-{{ message.tags }}">{{ message }}</div> {% endif %} {% endfor %} {% endif %} Error output: Could not parse the remainder: '=="warning"' from 'message.tags=="warning"' -
Gunicorn and django - Multiprocessing issue
I am running a django instance through Gunicorn. in this Django project, I have a view that starts a multiprocessing task in background that is fetching some data every x milliseconds, and stops after x seconds if no new request have been received. Using runserver, I have no problem, my multiprocessing continues to work as expected and my view fetch the data from this multiprocessing without any problem. but when I switch to Gunicorn, it seems that when I request my view, it doesn't detect that the process is already running and tries to start a new one in parallel, returning wrong values. Do you have any clues where the problem could come from? no. of workers? no. of threads? thank you, -
Django auth permissions
How can I make the Django model available by default, for users (Staff = True), to make available CRUD actions in the admin panel? I wrote some code based on the Django authentication system: from django.db import models from django.contrib.auth.models import AbstractUser from .manager import CustomUserManager from django.urls import reverse from pytils.translit import slugify class CustomUser(AbstractUser): username = None # removing username field email = models.EmailField(unique=True) is_staff = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class _TimedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta(object): abstract = True class Post(_TimedModel): title = models.CharField(max_length=100) body = models.TextField() slug = models.SlugField(null=False, unique=True) author = models.ForeignKey('blog.CustomUser', on_delete=models.CASCADE, related_name="post") objects = models.Manager() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta(object): verbose_name = 'Post' verbose_name_plural = 'Post' def str(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) Then I created a user registration, added the Post model to the admin panel. This is the admin.py file from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser, Post class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( … -
Broken images in Django
I have a problem with my images, which started when I changed a part of my code in view.p (API) from: class PostListView(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer to: @api_view(['GET']) def PostListView(request, *args, **kwargs): queryset = Post.objects.all() username = request.GET.get('username') if username != None: queryset = queryset.filter(author__username__iexact=username) serializer = PostSerializer(queryset, many=True) return Response(serializer.data, status=200) I did this because I wanted to pass "username" into it and I dont know how to do that using APIView, so i used this, but then my images are broken and i notice with the APIView, the images url starts from "127.0.0.1/8000/..." but with this new view the url is "localhost/...." which i think is the problem. How do i go about it please -
how to run python/djanjo shell as a script
In a tutorial on django we create a simple table run migrations and then go into a shell with the command: python manage.py shell from there, in the shell we run the following: from flights.models import Flight f = Flight(origin="New York", destination="london", duration=415) f.save() I'm trying to figure out how to run these commands from a py file so I created test.py: from django.apps import apps from flights.models import Flight apps.get_model('flights', 'Flight') f=Flight(origin="New York",destination="London", duration=415) f.save() but get the error Models aren't loaded. How to resolve? -
why the sentence if form.is_valid(): never pass. i have tried many thing, changing the python version for example and always is the same
When I run the code, it never pass the sentence if form.is_valid(): I have changed the version of python, but it is still the same views.py def login_page(request): form = Loginform(request.POST or None) context = { "form": form } print("User logged in") if form.is_valid(): # print("form is validated") print(form.cleaned_data) # print("form cleaned data") username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") forms.py from django import forms class Loginform(forms.Form): username = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) view.html <div class='container'> <div class='row'> <div class='col'> <p>{{ content }}</p> <div class='col-sm-6 col-12'> <form method='POST'> {% csrf_token %} {{ form }} <buttom type='submit' class='btn btn-default'>Submit</buttom> </form> </div> </div> </div> </div> # The form looks well, same the submit. I do not see the error please help me to undertand what happens with this sentence of form_is_valid -
How can I save a model instance that references itself in django?
I have the following code: from django.db import models class MyModel(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name='parent') In some cases, I would like the model to be its own parent. This may be done by saving the model and then assigning the parent, but I need this to be done before saving, since there is some code that depends on post_save signal and that needs the model's parent info. -
Django 3.1 How to solve template mapping in settings.py
As you can see in the below Django code of settings.py I'm trying to map the templates with it, but I can't be able to that. When I am running the server it is showing the error. Terminal: It is showing look like.. IndentationError: unexpected indent. -
Django Rest Framework - returning raw bytes image from view
I have a view that returns an image (I'm aware that it might be a bad practice. But it's necessary in my case). Using normal Django HttpResponse I just return: # img is bytes response = HttpResponse(img, content_type="image/jpeg") response['Access-Control-Allow-Origin'] = '*' return response I want to use DRF since most of my views use it as well. I tried to just replace HttpResponse with Response but it crashed with 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Is there another way to do that? Should I even use DRF for returning this kind of data or should I stick to raw Django HttpResponse? One last thing, I have the same problem with other buffer types. E.g HttpResponse(content_type='text/csv') and response = HttpResponse(content=excel, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'inline; filename=filename.xlsx' return response Is there some general solution for these cases? -
Reverse for 'surveyanalysis' with arguments '('',)' not found. 1 pattern(s) tried: ['surveyanalysis/(?P<Survey_Question_No>[0-9]+)/$']
my html template looks like this: <a href="{% url 'SurveyAnalysis:surveyanalysis' Survey_Question_No %}">ANALYZE RESULTS</a><i class="fa fa-long-arrow-right" aria-hidden="true"></i> views.py look like this def surveyanalysis(request,Survey_Question_No): surveyresponse = get_object_or_404(SurveyResponseDetails, id=Survey_Question_No) # start working for Chart labels = [] #empty labels for storing labels data = [] #empty data for storing data default_data=[] #empty default_data for storing default_data default_labels=[] #empty default_labels for storing default_labels #filtering total Radio type Question Responses queryset = SurveyResponseDetails.objects.order_by('Survey_Question_Desc').values('Survey_Question_Answer').filter(Survey_Question_No=Survey_Question_No).annotate(Survey_Question_Desc_count=Count('Survey_Question_Desc')) for response in queryset: data = list(queryset.values_list('Survey_Question_Desc_count', flat=True)) labels = list(queryset.values_list('Survey_Question_Answer', flat=True)) return render(request, 'survey-analysis/surveyanalysis.html', { 'surveyresponse':surveyresponse 'labels': labels, 'data': data, }) my urls look like this from django.urls import path from django.conf.urls import url from django.contrib import admin from . import views from django.views import View app_name='SurveyAnalysis' from django.contrib.auth import views as auth_views urlpatterns = [ path('surveyanalysis/<int:Survey_Question_No>/', views.surveyanalysis, name='surveyanalysis'), path('question', views.surveyanalysis, name='question'), ] Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated. -
How to get username in a variable forms.py Django
So i am trying to fill in a model variable in from by default. I need the current logged in username in master_id = #here# i am not able to use request. Please help. from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from django.db import transaction from django.contrib.auth import get_user_model from .models import User, Shop class ShopRegister(UserCreationForm): first_name = forms.CharField(required = True) last_name = forms.CharField(required = True) firm = forms.CharField(required = True) email = forms.CharField(required = True) contact = forms.CharField(required = True) details = forms.CharField(required = True) lid = forms.CharField(required = True) master_id = #need my username here############## class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.employee = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.firm = self.cleaned_data.get('firm') user.email = self.cleaned_data.get('email') user.contact = self.cleaned_data.get('contact') user.details = self.cleaned_data.get('details') user.lid = self.cleaned_data.get('lid') user.save() shop = Shop.objects.create(user=user) shop.master_id=self.cleaned_data.get('master_id') shop.save() return user -
TypeError at /api/v1/usuarios
I'm new to python and Django. But I already have prior knowledge. I am making an application as a backend using django rest. But there was an error that I am unable to resolve. Just below I show the error. And the code is below too. If you can help me I would appreciate it. Thank you. urls.py path('usuarios', UserAPIView.as_view(), name='usuarios'), views.py class UserAPIView(APIView): """ API de usuario """ def get(self, request): usuarios = User.objects.all() serializer = UserSerializer(usuarios, many=True) return Response(serializer.data) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['url', 'username', 'email'] -
My s3 images will not display on my django site
My web application is using django and s3. When I attempted to access my s3 images on AWS via the public bucket. Everything else works except for the simple secure storage (s3) bucket. I have this error: <Error> <style class="darkreader darkreader--safari-fallback">...</style> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>DAD37CB20E79C307</RequestId> <HostId> tuZqmK2Ei6dvMify2V2LoGmJxJ33UemNknXnH2DM4YzfqS3MNuvmLJJVq5SmUTr5976TkWpeHpc= </HostId> </Error> https://framann-quilting-place.s3.us-east-2.amazonaws.com/media/products/carousel/SewingKit.jpg -
Should I add my API NGINX sites-available config to the same file as my Django NGINX sites-available that will be used for production?
I made an API using postgREST, it's based off of my postgres database schema, and it connects to my database via a PRIVATE network. I only want the API to be used internally, only my servers should be able to access the API and present it to the client, I don't want to outside world to access it. Here is my NGINX file for my domain: /etc/nginx/sites-enabled/default server { listen 80; server_name SERVER_PUBLIC_IP_ADDRES; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /directory/to/django_webapp; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Below is an example of how postgREST advices users in their documentation to using NGINX. http { # ... # upstream configuration upstream postgrest { server localhost:3000; } # ... server { # ... # expose to the outside world location /api/ { default_type application/json; proxy_hide_header Content-Location; add_header Content-Location /api/$upstream_http_content_location; proxy_set_header Connection ""; proxy_http_version 1.1; proxy_pass http://postgrest/; } # ... } } As you can see in the code comment, it says expose to the outside world, Which I don't want to do. So then again, do I really need to add this portion of the code to my Django nginx? The API … -
How can i make customer chat option in a ecommerce website by django?
want backend end frontend html code Like this customer chat option https://i.stack.imgur.com/gaLEd.png -
Set default start page in Paginator Django
I have a list of projects. When I enter into details of one of them then I would like check others using next page. The problem I have is that it doesnt matter which one I click on I always start from the first page (first project) The documentation of Paginator class I found in django docs is very small and I would like to find the way to indicate which page display, ex. if I click on object with id=3 I should see <Page 3 of 8>. def project_detail(request, id): projects = Project.objects.all() paginator = Paginator(projects, 1) page = request.GET.get('page') project = paginator.get_page(page) return render(request, 'portfolio/projects/detail.html', 'project': project}) I woud like to implement this part of code inside: paginator.page(id) if it`s posible, but sincerly dont know how. -
django model forms how to use PK within the forms (forms.py)?
I want to do the following validation in a django model form: class BookUpdateModelForm(forms.modelForm): #[... a lot of stuff ...] def clean_title(self): title = self.cleaned_data.get("title") objectId = self.cleaned_data.get("id") if title in Book.objects.values_list('title', flat=True): book = Book.objects.get(title=title) if book.id != objectId: raise forms.ValidationError( "Este título ya esta tomado. Si requiere utilizarlo pongase en contacto con el administrador del sitio." ) return title Originally i was using this to try avoid repeated titles: class BookUpdateModelForm(forms.modelForm): def clean_title(self): title = self.cleaned_data.get("title") if title in Book.objects.values_list('title', flat=True): raise forms.ValidationError( "Este título ya esta tomado. Si requiere utilizarlo pongase en contacto con el administrador del sitio." ) return title But as you can guess the validation error poped up when i was trying to update the book model. Then i opted to Make 2 separated ModelForms, one to update and one to create. The first piece of code is from the update and is where i am finding my self in trouble. I can not access the id of the Object i am updating within the form. My template have the following lines: <!--auto select the current user to foreignkey in model--> <input type="hidden" name="user" value="{{user.id}}" id="my-id-user"> <!--auto select the current object to validate in … -
Postman and django rest framework (rest-auth)
postman drf I am reaching same url with drf and postman but fields are different.I don't understand why. (screenshots are under links postman and drf) -
can we write ORM queries without data?
from django.contrib.auth.models import User from django.db import models class CUser(User): score = models.IntegerField() The custom user has an additional field (“score”), we want to do the following operations using ORM queries only. Every answer must have a single query: Calculate the mean score of all users. Find the user with the highest score. Find if there is any user with score less than 2 (return True/False) Find all the users which have score exactly equal to the mean score. Change the score value of all users in a single query to 100 (one hundred) Find all the users which don't have score 10 or 20 Print a list of all the score values from all users excluding the first 10 users. Answers: 1. 2. 3. 4. 5. 6. 7. -
Cannot fix django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I run the following line of code on a dcker container: RUN python3 manage.py sitetree_resync_apps --settings=sites.production.settings and I get the following error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/xxx/xxx/invoicing/apps.py", line 10, in <module> from xxx.site.signals import resource_event, notify_by_email File "/xxx/xxx/site/signals.py", line 12, in <module> from xxx.backend.email import send_email File "/xxx/xxx/backend/email.py", line 11, in <module> from post_office import mail File "/usr/local/lib/python3.6/site-packages/post_office/mail.py", line 13, in <module> from .models import Email, EmailTemplate, Log, PRIORITY, STATUS File "/usr/local/lib/python3.6/site-packages/post_office/models.py", line 27, in <module> class Email(models.Model): File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 136, in check_apps_ready …