Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django do not save thumbnails from imagekit
from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill class Image(models.Model): image = models.ImageField(upload_to='home/', blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(50, 50)],format='JPEG', options={'quality':60}) when I uploading image. Everything OK with original image. But there is no thumbnail image. I guess this problem is related with cache. Maybe I am wrong. Can't figure out what to do... Please help. -
Django crispy-form changes lay on production server
I cannot seem to understand why crispy-form has changed the layout on my production server vs. the test server. Looking at the html code the only thing I can see is that classes for the form list is changes on the production server. Production Server HTML <div id="div_id_pants" class="control-group"> <label for="id_pants" class="control-label "> Test Server HTML <div id="div_id_pants" class="form-group"> <label for="id_pants" class=""> also noticed that on the test server there is a css file forms.scss.171 that provides the form-group class. Which is not being listed at all on the production site. Any info on where this might be mismatching would be greatly aprieciated. It doesn't look very good atm :( -
HTML file not understanding Django content
I'm using Django in HTML file. Normally whatever IDE you use, understands the syntax the highlights "load" in {% load xxxxx %}. But in my case, Pycharm or Intelllij Idea is not understanding the syntax and the output file too give a result as text, {% load xxxxx %} included in the result page. The environment I am using I have already included Django in that. I'm not able to understand the issue. Can anyone please help me with this -
TypeError: argument of type 'function' is not iterable : django error
i am creating an api for polls app and i struck into this error.TypeError: argument of type 'function' is not iterable : django error my models:how can i deal with it ..it seems like there is no error in code . from django.db import models from django.contrib.auth.models import User class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) def __str__(self): return self.choice_text class Vote(models.Model): choice = models.ForeignKey(Choice, related_name='votes', on_delete=models.CASCADE) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) voted_by = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ("poll", "voted_by") my views: from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from .models import Poll def polls_list(request): MAX_OBJECTS = 20 polls = Poll.objects.all()[:MAX_OBJECTS] data = {"results": list(polls.values("question", "created_by__username", "pub_date"))} return JsonResponse(data) def polls_detail(request, pk): poll = get_object_or_404(Poll, pk=pk) data = {"results": { "question": poll.question, "created_by": poll.created_by.username, "pub_date": poll.pub_date }} return JsonResponse(data) -
How to find whether django hits db [duplicate]
This question already has an answer here: Force evaluate a lazy query 2 answers As per my knowledge, django querysets are lazy and wont hit db until evaluated, in such case after assigning the queryset to a key in a dict, will the following lines cause db to be hit everytime? Please advice abc = model1.objects.all() content = { 'entry' : abc, # Once assigned will the below lines hits db? 'entry_count' : abc.count(), # will this hit db 'entry1_count' : abc.filter(name__icontains = 'a').count(), # will this hit db 'entry2_count' : abc.filter(name__icontains = 'b').count(), # will this hit db again? } return render(request, template, content} -
How to show number of rows in django
I have 6 tables and I had grab the total no of rows like this genre=Genere.objects.all().count() mood=Mood.objects.all().count() artist=Artist.objects.all().count() song=Song.objects.all().count() customuser=CustomUser.objects.all().count() favorite=Favorite.objects.all().count() Now I want to show number of rows in view so I try directly {{genre}} but it's saying name 'Genere' is not defined -
Django ORM unable to retrieve database model instances
I am working on a custom user model that subclasses AbstractBaseUser and a custom model manager that subclasses BaseUserManager.This model, Employee, authenticates by email address - USERNAME_FIELD is set to email. While I can create Employee instances and check my PosgreSQL DB to verify they are being saved, I am unable to retrieve them with the Django ORM and my custom model manager. If I try to retrieve all the employees, or 'get' one employee when running Employee.objects.get(id=1), I get an error that from_db_value() expected 4 arguments but received 5. I am stumped here. I had this same kind of custom user in another Django 1.11 app and worked fine. I have spent two days trying to resolve this. Any help? models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from phone_field import PhoneField from django.core.validators import RegexValidator # to ensure leading zeroes are captured in badge number numeric = RegexValidator(r'^[0-9]*$', 'Only numeric characters are allowed.') # Create your models here. class EmployeeManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) … -
CharField(editable=False) with local variable as deault
im new to django and am trying to figure out how to add a specific field to a django model. I want to upload a csv document and save its headers. As you can see, i want to use the headers i send with the document, or if they arent send, the ones from the first line of the document. from django.db import models class CSV_API_DB(models.Model): headers = models.CharField(max_length=250, blank=True) delimiter = models.CharField(max_length=1, default=';') filefield = models.FileField(upload_to='uploads/', max_length=100, default='empty') actual_headers = '' def __str__(self): actual_headers = '' if not self.headers: file_path = str(self.filefield) file = open(file_path) for line in file: string_line = str(line[:-1]) actual_headers = string_line.split(self.delimiter) break else: actual_headers = self.headers.split(self.delimiter) return str(actual_headers) true_headers = models.CharField(max_length=250, default = str(actual_headers), editable=False) The issue seems to be, that true_headers does not get overridden from the '__ str __' function, since the values in the database for true_headers are always just empty strings. -
Github doesn't change the database in our teams django environment
Our team is using a django environment to develop a website, the main issue is one team member recently updated one of the databases and the change will not care through mysql. We are literally on the same branch but the database tables are completely different. We are using the current version of django, python, and mysql are the development environment and github to share work. -
debug=true django not showing errors on deployment
My site has been deployed successfully on linode. All pages are working just fine, but except for one particular url. Whenever I click on that link, it gives an internal server error without showing any error messages even though DEBUG=TRUE. But when I go to a non existing url Django shows the errors. Here is the error log: [Tue Nov 19 09:18:37.378891 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] mod_wsgi (pid=22728): Exception occurred processing WSGI script '/home/shahid/django_project/djecommerce/wsgi.py'. [Tue Nov 19 09:18:37.379959 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] Traceback (most recent call last): [Tue Nov 19 09:18:37.380186 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner [Tue Nov 19 09:18:37.380235 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = get_response(request) [Tue Nov 19 09:18:37.380283 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response [Tue Nov 19 09:18:37.380330 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = self.process_exception_by_middleware(e, request) [Tue Nov 19 09:18:37.380388 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] File "/home/shahid/django_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response [Tue Nov 19 09:18:37.380435 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] response = wrapped_callback(request, *callback_args, **callback_kwargs) [Tue Nov 19 09:18:37.380567 2019] [wsgi:error] [pid 22728:tid 139877682562816] [remote 112.79.92.38:43204] … -
Django Register Issues
I receive this error after registering. AttributeError at /accounts/register/ 'AnonymousUser' object has no attribute '_meta' When I look at the admin panel, the user seems to be registered. But no password. I added the required codes below. Where am I doing wrong? Thanks. forms.py from django import forms from django.contrib.auth import authenticate from django.contrib.auth.models import User class LoginForm(forms.Form): username = forms.CharField(max_length=100, label='Kullanıcı Adı') password = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('Kullanıcı adını veya parolayı yanlış girdiniz!') return super(LoginForm, self).clean() class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, label='Kullanıcı Adı') password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'password1', 'password2', ] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Parolalar eşleşmiyor!") return password2 views.py from django.shortcuts import render, redirect from .forms import LoginForm, RegisterForm from django.contrib.auth import authenticate, login def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return redirect('home') return render(request, 'accounts/form.html', {'form': form, 'title': 'Giriş Yap'}) def register_view(request): form = RegisterForm(request.POST … -
Python Django strangely does mapping towards unexpected URL
I tested 1st Django web app project. That app project does mapping towards http://127.0.0.1:8000/api/ when the URL of http://127.0.0.1:8000 comes The test was successful. And then, I tested 2nd Django web app project. That Django app should have performed mapping towards http://127.0.0.1:8000/blog/ when the URL of http://127.0.0.1:8000 occurs. But Django strangely moves towards http://127.0.0.1:8000/api/ which was target URL of 1st Django web app. There is no /api/ URL configuration in 2nd project Following code snippets are URL configuration of 2nd Django web app # AskDjango_webfrontend_begin/askdjango/urls.py urlpatterns = [ path('admin/', admin.site.urls), # If the client enters in "localholst:8000", the page is redirected to localholst:8000/blog/ path("", RedirectView.as_view(url="/blog/", permanent=True)), # If the client enters in "localholst:8000/blog/", connect to blog.urls.py path("blog/", include("blog.urls")), ] # AskDjango_webfrontend_begin/blog/urls.py urlpatterns = [ path("",views.index,name="index"), path('<int:pk>', views.post_detail, name="post_detail") ] -
Django: How to store user specific data like bookmarks, questions
I just learned the basic authentication system in django. I am trying to make a learning website where the user can add courses and ask questions. How do I make the user authentication in a way that each user can have different data on the courses they have added(course completed %, you were views the chapter # etc) and can see all of these in their dashboard. I would also like to have a community for the users to discuss and ask questions. I would be really thankful if someone could explain the courses part to me in a simple way or if there's a link to the topic already on stack overflow or any other website please link it here. Thanks in advance. -
Celery Tasks Won't Purge Properly and Keep Restarting
have a frustrating problem with Celery I was hoping you can help me with. I'm using Redis as my message broker and am using celery in conjunction with Django and celery-beat. I tested a periodic job before that had a mistake in it and could not succesfully run. I terminated celery, typed celery flush, flushed redis and have restarted and million times. No matter what I do, everytime I start celery backup, my old child processes start right where I left them (I think, see console log below). I cannot figure out how to make these things go away! I want every child process that was ever run to DIE! Any suggestions? [2019-11-18 19:50:03,432: INFO/SpawnPoolWorker-3] child process 15748 calling self.run() [2019-11-18 19:50:03,435: INFO/SpawnPoolWorker-1] child process 14028 calling self.run() [2019-11-18 19:50:03,442: INFO/SpawnPoolWorker-8] child process 24924 calling self.run() [2019-11-18 19:50:03,445: INFO/SpawnPoolWorker-11] child process 19120 calling self.run() [2019-11-18 19:50:03,445: INFO/SpawnPoolWorker-2] child process 12808 calling self.run() [2019-11-18 19:50:03,447: INFO/SpawnPoolWorker-4] child process 20976 calling self.run() [2019-11-18 19:50:03,452: INFO/SpawnPoolWorker-7] child process 27288 calling self.run() [2019-11-18 19:50:03,453: INFO/SpawnPoolWorker-6] child process 3104 calling self.run() [2019-11-18 19:50:03,457: INFO/SpawnPoolWorker-5] child process 16752 calling self.run() [2019-11-18 19:50:03,459: INFO/SpawnPoolWorker-9] child process 18144 calling self.run() [2019-11-18 19:50:03,475: INFO/SpawnPoolWorker-12] child process 17232 calling self.run() … -
How to debug Django with allauth package error
I am struggling with an error all day long. I have a Django app deployed on Heroku. Everything works perfectly offline with the social authentication. When I deploy the application I receive an error: SocialApp matching query does not exist. I have tried settings the SITE_ID but nothing changes. Also I have checked that my DB have the Site objects created. Any help would be appreciated. -
Using prefetch_related on specific attributes?
I have the following code: pictures_of_model: Model3D.objects.prefetch_related('Pictures') Pictures is another table in which I store id's for pictures, the pictures themselves in an ImageField and an modelid that is a foreign key. How do I make sure that django prefetches the attribute with the ImageField and not the id of the picture? pictures_of_model: Model3D.objects.prefetch_related('Pictures').picture that can't be correct, right? Picture is my ImageField that holds, well, the picture. I appreciate every answer that helps me learn, thank you! -
Django Rest Framework : Only last record is saved in DB when trying to call "perform_create" function iteratively
I'm newbie in Django and trying to build API server using Django Restframework. With sincere help from @cagrias, I got a success in parsing json and save several records in my DB. Now, I'm struggle in saving multiple records in my DB with iteratively call 'perform_create' function. My View.py function is as follows. models have 6 tables BankA, BankB, BankC, and CardA, CardB, CardC. What I want to is save 4 records when call the post api, but now, only last one(('카드매출', sales_card)) is saved. I hope your help, and it will be very grateful for me. Thank you. # API to save trading history (aggregated Purchase/Sales for Bank/Card) class SalesAndPurchaseInPeriodListView(ListCreateAPIView): def post(self, request): quiry = request.data serializer = SalesAndPurchaseInPeriodListSerializer(data=request.data) banklist = [BankA, BankB, BankC] cardlist = [CardA, CardB, CardC] # Purchase Bank purchase_bank = 0 for bank in banklist: records_bank = bank.objects.filter(resAccountIn='0', creator_id=request.user.id) for record in records_bank: purchase_bank += record.resAccountOut # Purchase Card purchase_card = 0 for card in cardlist: records_card = card.objects.filter(creator_id=request.user.id) for record in records_card: purchase_card += record.resUsedAmount # Sales Bank sales_bank = 0 for bank in banklist: records_sales_bank = bank.objects.filter(resAccountIn='0', creator_id=request.user.id) for record in records_sales_bank: sales_bank += record.resAccountOut # Sales Card sales_card = 0 for card … -
Android phone no longer wants to connect to Django server
I've been running a Django server for the past few days and have been using my phone to make POST requests and such. However, today my phone doesn't see the server anymore. I have made no changes to my server since last night. I think it's a problem with my phone because I can connect to the server through my other Windows machine, also on the same network. At first, I thought it was the fact that they have different IP addresses but the Windows computer that can connect also has a different IP address and connects fine: Windows computer running Django server: 10.35.24.13 Windows computer able to connect: 10.35.105.108 Android phone unable to connect: 10.35.109.137 If it helps, Chrome on the phone displays: This site can't be reached. http://10.35.24.13:8181/ is unreachable. ERR_ADDRESS_UNREACHABLE I'm completely baffled and have no idea what's wrong. Any suggestions are appreciated. Thanks. -
Django TemplateView get template from a field from DB
I want create a templateview but need to use a editable template on-the-fly, to this i can set a template from a code stored inside a field from a table. # some_app/views.py from django.views.generic import TemplateView class AboutView(TemplateView): template_name = "about.html" -> from table.field Some ideia? -
Django Listview Displays 0 results
I have a weird situation (translation: I'm missing something obvious) where I have a ListView that renders fine when I iterate over each object in my queryset and yield, but returns 0 results when I just return the queryset. class TestListView(ListView): model = Result context_object_name = 'results' template_name = 'cases/test_list2.html' def get_queryset(self): # Get latest results results = Result.objects.filter(canonical=True, environment__config__in=['staging', 'production']).order_by('test__id', '-created_at').distinct('test__id').select_related('test', 'environment') # Return Queryset return results # type <class 'django.db.models.query.QuerySet'>, returns 0 elements from view for result in results: yield result # returns correct number of results, assuming above 'Return Queryset' line is commented out What am I doing incorrectly? -
TypeError: config() got an unexpected keyword argument 'ssl_require'
I am trying to launch a django app using heroku and got the following error TypeError: config() got an unexpected keyword argument 'ssl_require' when running 'heroku run python manage.py migrate' in Django project using Heroku The complete output is Running python manage.py migrate on ⬢ serene-taiga-89672... up, run.6367 (Hobby) Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/friendzone/settings.py", line 212, in <module> django_heroku.settings(locals()) File "/app/.heroku/python/lib/python3.7/site-packages/django_heroku/core.py", line 69, in settings config['DATABASES']['default'] = dj_database_url.config(conn_max_age=MAX_CONN_AGE, ssl_require=True) File settings.py is import os import dj_database_url import django_heroku import dotenv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for … -
Setting pagination_class in Django ListAPIView causes Runtime Error
I have a class-based view for text messages inheriting from the django generic view ListAPIView. As you can probably tell from the inheriting class name, the view is being used as an API with pagination (from the Django Rest framework). I would like to turn off pagination for some specific queries, however even when I try turning off pagination for all queries via this stack overflow question (Turn off automatic pagination of Django Rest Framework ModelViewSet), I get the following error: RuntimeError: Do not evaluate the `.queryset` attribute directly, as the result will be cached and reused between requests. Use `.all()` or call `.get_queryset()` instead. I am overwriting the get_queryset() method in the view without issue, however by just setting the paginator_class variable to None I am receiving this error. Any help would be appreciated. Here's some code: view.py: class TextMessageView(generics.ListAPIView): queryset = TextMessage.objects.all() serializer_class = TextMessageSerializer pagination_class = None def get_queryset(self): """ If a phone number is included in the url query, return only the text messages sent by that number in the queryset, otherwise return all text messages. :return: A Django queryset with a variable number of text messages. """ from_phone_num = self.request.query_params.get('from_phone_number', None) distinct_nums = self.request.query_params.get('distinct_numbers', None) … -
Can I write a function that takes data from two different tables, transforms it and saves to a third table in Django?
I'm making a carpooling service app. I have 2 tables: drivers and passengers. I have an algorithm to match users from the 2 tables. I need a script/function that takes data from the 2 tables, implements the algorithm and saves the output to a third table. What is the best way to do this? (I'm very new to Django) Can I make the script/function be executable from the shell? -
DJANGO+REACT (Failed to load resource)
I follow the tutorials here https://www.youtube.com/watch?v=r0ECufCyyyw&list=PLLRM7ROnmA9FxCtnLoIHAs6hIkJyd1dEx&index=5&t=0s then i have problem like this: image plz help me, thanks a lot -
Django Multiple Users can view single model object
How to define a condition where we can set multiple users access for that single model object. Let's suppose we have the following model. class Project(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.TextField() And i have 2 users: admin and jobert Since user field in above model is single one to one field which means either admin or jobert are saving that object. if that object created by admin then jobert can't see that object and vice-versa for jobert. How do i made that user field to accept or allow multiple users to access that object. i want adminand jobert users to access that model object.