Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django server work with Angular Universal to render the first page
https://angular.io/guide/universal I've read this. The example is for node express. I'm using django server, how to work with angular universal to render the first page. -
Success_url in Django
I'm new to Django(version 2.2.2) and could use some help. I'm creating a very simple webpage which includes a form. I included a success_url property when creating a CreateView for the form in the views.py file. Once a user inputs the details and clicks on submit, it'll redirect them to the homepage. Everything seems to work well except the success_url. It won't redirect to the homepage and instead, causes an error. Does anyone know how to do this? Student model in models.py: from django.db import models class Student(models.Model): name = models.CharField(max_length = 25) age = models.IntegerField() email = models.EmailField() created_date = models.DateTimeField(auto_now = True) def __str__(self): return self.name views.py: from django.shortcuts import render from django.views.generic import CreateView from app.forms import StudentForm class StudentView(CreateView): template_name = 'create_student.html' form_class = StudentForm success_url = '/home/' app.urls file: from django.urls import path from app.views import StudentView urlpatterns = [ path('create_student', StudentView.as_view(), name = 'create_student'), ] project.urls file: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] HTML file: <form method="POST"> {% csrf_token %} {{form.as_p}} <button> Submit </button> </form> -
Django mod wsgi on wamp internal server error
Actually I have successfully Installed the mod_wsgi on windows but when I add some config on httpd.conf file on apache Error occurs. LoadFile "c:/programdata/anaconda3/python37.dll" LoadModule wsgi_module "c:/programdata/anaconda3/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/programdata/anaconda3" and in my httpd.conf file: LoadModule wsgi_module "c:/programdata/anaconda3/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIScriptAlias / "C:/Users/MyUser/Documents/MyFirstDjangoProj/student_management_system/student_management_sys/student_management_sys/wsgi.py" WSGIPythonHome "c:/programdata/anaconda3" WSGIPythonPath "C:/Users/MyUser/Documents/MyFirstDjangoProj/student_management_system/student_management_sys" Require all granted Require all granted Require all granted -
How to receive two or more forms in a function in django
As the title says, i am working with two forms in a template. And i was wondering if there is a way to send two or more forms to save it to the function. Becuase i dont know how can i "detect" the correct form that has to save. This is my two forms: Form 1 from the 'enterprise'instance <form method="POST" action='' enctype="multipart/form-data"> {% csrf_token %} <h4><strong>Datos de empresa:</strong></h4> <!--Foto del miembro de equipo--> <h6><strong>Subir logo:</strong></h6> <input type="file" name="image_path"> <!--Full name--> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <strong>Nombre de empresa:</strong> </div> <div class="col-sm-6 mb-3 mb-sm-0"> <strong>Número de teléfono:</strong> </div> <div class="col-sm-6 mb-3 mb-sm-0"> <input class= "form-control" type="text" name="name" maxlength="20" value="{{enterprise.name}}"> </div> <div class="col-sm-6"> <input class= "form-control" type="tel" pattern="[0-9]{4}-[0-9]{3}-[0-9]{4}" name="phone_number" value="{{enterprise.phone_number}}"> </div> </div> <!--Username and email is same in this case--> <strong>Correo electrónico:</strong> <div class="form-group"> <input class= "form-control" type="email" name="email" value="{{enterprise.email}}" > </div> <!--Date of birth--> <strong>Fecha de fundación:</strong> <div class="form-group"> <input class= "form-control" type="date" name="date" value="{{enterprise.date}}" > </div> <!--Direction--> <strong>Dirección:</strong> <div class="form-group"> <textarea class= "form-control" rows="6" name="direction" value="{{enterprise.direction}}">{{enterprise.direction}}</textarea> </div> <!--Description--> <strong>Descripción de empresa:</strong> <div class="form-group"> <textarea class="form-control" rows="6" type="text" name="description" value="{{enterprise.description}}">{{enterprise.description}}</textarea> </div> <!--Employees--> <strong>Número de empleados (aproximado):</strong> <div class="form-group"> <input class= "form-control" type="number" name="employees" min=1 value="{{enterprise.employees}}"> </div> <!--Button--> <hr> … -
Importing data from google api to my database
I need to create view which import data from google books api and save in my model, I have no Idea how to do this in Django. For now I have this view but I don't know if this is good and what's next def book_search(self, request): value = input() apikey = input() params = {'q': value, 'key': apikey} response = request.get('https://www.googleapis.com/books/v1/volumes', params=params) bookapi = response.json() -
How can I get extra data from a linkedin profile?
I'm using social-auth-app-django to implement the login with social networks, but I'm looking for profile information, such as: photo, email, etc! I already set up my settings but I can't get the information! SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY ='' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = '' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress'] # These fields be requested from linkedin. SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = [ 'email-address', 'picture-url', ] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('firstName', 'first_name'), ('lastName', 'last_name'), ('emailAddress', 'email_address'), ('public-profile-url', 'public_profile_url'), ('pictureUrl', 'picture_url'), ] This is the result: "email_address": null, "public_profile_url": null, "picture_url": null, Thank you! -
Retrofit post cannot successfully send json data to django server
Everyone, I recently developing a server-client system, in server side, I use django and restframework to interact with android applications. In client side, I use android and retrofit to send and get data from server.When I Get data from server, everything is fine, But when I try to post data from android to django, It has some errors. Specifically, It successfully post data to server but doesnot shown in django views. I first use postman to test if I can post data to the URL http://192.168.*.**:8001/api/output and it works, But When I use android application to send post data to http://192.168.*.**:8001/api/output, it can also post successfully Here are my django server code class OutputInfoView(ModelViewSet): serializer_class = OutPutInfoSerializer def get_queryset(self): return models.OutputInfo.objects.all() class OutPutInfoSerializer(serializers.ModelSerializer): class Meta: model = models.OutputInfo fields = ['id', 'user', 'lx', 'ly', 'room', 'activity', 'sound'] # router url routers = routers.DefaultRouter() routers.register(r'output', views.OutputInfoView,basename='OutputInfo') urlpatterns = [ path('', include(routers.urls)) # path('output', views.OutputInfoView.as_view(), name='output'), ] In my android client, I user retrofit to post data: public interface JsonPlaceHolderAPI { @Headers({"Content-Type: application/json"}) @POST("output") Call<List<Sender>> createUser(@Body RequestBody body); } This is the main activity loading HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build(); Retrofit retrofit = new … -
How to populate a model at the end of the user registration
I have the model 'AuthCustomUser(AbstractUser)' for the registration of a new user. In it will be saved the necessary data for the login, for example: name, email and password. On the other hand, I have the model 'MetaUser (models.Model)' that I will use for the additional information of the user, for example: address, telephone, etc. I want to create a relationship between both models at the moment of the end of the registration by the user. In the model 'MetaUser(models.Model)' I have a foreign key: 'user = models.ForeignKey (settings.AUTH_USER_MODEL, on_delete = models.CASCADE)' When the user is registered the data will be entered in the model 'AuthCustomUser (AbstractUser)', then I want to insert the user's 'ID' in the model 'MetaUser (models.Model)' to make the relation of the foreign key between both Models. Finally, the user will start session immediately after finishing his registration, and he will be given access to the home.html. These are my models: class MetaUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) screen_orientation = models.CharField(default='landscape', max_length=9) def __str__(self): return self.name class AuthCustomUser(AbstractUser): def __str__(self): return self.name And you are my view of the registry: class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' def form_valid(self, form): form.save() username = … -
How build filter with ForeignKey related_name field
I need to write view with FilterSet and everything was fine until searchfileds were in one model but when I'm trying to add related to field I'm getting:AttributeError: 'ManyToOneRel' object has no attribute 'get_transform'. How can I add related to field to my filter? My filter: class BookFilter(FilterSet): class Meta: model = Book fields = { 'title': ['icontains', ], 'authors': ['icontains', ], 'published_date': ['iexact', ], 'language': ['iexact', ], 'industry_identifiers': ['icontains', ], } My Models: class Book(models.Model): title = models.CharField(max_length=75, verbose_name='Book title') authors = models.CharField(max_length=150, verbose_name='Authors') published_date = models.IntegerField( validators=[validate_book_published_date, max_year_validator], verbose_name='Publishing date') pages = models.CharField(max_length=4, verbose_name='Number of pages') language = models.CharField(max_length=2, verbose_name='Language') image = models.URLField(verbose_name='Image', default=None, blank=True) class Meta: ordering = ('title',) def __str__(self): return f'{self.title} written by {self.authors}' class IndustryIdentifiers(models.Model): type = models.CharField(max_length=25, verbose_name='Type') identifier = models.CharField(max_length=25, verbose_name='Identifier') book = models.ForeignKey(Book, on_delete=models.CASCADE, verbose_name='Book', related_name='industry_identifiers') def __str__(self): return f'{self.type}: {self.identifier}' -
How to retrieve input data from one form to another form in Django?
I am trying to create an app which create an user with unique id using forms and add that user to a data table . I need to retrieve the field input data from previous form to new form with some new fields related to that user and give another unique id to that user with other data table I am beginner in Django , I have done couple of online bootcamps . I have search my problem online on many platforms but didn't got expected result . maybe I am not getting right term to represent my problem. -
Facing problems redirecting user using django post_save signal
When ever a user creates a new chat thread, i want to automatically redirect them to the thread. But facing problems example my models class Thread(models.Model): name=models.CharField() creator=models.ForeignKey(User) class Chat(models.Model): thread=models.ForeignKey(Thread) message=models.TextField() User creates a thread , and has to be redirected to the created thread('app:chat',pk) displaying the Chatform and thread name. I tried using django post_save signal to redirect the user after creating a thread def redirect_user(sender,instance,**kwargs) pk=instance.id url=('app:chat',pk) post_save.connect(redirect_user,sender=Thread) Well this is not working. Please help with a good approach to solve this problem. -
What is the default hashing algorithm used by Django cache
I am using caching in Django. My cache is a django-redis cache: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } I am using view based cache: @cache_page(timeout=60 * 10) def my_view(request: Request): # my view stuff What I would like to know is what is the algorithm used by Django to create the key? The docs just say that it's made from the URL and headers. But I would like to know the specifics or better yet the code that generates it. But the docs lack this information. So, how does Django derive keys for view based caches? -
How to check if data already exists in the table using django
I am new with django framework struggling to compare value from the database. this are my tables in models.py : class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) title = models.CharField(max_length=200) content = models.TextField() creationDate = models.DateTimeField(auto_now_add=True) lastEditDate = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Votes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) post_id = models.ForeignKey(Post, on_delete=models.CASCADE,) up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) class Meta: unique_together = (("user","post_id"),) I have data in the vote tabe like this: Now what I want is to check in the above table if 'user_id' and 'post_id' already exists in the Votes tabel's rows if the exist throw a message if not add value on upvote or downvote, i gues everyone understand what i want if not please let me know. something which i tried was this code: def chk_table(): user_id = request.user post_id = id votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists() return votes_table but this function is checking in hole table not just in just in one row... -
Django and mongodb
Any good tutorial for python django mongodb? I have python 3.7.3 installed. I grabbed django 1.6 from https://github.com/django-nonrel/django (that's really old). Followed the instruction of https://django-mongodb-engine.readthedocs.io/en/latest/topics/setup.html The "python manager.py runserver" show some htmlparser errors. File "D:\apps\Python37\lib\site-packages\django\utils\html.py", line 14, in from .html_parser import HTMLParser, HTMLParseError File "D:\apps\Python37\lib\site-packages\django\utils\html_parser.py", line 12, in HTMLParseError = _html_parser.HTMLParseError AttributeError: module 'html.parser' has no attribute 'HTMLParseError' Any recommendations to have them work together? -
Data migration causes error AttributeError: type object 'User' has no attribute 'normalize_username'?
I'm trying to create a data migration to add a user to the database. However, I get an attribute error when I try to do so. I've ran ipdb to troubleshoot the problem, I've tried commenting out fields of the user object to see if one of those was causing the error, and I've tried adding "user.save()" # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2019-02-08 21:23 from __future__ import unicode_literals from django.db import migrations from django.conf import settings def create_urechr_user(apps, schema_editor): staffPosition = apps.get_model("hr", "staffPosition") User = apps.get_model(settings.AUTH_USER_MODEL) user = User.objects.create_user( username = "myName", password = "test", is_active = True, email = "", ) staff = staffPosition.objects.get(pk = 95) user.save() urec_staff = staffPosition.objects.create( parent_staff_position = staff, user_id = user, title = "URec Human Resources", ) urec_staff.save() class Migration(migrations.Migration): dependencies = [ ('hr', '0003_add_verbose_name_20190213_1519'), ] operations = [ migrations.RunPython(create_urechr_user), ] AttributeError: type object 'User' has no attribute 'normalize_username' -
Assign a widget to ModelForm field after initialization
I have a ModelForm which looks more or less like this one: class SomeModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(SomeModelForm, self).__init__(*args, **kwargs) <some fields/code> # the problematic line below self.fields['date'].widget = forms.DateInput(attrs={ 'type': 'date', 'class': 'form-control input-lg', }), class Meta: model = models.SomeModel fields = [<some fields>, 'date',] And the problem is I'm getting an error: Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'is_hidden' It looks that I cannot assign forms.DateInput() widget to already existing field (as you can see I have to execute super().__init__() because of popping a field from **kwargs). Is there any solution to do this without exceptions? -
How do I make sure entered integer is greater than current value before updating model field?
I am using a form that saves to one model to update the most current mileage which is stored in another model. I want to make sure the mileage entered is > or = the current mileage. I havent been able to figure out the right validation or where to write the validation. I have tried an if statement in the form_valid() of the CreateView and a save() method in the model. class Vehicle(models.Model): name = models.CharField(blank=True, max_length=100) make = models.CharField(blank=True, max_length=100) model = models.CharField(blank=True, max_length=100) year = models.IntegerField(blank=True, null=True) vin = models.CharField(blank=True, max_length=17) gvw = models.IntegerField(blank=True, null=True) license_plate = models.CharField(blank=True, max_length=100) purchase_date = models.DateField() current_mileage = models.IntegerField(blank=True, null=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('vehicles:vehicle_detail', kwargs={'pk':self.pk}) @property def get_current_mileage(self): return self.current_mileage class FuelEntry(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) fuel_choices = ( ('EMPTY', 'Empty'), ('1/8', '1/8'), ('1/4', '1/4'), ('1/2', '1/2'), ('3/4', '3/4'), ('FULL', 'Full'), ) current = models.CharField(max_length=5, choices=fuel_choices) after = models.CharField(max_length=5, choices=fuel_choices, blank=True) gallons = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0') cost = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0') mileage = models.IntegerField(blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-date', 'vehicle'] def __str__(self): return self.vehicle.name def get_absolute_url(self): return reverse('fuellog:entry_detail', kwargs={'pk':self.pk}) class CreateEntry(CreateView): model = … -
Continuously check if file exists with AJAX in Django
I've developed an application in Django where a user goes to a form on a site and enters in an Elasticsearch query, then generating a report for the user to download. It all works fine and dandy, but lately in testing some more queries we've noticed that some return a lot of results which leads to a timeout request. What we've figured out that we'd like to do is have Django continuously check if a file exists (because it won't be written to the local system until it's completed) to prevent that timeout issue. Additionally, once the file is done being created we want to add a download button so that the user knows it is done. Following this tutorial, I added a function to my views.py and associated it with a url which is then called by a javascript code block in my html form. Because I am brand new to using AJAX, JQuery, Javascript, and Django I'm not quite sure how to get it to work. Mainly, I'm trying to figure out how to get it to keep checking if the file is done being created yet. If this were just using basic Python I would do a … -
Django, on registering a user: AttributeError: 'AnonymousUser' object has no attribute '_meta'
I added the field 'description' (as a test) to the registration form, and am also attempting to create two different profiles for two different users (WPs and Ws). I have created, as you will see below, a seperate registration page for wps (user type2), referenced by profile_wp, register_WP etc, and on trying to register a user using this form, I receive the following error: AttributeError: 'AnonymousUser' object has no attribute '_meta' There are various answers on this, but none solved my problem. The various relevant bits of my code are below forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): #form that inherits from the usercreationform email = forms.EmailField() class Meta: model = User class Register_WP_Form(UserCreationForm): #form that inherits from the usercreationform email = forms.EmailField() description=forms.EmailField() #choice = forms.ChoiceField(required=True, widget=forms.RadioSelect( #attrs={'class': 'Radio'}), choices=(('option1','I am a W'),('option2','I am a WP'),)) class Meta: model = User #when this form validates it creates a new user #type the fields to be shown on your form, in that order. fields = ['username','email','password1','password2','description'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model= Profile fields=['image'] views.py #USERS … -
After connecting to remote database, migrating gives error: Errno61, Connection Refused
I recently started using sql and connected to an remote sql server. I can run queries on it in python shell and get correct results. However, when I manage.py runserver It tells me that there I need to migrate, however when I migrate I get an error saying: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '*host*' ([Errno 61] Connection refused)") What should I do to fix this error. setting.py database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*name*', 'USER': '*user*', 'PASSWORD': '********', 'HOST': '*host*', 'PORT': '****', 'OPTIONS': { 'sql_mode': 'traditional', } } } full error list here: File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/connections.py", line 583, in connect **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 727, in create_connection raise err File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 716, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect raise exc pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'masspike.ctqk1lhawxna.us-west-2.rds.amazonaws.com' ([Errno 61] Connection … -
Django queryset to a string
I have a queryset by doing: chart_data = DetailChange.objects.extra(select={'day': 'date(captured_date)'})\ .values('item_id__store_id__store_name', 'day')\ .annotate(total_sale=Sum('amount_sold')) then I have a queryset like this: {'day': datetime.date(2019, 6, 24), 'item_id__store_id__store_name': 'Keyboard Pro', 'total_sale': 706.0} {'day': datetime.date(2019, 6, 25), 'item_id__store_id__store_name': 'Keyboard Pro', 'total_sale': 18.0} ... now what I want to do is get one single string that combines all the days in it, separated by ",". Like: "2019-6-24, 2019-6-25, 2019-6-26, ..." Is there an easy way to get it done? -
Why won't import models work in a utility file in the same directory?
From views.py I'm calling a function that's in another file in the same directory (utils.py). utils.py errors because it can't import models from models.py which is in the same directory. I get the following error: File "/home/myuser/site/core/utils.py", line 1, in 2019-06-26 15:22:46,645: from .models import( 2019-06-26 15:22:46,645: *************************************************** 2019-06-26 15:22:46,646: If you're seeing an import error and don't know why, 2019-06-26 15:22:46,646: we have a dedicated help page to help you debug: 2019-06-26 15:22:46,646: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2019-06-26 15:22:46,646: *************************************************** 2019-06-26 15:22:51,962: Error running WSGI application 2019-06-26 15:22:51,963: ImportError: cannot import name 'Movie' utils.py from .models import( Movie, Album, Book) def get_weekly_tops(): start_date, end_date = getThisWeekStartEnd() book = Book.objects.filter(release_date__range=[start_date, end_date]).filter(active=True).order_by('-amazon_rating')[:1] theater = Movie.objects.filter(release_date__range=[start_date, end_date]).filter(active=True).filter(bluray_date__isnull=True).order_by('-imdb_rating')[:1] bluray = Movie.objects.filter(bluray_date__range=[start_date, end_date]).filter(active=True).filter(bluray_date__isnull=False).order_by('-imdb_rating')[:1] album = Album.objects.filter(release_date__range=[start_date, end_date]).filter(active=True).order_by('-base_rating')[:1] if len(book) == 0: book = Book.objects.filter(release_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).order_by('-amazon_rating')[:1] if len(theater) == 0: theater = Movie.objects.filter(release_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).filter(bluray_date__isnull=True).order_by('-imdb_rating')[:1] if len(bluray) == 0: bluray = Movie.objects.filter(bluray_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).filter(bluray_date__isnull=False).order_by('-imdb_rating')[:1] if len(album) == 0: album = Album.objects.filter(release_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).order_by('-base_rating')[:1] return {'book':book, 'theater':theater, 'bluray':bluray, 'album':album} views.py from .utils import( get_weekly_tops) def index(request): weekly_tops = get_weekly_tops() return render( request, 'index.html', context={ 'weekly_tops':weekly_tops }, ) -
django-imagekit generates thumbnail images when getting a request to access a page and it makes the page load really slow
I'm using django-imagekit to thumbnail images, I use image_thumbnail field to access thumbnails, but the problem is that ImageSpecField makes my website to work really slowly as it creates thumbnails when the page is requested. I thought it would be much faster if I make thumbnails when initially uploading original images in Django admin. Is it possible to keep images with various sizes when uploading an original image in Django admin? models.py class Image(TimeStampedModel): image = ProcessedImageField(upload_to=image_path, format='JPEG', processors=[Thumbnail(1500)]) image_thumbnail = ImageSpecField(source='image', processors=[Thumbnail(280)], format='JPEG', options={'quality': 60}) -
How to Select specific Row from the Tabel Using Django Query
I am new with django framework i have no idea about how query works in django, this are my tables in models.py : class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) title = models.CharField(max_length=200) content = models.TextField() creationDate = models.DateTimeField(auto_now_add=True) lastEditDate = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Votes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) post_id = models.ForeignKey(Post, on_delete=models.CASCADE,) up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) class Meta: unique_together = (("user","post_id"),) I have data in the vote tabe like this: Now what I want is to check in the above table if 'user_id' and 'post_id' already exists in the Votes tabel's rows if the exist throw a message if not add value on upvote or downvote, i gues everyone understand what i want if not please let me know. something which i tried was this code: def chk_table(): user_id = request.user post_id = id votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists() return votes_table but this function is checking in hole table not just in just in one row... -
Django inline formset want to auto-save user and datetime
I am having 2 models: Study Request Concept and Comments. Study request Concept can have multiple comments. *models.py: class StudyRequestConcept(models.Model): CHOICES = ( ('Yes', 'Yes'), ('No', 'No'), ) REQUEST_STATUS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) APPROVER_CHOICES = ( ('Amey Kelekar', 'Amey Kelekar'), ) requestor_name = models.CharField(max_length=240, blank=False, null=False) project = models.CharField(max_length=240, blank=False, null=False) date_of_request = models.DateField(blank=False, null=False) brief_summary = models.CharField(max_length=4000, blank=False, null=False) scientific_question = models.CharField(max_length=2000, blank=False, null=False) strategic_fit = models.CharField(max_length=2000, blank=False, null=False) collaborators = models.CharField(max_length=1000, blank=False, null=False) risk_assessment = models.CharField(max_length=2000, blank=False, null=False) devices = models.CharField(max_length=1000, blank=False, null=False) statistics = models.CharField(max_length=2000, blank=False, null=False) personnel = models.CharField(max_length=1000, blank=False, null=False) sample_size = models.PositiveIntegerField(blank=False, null=False, default=0) population = models.CharField(max_length=2000, blank=False, null=False) dmti_study_start_date = models.DateField(blank=False, null=False) duration = models.PositiveIntegerField(blank=False, null=False, default=0) decision_date = models.DateField(blank=False, null=False) deliverables = models.CharField(max_length=4000, blank=False, null=False) logistics_flag = models.CharField(max_length=3, choices=CHOICES, default='No') status = models.CharField(max_length=20, choices=REQUEST_STATUS, default='Pending') approver_date = models.DateField(blank=True, null=True) approver_name = models.CharField(max_length=240, choices=APPROVER_CHOICES, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) def get_absolute_url(self): return reverse('update_StudyRequestConcept', kwargs={'pk': self.pk}) def get_commentsStudyRequestConcept(self): return ','.join([str(i) for i in self.commentsStudyRequestConcept.all().values_list('id', flat=True)]) class CommentsStudyRequestConcept(models.Model): comments = models.CharField('Comment', max_length=2000, blank=True, null=True) commented_on = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) studyRequestConcept = models.ForeignKey(StudyRequestConcept, related_name='commentsStudyRequestConcept', on_delete=models.CASCADE) def __str__(self): return str(self.id) Now when the user enters …