Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to get access key and access token variable over to function in celery
I have a function working in celery that I want to work with the Twitter API however when trying to access I have to use request to get the oauth keys from the user. This won't work in celery tasks so I need some other way of getting the variables and using them. celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings from django.shortcuts import render import time import tweepy os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoTweetLiker.settings') app = Celery('AutoTweetLiker') app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL='redis://:pf133827b9d431528f1158e82e1b04a8bda7b3555544882d8f0e3b963bd0f85a1@ec2-18-207-19-49.compute-1.amazonaws.com:13609', CELERY_RESULT_BACKEND='redis://:pf133827b9d431528f1158e82e1b04a8bda7b3555544882d8f0e3b963bd0f85a1@ec2-18-207-19-49.compute-1.amazonaws.com:13609') app.autodiscover_tasks() @app.task(bind=True) def liker(self): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth, wait_on_rate_limit=True) * does function with twitter api * and the views.py with the function and auth def like(request): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) access_key = request.session['access_key_tw'] access_secret = request.session['access_secret_tw'] oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth) user = api.me() username = request.user.get_username() muting.delay() return render(request, "home.html") def auth(request): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth_url = oauth.get_authorization_url(True) response = HttpResponseRedirect(auth_url) request.session['request_token'] = oauth.request_token return response def callback(request): verifier = request.GET.get('oauth_verifier') oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) token = request.session.get('request_token') request.session.delete('request_token') oauth.request_token = token try: oauth.get_access_token(verifier) except tweepy.TweepError: print('Error, failed to get access token') request.session['access_key_tw'] = oauth.access_token request.session['access_secret_tw'] = oauth.access_token_secret print(request.session['access_key_tw']) print(request.session['access_secret_tw']) api = get_api(request) response = HttpResponseRedirect(reverse('mute')) return response The … -
Form POST using Ajax doesn't populate database in Django, but gives success message
VIEW: class AddFoo(BSModalCreateView): template_name = 'qualitylabs/add_foo.html' form_class = AddFooForm success_message = 'Success: Foo was created' success_url = reverse_lazy('Home') FORM: class AddFooForm(BSModalModelForm): class Meta: model = Foo fields = '__all__' widgets = { 'part_number': PartNumberWidget, 'operation': OperationNumberWidget, } JAVASCRIPT: function sendToServer(machine, before, after) { var modified_form_data = before + "&inspection_machine=" + encodeURIComponent(machine) + after $.ajax({ type: $('#AddFooForm').attr('method'), url: $('#AddFooForm').attr('action'), data: modified_form_data, success: function (data) { console.log('did it!!!!!') } }); } I'm trying to post a form to the server, which should populate the database. I have to send it in Ajax because I have to iterate multiple times, changing variables each time (poorly set up database). The weirdest thing is that when I run the code, I get: "POST /add_foo/ HTTP/1.1" 302 0 which is the same result that you get when the server responds properly. The page does not redirect to the success_url, and when I check the data in the admin page, the items have not been added. However, in the admin page I do get the success message of "Sucess: Foo was created" Any ideas? It's quite strange. -
How to set a date from date picker and fetch it from the REST API?
on the backend. I set a filter for my data. Where I can filter the dates from the REST API url. class RainfallFilter(filters.FilterSet): start_date = DateFilter(field_name='timestamp', lookup_expr='gt') end_date = DateFilter(field_name='timestamp', lookup_expr='lt') date_range = DateRangeFilter(field_name='timestamp') class Meta: model = Rainfall fields = [] class RainfallView(generics.ListCreateAPIView): serializer_class = RainfallSerializer queryset = Rainfall.objects.all() filterset_class = RainfallFilter def get(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = RainfallSerializer(queryset, many=True) return Response(serializer.data) What I want to happen is from my chart.js, I want to display to my chart what I selected start and end dates. or date_range. That I have a date picker on my frontend UI that If I select, dates start_date=2020-01-20 to end_date=2020-01-25. it will only show data from 20-25. How am I gonna do it? var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in qs %}'{{i.timestamp}}',{% endfor %}], datasets: [{ label: 'Rainfall Graph', data: [{% for i in qs %}'{{i.amount}}',{% endfor %}], lineTension: 0, backgroundColor: 'transparent', borderColor: '#c9c5c5', borderWidth: 2, pointRadius: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: false } }] }, legend: { display: false } } }) }()); -
how to change the background color of the particular row in python Django
the below code is table.py class StColumn(tables.Column): def render(self, value, record): if record.status == 'warning': self.attrs ={"td": {"bgcolor": "DeepSkyBlue"}} elif record.status == 'ok': self.attrs ={"td": {"bgcolor": "SandyBrown"}} return u"%s" % (record.status.id) class resultTable(BaseTable): class Meta(BaseTable.Meta): model = resultModel attrs = {'class': 'table table-striped table-bordered table-hover row-color=green' , 'width': '70%'} status= StColumn(accessor='status.id') print(status) fields = ( "field1", "field2", "field3", "status", "field5", ) **how we can change the color of row when the status==warning and status ==ok ** -
Images not appearing in virtual environment
I'm currently working on an application on my virtual environment (Pycharm) and I've dropped three different png. images into my "img" folder which sits in a projects folder static>projects>img. Through the script path in my venv all folders are recognized telling me the path way is functioning, I can't seem to figure why the images aren't showing up. Thank you for your time and assistance. -
|as_crispy_field got passed an invalid or inexistent field in CharField
I am building a BlogApp and while trying to styling the forms i got this error. :- |as_crispy_field got passed an invalid or inexistent field edit.html {% load crispy_forms_tags %} {% block content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ allowance_form|as_crispy_field }} </table> <button type="submit">Save Changes</button> </form> </div> {% endblock content %} views.py def edit_allowance(request,user_id): if request.method == 'POST': allowance_form = ProfilePhotoAllowForm(request.POST, request.FILES, instance=request.user.profile) if allowance_form.is_valid(): custom_form = allowance_form.save(False) custom_form.save() return redirect('profiles',user_id=user_id) else: allowance_form = ProfilePhotoAllowForm(instance=request.user.profile) context = {'allowance_form':allowance_form} return render(request, 'edit.html', context) Whenever i run the page it keep showing me this |as_crispy_field got passed an invalid or inexistent field Error. I don't know what's wrong in this Code. I checked all answered on StackOverFlow BUT they didn't help me in this. Any help would be appreciated. Thank You in Advance. -
DRF Serializer behaves differently when using as nested serializer
I have a model serializer for a date field and a time field. The model and serializer look like this: class OrderDate(TimeStampedModel): order = models.ForeignKey(Order, related_name='dates', on_delete=models.CASCADE, null=True, blank=True) date = models.DateField() from_hour = models.TimeField() to_hour = models.TimeField() class OrderDateSerializer(serializers.ModelSerializer): class Meta: model = OrderDate fields = ['id', 'date', 'from_hour', 'to_hour'] Now I use this serializer as a nested serializer in my order model and I added a validator like this: class BaseOrderSerializer(serializers.ModelSerializer): dates = OrderDateSerializer(many=True) @staticmethod def validate_dates(value): return OrderService.validate_dates(value) The value object inside the validated_dates method is an ordereddict which has datetime objects as value. Example value like this: [OrderedDict([('date', datetime.date(2020, 12, 16)), ('from_hour', datetime.time(11, 0)), ('to_hour', datetime.time(15, 0))])] Now I want to use the OrderService.validate_dates method a second time outside the serializer like this: date_serializer = OrderDateSerializer(data=request.data, many=True) date_serializer.is_valid(raise_exception=True) OrderService.validate_dates(date_serializer.data) The problem here is, that the serialized data now is an ordered dict with string values instead of datetime objects. [OrderedDict([('id', None), ('date', '2020-12-16'), ('from_hour', '11:00:00'), ('to_hour', '15:00:00')])] That results in an type error inside my method. Is there any way to change this and have the same value types in the ordered dicts? -
Where to best execute database operations using Django framework?
Thanks in advance for any help. I am new to django specifically as well as web development in general. I have been trying to teach myself and develop a website using the Django framework and while everything is working so far, I am not sure if I am really doing things in the best possible way. Typically, within my django app, I will have certain points where I want to modify the contents of my database model in some way. A typical use case is where I have button on my site that says "Add an article": models.py: from django.db import models # data model import from django.contrib.auth.models import User # Create your models here. class Post(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) post = models.CharField(max_length=1024) urls.py: from django.urls import include, path from . import views urlpatterns = [ path('', views.post, name='new_post'), path('post_exec', views.post_exec, name='post_exec'), ] views.py: from django.contrib import messages from django.shortcuts import render, redirect # import data models from django.contrib.auth.models import User from .models import Post def post(request): # make sure the user has privileges user = User.objects.get(id = request.user.id) if not user.is_superuser: return redirect('home') return render(request, 'post.html') def post_exec(request): # make sure the user has priveledges user = User.objects.get(id … -
404 on http://@ but not https://
I'm very new to everything web development. I've developed a site with Django and deployed it on digital ocean. Here's the problem: I can ping both my @ and www. domains (they both correctly point to the IP address), and I have a certbot certificate that lists both. When trying to load the website on www.example.com, it correctly redirects to https://wwww.example.com - beautiful. However, when I try to load it from example.com, I get a "404 Not Found // nginx/1.18.0 (Ubuntu)"-error. What's weird is that if I manually try and load https://example.com, then it loads correctly (that is, on https://example.com, proving that the certbot certificate is indeed catching both). It thus seems that I ought to try and redirect example.com requests to www.example.com, since everything will then go through smoothly. By the way, the ALLOWED HOSTS is ".example.com". From what I can gauge, this involves manipulating the /etc/nginx/conf.d/example.com file, and making a server block complete the redirect, but I'm lost as to how. I don't much care if example.com redirects to https://example.com, or to https://www.example.com (I'm just learning, SEO is of no consequence to me), I just need my website to load correctly. So sorry if this has already been … -
How can I logout user in Django when he closes my page tab?
I have this code: SESSION_EXPIRE_AT_BROWSER_CLOSE = True which logout user on browser close, but is there anything similar to this code for logout user on window tab close? -
How can i make a query that groups first column and attach any of the rows of second column within each group
I new in sql and I have a postgresql database which has: Table name1 name2 name3 group1 subgroup_A element1 group1 subgroup_B element2 group1 subgroup_C element3 group2 subgroup_D element4 group2 subgroup_E element5 group2 subgroup_F element6 group2 subgroup_G element7 group3 subgroup_H element8 group3 subgroup_I element9 I need to get just 3 rows from db | name1 | name3 :-------|------------ |group1 | element1 (or element2, element3. it doesnt matter) |group2 | element4 (or element5 .. element7. it doesnt matter) |group3 | element8 (or element9. it doesn`t matter) database has more than 300000 rows. I tried to use: select distinct name1 from Table I got | name1 | :-------|------------ |group1 |group2 |group3 but how to add any of the name3 inside each group What is the best way to do this in SQL and in 'django orm'? -
django admin connect two model in creation
I have three models class Voting(Model): id = ... class Candidate(Model): voting = ForeignKey(Voting, on_delete=DO_NOTHING) class Commands(Model): voting = ForeignKey(Voting, on_delete=CASCADE, verbose_name="Votación") candidate = ForeignKey(Candidate, on_delete=CASCADE) And I did this en model admin class CommandInline(admin.TabularInline): model = Commands extra = 1 @admin.register(VotingCandidate) class VotingCandidateAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['voting', "name"]}), ('Mensajes', {'fields': ['default_messages', 'votge_ok_mesage', 'vote_error_mesage', ], 'classes': ['collapse']}), ] inlines = [CommandInline] But when I press Save I get this error: Exception Type: RelatedObjectDoesNotExist Exception Value: Commands has no voting. How I can put in command.voting_id the value of andidate.voting_id in order to can save one Candidate and the cmmands? -
How to add likes to my blog posts using generic relationships in Django
I'm trying to add a like/dislike functionality in Django using generic relationships. Can someone help me? My post model class Post(models.Model): title = models.CharField(max_length=225) post_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) class Meta: ordering = ['-post_date',] def get_absolute_url(self): return reverse('post-detail', args=(str(self.id)),) Thanks in advance! -
Django Channels long running consumer authentication issues
When using django channels, I have a long-running websocket connection. My users may become logged out due to their session expiring while this connection is still active. This causes sporadic behavior where HTTP requests don't work, because they're not authenticated, but the websocket is still sending and receiving data like nothing is wrong. The Django Channels docs say: If you are using a long running consumer, websocket or long-polling HTTP it is possible that the user will be logged out of their session elsewhere while your consumer is running. You can periodically use get_user(scope) to be sure that the user is still logged in. However, this doesn't work. When I call the following code I'm able to see that Django Channels believes the user is still authed. user = async_to_sync(get_user)(self.scope) print(user.is_authenticated) What is the correct way to check if a user is still authenticated in a Django Channels websocket consumer? This GitHub issue touches on the issue but doesn't have a good solution Websocket consumer as follows: class GUIConsumer(WebsocketConsumer): def connect(self): async_to_sync(self.channel_layer.group_add)( GROUP_NAME, self.channel_name) user = self.scope.get('user') if user and user.has_perm('auth.can_access_ui'): self.accept() else: self.accept() self.close() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( GROUP_NAME, self.channel_name) def data(self, event): publisher_type = event.get('publisher') data = event.get('data') … -
Django admin list display with dynamic callable
I have a django project which create lots of reports, and each user has different permissions to view different report. And now I have a admin page which summarize all the user permissions for all reports, and I did it by sth similar to this: class userAdmin(admin.ModelAdmin): def report1_perm(self, user): return user.has_perm('report1') def report2_perm(self, user): return user.has_perm('report2') list_display=['report1_perm', 'report2_perm'] Now instead of having to def a diff method for each report, I want to make callables from the list of reports I have, but I am having trouble to figure out what to pass to the list_display, I have played with setattr or name but they do not seem to work. -
How To Filter By Last 3 Months In Django
What is the best way to filter a DateField by the last 3 months in django. #post_list = Post.objects.filter(release_date=three_months_ago) Here is some relevant info: models.py: class Post(models.Model): release_date = models.DateField(null=True, blank=True, default=None) -
Problem validating modelformset_factory in Django
I have a problem trying to validate a modelform and, after various tests, I think the problem is with the html template in how the information is displayed. I have 2 models: models.py: class bdAccesorios(models.Model): fdClienteAcc=models.CharField(max_length=35) fdProveedorAcc=models.CharField(max_length=60) fdSkuAcc=models.CharField(max_length=30) fdNombreAcc=models.CharField(max_length=60) fdCostoAcc=models.DecimalField(max_digits=8, decimal_places=2) fdUnidadAcc=models.CharField(max_length=30) fdExistenciaAcc=models.IntegerField() fdAuxAcc=models.CharField(max_length=60, default="0") class bdComponentes(models.Model): fdGrupoComp=models.CharField(max_length=30) fdNombreComp=models.CharField(max_length=60) fdSkuComp=models.CharField(max_length=30) fdExistenciaComp=models.DecimalField(max_digits=8, decimal_places=2) fdDesgloseComp=models.ManyToManyField(bdAccesorios, through="bdComponentesDesglose") fdPertenenciaComp=models.ForeignKey(bdUsuariosAux , on_delete=models.CASCADE) fdAuxComp=models.CharField(max_length=60, default="0") and establish a many to many relationship through a third model to class bdComponentesDesglose(models.Model): fdAccesorioCompDes=models.ForeignKey(bdAccesorios, on_delete=models.CASCADE) fdComponenteCompDes=models.ForeignKey(bdComponentes, on_delete=models.CASCADE) fdCantidadCompDes=models.IntegerField(default=1) fdPrecioTotalAcc=models.DecimalField(max_digits=8, decimal_places=2, blank="true", editable="false") To update bdComponentes I combine two forms forms.py: class fmComponente(ModelForm): class Meta: model=bdComponentes fields='__all__' exclude = ('fdAuxComp', 'fdDesgloseComp') labels = { 'fdGrupoComp': 'Grupo', 'fdSkuComp': 'SKU', 'fdNombreComp': 'Nombre', 'fdPertenenciaComp': 'Cliente', 'fdExistenciaComp': 'Existencia', } class fmComponenteDes(ModelForm): class Meta: model=bdComponentesDesglose fields='__all__' exclude = ('fdComponenteCompDes','fdPrecioTotalAcc',) labels = { 'fdAccesorioCompDes': 'Accesorio', 'fdCantidadCompDes': 'Cantidad', } Then I make a view to update the model views.py: def vwComponenteModificar(request,IDComp): vrModificarComp = bdComponentes.objects.get(id=IDComp) vrModificarCompDes = bdComponentesDesglose.objects.filter(fdComponenteCompDes__fdNombreComp=vrModificarComp.fdNombreComp) vrComponenteForm=fmComponente(instance=vrModificarComp) vrComponenteDesModelForm = modelformset_factory(bdComponentesDesglose, extra=0, exclude = ('fdComponenteCompDes','fdPrecioTotalAcc',)) vrComponenteDesForm=vrComponenteDesModelForm(queryset=vrModificarCompDes) if request.method == "POST": vrComponenteForm = fmComponente(request.POST, instance=vrModificarComp) vrComponenteDesForm=vrComponenteDesModelForm(request.POST) if vrComponenteForm.is_valid() and vrComponenteDesForm.is_valid(): ###Here is the problem vrComponenteForm.save() for lpCompDes in vrComponenteDesForm: lpCompDes.save() return redirect('/') return render(request,"DataParagonMain/ComponentesCrear.html",{ 'dtCrearComp': vrComponenteForm, 'dtCrearCompDes': vrComponenteDesForm }) My problem is in my template the view, previously mention, … -
Django homepage on port 8000 not answer
i uploaded a docker-compose with Django and Mysql, and everythings looks okay. docker container ls show both containers running, but Django homepage on port 8000 not answer. I got another one docker-compose with postgres and that works well. What can possibly going on? docker-compose file: version: "3.8" services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - '8000:8000' depends_on: - db db: image: mysql:5.7 ports: - '3306:3306' environment: MYSQL_DATABASE: 'djangomysql' MYSQL_USER: 'wendel' MYSQL_PASSWORD: 'wendel12' MYSQL_ROOT_PASSWORD: 'wendel12' -
Crazy number of fields
I want to record 144+ separate pieces of data for every record in my Django database. I think I know that I will need to create a field for each data point but it doesn’t seem very efficient. Is there a more effective way of doing this. It is a scoring system so I need to be able to enter values 1 to 10 as well as x, which counts as 10 and m, which counts as 0. The scores are recorded in groups of 3 or 6 values Any thoughts -
Endless select when two child models of one abstract model in annotation fields
There are two models, which inherit from one abstract model class ProductToStock(models.Model): product = None stock = None qty = models.PositiveSmallIntegerField(db_index=True) price = models.DecimalField(decimal_places=2, max_digits=8, db_index=True) class TireToStock(ProductToStock): product = models.ForeignKey('Tire', related_name='offers', on_delete=models.CASCADE) stock = models.ForeignKey('providers.Stock', related_name='available_tires', on_delete=models.CASCADE) class WheelToStock(ProductToStock): product = models.ForeignKey('Wheel', related_name='offers', on_delete=models.CASCADE) stock = models.ForeignKey('providers.Stock', related_name='available_wheels', on_delete=models.CASCADE) And there is a stock model: class Stock(models.Model): name = models.CharField(max_length=200) I want to select all stocks and get count of tires and wheels on each of them. If I get only one of my counts it's work fine: Stock.objects.annotate( tires_count=Count('available_tires') ) But if I get both counts, I get endless recursive select: Stock.objects.annotate( tires_count=Count('available_tires'), wheels_count=Count('available_wheels'), ) How can I select both counts in one query? -
Django cant return a class based view user id
My goal is to update the view using ajax. when the user enters a value in those 3 fields and save those fields to the database with for this user. I have a user model with 3 text field as follow class Q3Sign(models.Model): title = models.CharField(max_length =255,blank =True) title2 = models.CharField(max_length =255, blank = True) title3 = models.CharField(max_length =255,blank =True) user = models.ForeignKey(User, on_delete=models.CASCADE ) class Meta: db_table = "Q3sign" and my view is as fellow, I am getting the following error when I try to populate the fields. django.db.utils.IntegrityError: NOT NULL constraint failed: Q3sign.user_id class Createcourse(generic.CreateView): model = Q3Sign fields = ['title','title2','title3'] template_name = 'Q3canA/create_course.html' success_url = reverse_lazy('create_course') def create_course(self, request): members = Q3Sign.objects.all() return render (request,'Q3canA/create_course.html' , {'members':members}) def insert(request): member = Q3Sign(title=request.POST['title'], title2=request.POST['title2'], title3=request.POST['title3'], user=request.POST['user.id']) member.save() return redirect('create_course') and here is my html <div class="container"> <h2>Courses</h2> <form method=post> {% csrf_token %} {{ form.as_p}} <input type="submit" value="Create course" /> </form> </div> <form method="post"> {% csrf_token %} <div class="form-inline"> <label>Course 1</label> <input type="text" id="title" name="title" class="form-control"/> </div> <br /> <div class="form-inline"> <label>Course 2</label> <input type="text" id="title2" name="title2" class="form-control"/> <label>Course 3</label> <input type="text" id="title3" name="title3" class="form-control"/> </div> <br /> <div class="col-md-4"></div> <div class="col-md-4 form-group"> <button type="button" class="btn btn-primary form-control" id="submit">Submit</button> … -
Django: AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'
The following error is given to me when i access my localhost:8000/update_item/: "AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'" views.py def updateItem(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order = order, product = product) carrito.js: function updateUserOrder(productId, action){ console.log('Usuario logeado y enviando data...') var url = '/update_item/' fetch (url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId' :productId, 'action' :action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) location.reload() }) } The error is in the following line: data = json.loads(request.data) if i change that line to the following: data = json.loads(request.body) It gives me another error: "JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0)" -
Django crash when upload a big file
I'm trying to send a big file (more than 2.7 GB) with axios to Django: const formData = new FormData() formData.append('myFile', myFile) const config = {...} axios.post(url, formData, config)... Now, it sends all the data, but the memory usage starts growing even before the view starts! def my_vies(request: HttpRequest) -> HttpResponse: print('Starts the view') ... If the file is small the message prints correctly, now with the huge file the server crashes due to memory usage before the print is reached. I've tried to change the upload handler to only use disk in settings.py: FILE_UPLOAD_HANDLERS = ['django.core.files.uploadhandler.TemporaryFileUploadHandler'] But had the same result. I don't know whats happening, I can't even try this solution as nothing of the view's code is executed. What I'm missing? Any kind of help would be really appreciated -
How do I change the text "Thanks for spending some quality time with the Web site today." in Django?
When you log out of the Django admin, it displays a string "Thanks for spending some quality time with the Web site today." Can I change that to something else? I was able to change other attributes such as admin.site.site_header = "Whatever" admin.site.site_title = "Whatever" admin.site.index_title = "Whatever" in the urls.py file which worked great so I am guessing this can be changed similarly. Thanks for your help. Tried Google, no dice. -
Dynamically load background image in template
I have a list object as follows: <div role="list" class="w-clearfix w-dyn-items w-row"> {% if latest_post_list %} {% for post in latest_post_list %} {% if post.is_published %} <div role="listitem" class="blog-thumbnail w-dyn-item w-col w-col-4"> <a href="/{{ post.id }}" data-w-id="46150442-4efa-9d36-3a4c-20d527e7a6bc" class="thumbnail-wrapper w-inline-block"> <div class="image-wrapper"> <div style="-webkit-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);-moz-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);-ms-transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0);transform:translate3d(0, 0, 0) scale3d(1, 1, 1) rotateX(0) rotateY(0) rotateZ(0) skew(0, 0)" class="thumbnail-image"></div> <div class="category-tag">{{ post.category }}</div> </div> <div class="thumbnail-text"> <div class="blog-title">{{ post.title}}</div> <div class="preview-text">{{ post.body}}</div> </div> <div class="thumb-details w-clearfix"><img src="" alt="" class="author-img"> <div class="author-title">{{ post.author }}</div> <div class="thumbnail-date">{{ post.pub_date }}</div> </div> </a> </div> {% endif %} {% endfor %} {% else %} </div> <div class="w-dyn-empty"> <p>No items found.</p> </div> {% endif %} </div> The background image is set in stylesheet: background-image: url('https://foo.bar.net/img/background-image.svg'); An image is added to the category model using an Imagefield. class Category(models.Model): created_at = models.DateTimeField('date created') updated_at = models.DateTimeField('date published') title = models.CharField(max_length=255) image = models.ImageField(upload_to='static/images') class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title I would like to have the background image set to be the uploaded category …