Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to customize Image Chooser in Wagtail?
How do I customize the Image Chooser in Wagtail? I need to block the user from having the ability to upload GIFs > ~1 MB in size. Uploading a 3 MB GIF crashes the server right now, and even a 1.5 MB GIF timed out on production. I'm using wand and ImageMagick for the GIFs, I altered the disk quota for ImageMagick but it's not a viable solution on the server, the compression takes forever. So my next step is to totally block large GIFs from being uploaded. I want to set a limit of about 1 MB for GIFs. I don't want to fork the Wagtail framework to do this. Are there any alternative suggestions to get around this GIF problem? -
Django model inline with multiple FK's for both keys to the same model under one inline
I have a situation where I have a model related by two possible foreign keys to another, and I would like to display using a single inline, all the related model fields including both possible FK's. In the example below I have the models of an account and a transaction. All transactions are credit/debit pairs, which indicate the source and destination account using the two FK's, credited_account, and debited_account. class Account(models.Model): owner = models.ForeignKey(User) account_type = models.ForeignKey(AccountType) class Transaction(models.Model): created = models.DateTimeField(auto_now_add=True) amount = models.PositiveIntegerField() credited_account = models.ForeignKey(Account, related_name='credit_transactions', on_delete=models.PROTECT) debited_account = models.ForeignKey(Account, related_name='debit_transactions', on_delete=models.PROTECT) In the AccountAdmin I would like to display all the transactions where the account is either credited or debited, using a single Inline, under a single Transactions header. I know, as per the docs, that I am able to specify them independently by indicating the foreign key and using two different inlines, like so: class DebitInline(admin.TabularInline): model = Transaction fk_name = 'debited_account' class CreditInline(admin.TabularInline): model = LedgerTransaction fk_name = 'credited_account' class AccountAdmin(admin.ModelAdmin): inlines = [CreditInline, DebitInline] The problem I'm having here is that the credit and debit transactions are separated under two different inlines, of the same header, and I would like them ordered by … -
Django Form Fields not Displaying
So I am trying to basically have a check box on an image page which lets me set a boolean field true/false if I want this image to be deemed the "profile image." The problem is that the form field options are not showing up in the template. Any suggestions? single_image.html <form method='POST' action="{% url 'set_profile_image' plant_pk=plnt.pk image_pk=img.pk %}"> {% csrf_token %} <hr> {{ form.as_p }} <hr> <input type="submit" value="Submit"> forms.py class SetProfileImageForm(forms.ModelForm): """A form to set profile image.""" image_main = forms.BooleanField(required=True) class Meta: model = Image fields = ["image_main","image_url",] views.py def set_profile_image(request, plant_pk, image_pk): """A custom view function to set profile image.""" # find the plant for whom we are setting the image plant = Plant.objects.get(pk=plant_pk) if request.method == 'POST': if "cancel" in request.POST: return redirect('display_plant', pk=plant.pk) form = SetProfileImageForm(request.POST or None, request.FILES or None) if form.is_valid(): plant.set_profile_image(image_pk) return redirect('display_plant', pk=plant.pk) else: print("Error: the form was not valid.") else: return reverse('gallery', kwargs={'pk':plant.pk}) -
django only listening at 127.0.0.1
No matter what ip I put in it always listens on 127.0.0.1 This is what I enter to start django python manage.py runserver 0.0.0.0:8000 I am running it on windows WSL ( windows subsystem for linux ) ,this is my first time doing so . Now the wierd part : If I remove '127.0.0.1' from 'allowed_host' in settings it won't start and will ask me to put '127.0.0.1' in 'allowed_host'. The starting message is Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2020 - 16:18:59 Django version 3.1.2, using settings 'document_manager.settings' Starting development server at http://0.0.0.0:8000/ however when I make any request to http://0.0.0.0:8000/ it dosen't work ,but if I make a request on 127.0.0.1 it works . -
URL Based Language Setting Instead of Browser Language Preferences
I am trying to have both Persian (RTL) and the English version of the website in separate URLs like: www.domain.com/en-us www.domain.com/fa-ir This is the first time I am doing this. Therefore, I am kind of confused about that. What I actually did was getting help from this tutorial: https://monicalent.com/blog/2014/08/10/internationalization-with-django-backbone-underscore-template-and-sass-ltr-and-rtl-language Yet, I have no idea how should I make separate URLs for each language. Settings.py: USE_I18N = True USE_L10N = True USE_TZ = True LOCAL_PATHS = ( '/locale/' ) LANGUAGE_CODE = 'en-us' LANGUAGES = ( ('en-us', 'English'), # You need to include your LANGUAGE_CODE language ('fa-ir', 'Farsi') ) Views.py of my home app: from django.shortcuts import render # Create your views here. def home(request): if hasattr(request.user, 'lang'): request.session['django_language'] = request.user.lang return render(request, 'index.html') Urls.py : from django.contrib import admin from django.urls import path import home.views urlpatterns = [ path('admin/', admin.site.urls), path('', home.views.home, name='index') ] index.html: {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Kilka Shafagh</title> </head> <body> <span>{% trans "Test" %}</span> </body> </html> However, Even when I set language preferences to persian, the translation does not occur. I would be grateful if anyone guide me through this as the related topics on stackoverflow could … -
Running a JS module in a Django project
I am a beginner and would like to use this Javascript module (meant for Node) in my Django project in which I'm using Django's template system for the front-end: https://github.com/jshemas/openGraphScraper What is the best way to do this? Do I have to run Node alongside Django separately? -
unable to deserialize self referential foreign key with custom serializer
I am using django and django-rest-framework to create APIs I have a model like this class Version(models.Model): version_tag = models.IntegerField(verbose_name=_("Version")) data = models.TextField(verbose_name=_("Data")) cloned_from = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True ) endpoint = models.ForeignKey( ManagedEndpoint, verbose_name=_("Endpoint"), related_name="versions", related_query_name="version", on_delete=models.CASCADE, ) and a serializer like this class VersionSerializer(serializers.ModelSerializer): data = serializers.JSONField() version_tag = serializers.IntegerField(required=False) cloned_from = ClonedFromSerializer(required=False) resource_purpose = serializers.CharField( source="endpoint.resource_purpose", required=False ) class Meta: model = models.Version fields = [ "resource_purpose", "version_tag", "data", "cloned_from" ] and i have custom serializer ClonedFromSerializer like this class ClonedFromSerializer(serializers.Field): def to_representation(self, value): if value.endpoint is None: return "" return "%s : %s" % (value.endpoint.resource_purpose, value.version_tag) def to_internal_value(self, data): resource_purpose, version_tag = data.split(":") try: endpoint = models.ManagedEndpoint.objects.get( resource_purpose=resource_purpose.strip() ) return models.Version.objects.get( endpoint=endpoint, version_tag=version_tag.strip() ) except models.ManagedEndpoint.DoesNotExist: raise serializers.ValidationError( "invalid clone_from value passed" ) What I wanted to do is, cloned_from should output a string with resource_purpose and version_tag which is working correctly. What is not working is that when I make a post call i.e. when i want to create a new version with cloned_from is passed as a string, it is creating with clone_from=None. I don't have a clue why it is still None when am returning Version object. can anyone help ? -
How to show the total count of online users in the template (django)?
This is my user model- class CustomUser(AbstractUser): user_id = models.UUIDField(default=uuid.uuid4,editable=False,primary_key=True) username = models.CharField(max_length = 100,unique = True) friends = models.ManyToManyField('CustomUser',related_name="friend", blank= True) user_last_seen = models.DateTimeField(auto_now_add=False) I am able to track the time when a user was last seen (whether they log out or not) using the following middleware: class ActiveUserMiddleware(MiddlewareMixin): def process_request(self, request): current_user = request.user if request.user.is_authenticated: now = datetime.datetime.now() current_user.user_last_seen = now current_user.save(update_fields=['user_last_seen']) And also able to show in my template that whether they are active at the current moment, or when they were last seen - {%if i.user_last_seen|timesince|upto:',' < "1 minutes" %} <td style="font-size:small; color:green;text-align:right;"> Active Now </td> {%else%} <td style="font-size:small; color:gray;text-align:right;"> {{i.user_last_seen|timesince|upto:','}} ago </td> {%endif%} Along with this, I want to show the total number of users that are active right now. But I am having a hard time to understand how to do that exactly. I am still a beginner when it comes to Django, any suggestions or ideas would be really helpful. -
Django postgres connection, SET timezone for psycopg2
In django settings.py I have TIME_ZONE = 'Asia/Tbilisi' I have same timezone for postgres also and separately, both works correctly. Though, in Django, when I run raw queries like: from django.db import connection ... cursor = connection.cursor() cursor.execute("select localtimestamp(0)") res = cursor.fetchall() This shows datetime with UTC time zone. Probably this is caused by psycopg2 connection settings? because this: print( connection.cursor().connection.get_parameter_status("TimeZone") ) shows: UTC. Question: How can I change this connection settings and SET needed timezone? -
Django hosting raw HTML files behind authentication
I inherited an NGINX/Gunicorn/Django (1.11) server. I've only been poking around with Django for a little while. We have a piece of software that not everyone has a license for. It can dump out its data in a series of linked HTML files: index.html models/model_a.html models/model_b.html models/model_b/model_1.html models/model_b/model_2.html And so on. They're all linked together and navigable from the top-most file, index.html. I created a menu button and I linked it to a location where the HTML model is stored. Users can navigate to it and browse around, exactly as expected. Here's my problem. We're using SAML authentication. To use the menu button in Django, you obviously have to be logged in. But once you are sent to the link, you can reuse it forever. A user can send out the URL and and anyone using the link will bypass logging in completely. The URL would look like this: https://example.com/models/model_b/model_1.html Again, anyone with that URL can get to the information. I want to ensure anyone trying to access that HTML render of the software's model has to authenticate first. Any ideas? (Sorry if it's a basic question. I'm new at this and I'm not very smart in general. So there's … -
Email Verification django rest framework
I am creating an api using Django Rest Framework, when user signs up (registers) for an account, the user receives a verification email, with a verification link, once clicked the account should be verified. I got the email sending part working and configured. My question is: How to have the link in the verify-email endpoint activate account when user clicks on it (decode payload) ? I cannot seem to find what I am looking for over the internet, I browsed the DRF documentation, but could not find it. I am using Django Token Authentication for authentication, that ships with Django rest. Your inputs are much appreciated. Thank you. -
How to generate slug according to title of post in django?
Well i dont want to work with id of post in my urls so i want to generate slug according to to post title and that can be same. so i dont understand how can i do that can you guys tell me it can be done, my model post is given below. model.py class Post(models.Model): username = models.ForeignKey(UserProfile, on_delete=models.CASCADE) description = models.CharField(('Description'),max_length=250) title = models.CharField(('Content Title'), max_length=250) create_date = models.DateTimeField(default = timezone.now) image_data = models.ImageField(upload_to='User_Posts', height_field=None, width_field=None, max_length=None) slug = (title) def __str__(self): return self.title -
How do I get the API Key message to go away TinyMCE? (Django)
I've included the TinyMCE editor into my program and it's showing up, but says I need to add a API key. I've tried doing this but can't figure out where: {% extends "blog/base.html" %} {% load crispy_forms_tags %} <head> <script src="https://cdn.tiny.cloud/1/<KEY>/tinymce/4/tinymce.min.js" referrerpolicy="origin"></script> </head> {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} {{ form.media }} <fieldset class="form-group" id = #mytextarea> <legend class="border-bottom mb-4">Add Law</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Finish</button> </div> </form> </div> {% endblock content %} This is my form.html template. Here is my settings.py: TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'silver', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } TINYMCE_JS_URL = 'https://cdn.tiny.cloud/1/<KEY>/tinymce/5/tinymce.min.js' and finally my … -
For loop in Django doesnt show up the result from database
i have a problem with for loop. First i have this views.py: from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html') As you see from the .models i am importing everything (*), but in particular i am interested in class Product (code from models.py): class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) def __str__(self): return self.name Then in Django admin http://127.0.0.1:8000/admin i have created several products: So i have the model, products in database and view. Finally in my template store.html i have for loop: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img src="{% static 'img/placeholder.png' %}" alt="" class="thumbnail"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <button class="btn btn-outline-secondary add-btn">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float: right"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} But it doesnt show the products from the database: If i delete in store.html a for loop: {% for product in products %} and {% endfor %} Then the plain html displays. Any clue why the for loop doesnt work please? … -
Python create_user Object of type 'set' is not JSON serializable
I have this code: class usuario(APIView): def post(self, request): try: data = json.dumps(request.data) #usuario = UserSerializer(data = request.data) #print(usuario) #if usuario.is_valid(): # print(usuario.data) #print("'"+str(data['email'])+"'") #firebase_admin.initialize_app() user = auth.create_user( email='user@example.com', email_verified=False, phone_number='+15555550100', password='secretPassword', display_name='John Doe', photo_url='http://www.example.com/12345678/photo.png', disabled=False) print('Sucessfully created new user: {0}'.format(user.uid)) return JsonResponse({"user": 'teste}'}, status=status.HTTP_201_CREATED) except Exception as ex: print(ex) return JsonResponse({"Ocorreu um erro no servidor"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, safe=False) When I try to do a post request with postman, it returns: Object of type 'set' is not JSON serializable line 37, in post Line 37 is: disabled=False) -
Django Rest frame work error get() returned more than one Customer_Notes -- it returned 3
I am using react app to fetch data from a django rest api. The issue here is there are multiple notes added for one single user and when I am trying to make a get request it is throwing the above error. It is allowing me to only fetch one single row when i specify the lookup field to be pk. However I want to return all the objects. class Customer_NotesViewSet(viewsets.ModelViewSet): queryset = Customer_Notes.objects.all() serializer_class = serializers.Customer_NotesSerializer lookup_field = 'customer' class Customer_NotesSerializer(serializers.ModelSerializer): class Meta: model = Customer_Notes fields = "__all__" What changes or work around can be done here ? -
ProgrammingError at /accounts/facebook/login/token/
I'm having trouble setting up the facebook login in django. Whenever I click the facebook log-in link it tells me this: ProgrammingError at /accounts/facebook/login/token/ (1146, "Table 'user$db.account_emailaddress' doesn't exist") I followed the set up recommended here. From what the error message says I suspect it is related to the migrations in my database. The Traceback leads me to /allauth/account/utils.py where I can the see the problem is the use of EmailAddress.objects.filter(). In fact, when I go in the shell and try: from allauth.account.models import EmailAddress I can import EmailAddress successfully. It's only when I try to use EmailAddress.objects.all() that I get the same 1146 error. I tried to redo all migrations related to allauth but my database still never shows any table related to allauth or account. Here are the details of my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'social_django.context_processors.login_redirect', 'django.template.context_processors.request', ], }, }, ] INSTALLED_APPS = [ 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.messages', 'django.contrib.sites', 'social_django', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'custom_user.apps.CustomUserConfig', 'user_profile', 'django_email_verification', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] SITE_ID = 1 and urls.py: urlpatterns = [ path('accounts/',include('allauth.urls')), path('request-reset-email', RequestResetEmailView.as_view(), name='request-reset-email'), ] Thanks everybody for your help. -
Django redirect interfering with stat files loading
I am having a Django app where users search for files that are generated as reports (edited html creating reports Impression) . On the front-end,the search form makes a Get action '/search/q=someValue' However,the query url needs to be replaced and so I updated my views.py such that Def search_view(request): //Validate the query is valid //Redirect to some_new_url Def some_new_url(request): //Now use this view for search When i carry out a search, static files are not applying but if i navigate using internal links referencing the same url(some_new_url) everything works okay.What could be the issue -
Counting specific field of deeply nested Object django
I have a model Category and it has children and also the Product model looks like this class Category(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, related_name='children') product_count = models.IntegerField(null=True) class Product(models.Model): category = models.ForeignKey(Category) sub_category = models.ForeignKey(Category, related_name='sub_category_products') name = models.CharField(max_length=300) price = models.DecimalField() and I need to count all products belong to the specified category it can be in the subcategory of the category. The Category model can be deeply nested. How can I do this query! Any would be appreciated. Thanks in advance! -
TemplateSyntaxError at Could not parse the remainder:
I'm new to Django and trying to get path details of one specific image from the ProductImage table using the place field in the table and display the image.Where place == 'Main Img' Product and ProductImage has one to many relationship. My database has two tables named Product(id, name, price,..) and ProductImage(id, productid, image, place) which contains three images('Main IMG', 'Sub Img 1', 'Sub Img 2') Here is my models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length=200) desc = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) discount = models.DecimalField(max_digits=4, decimal_places=0) def __str__(self): return self.name class ProductImage(models.Model): PLACEHOLDER= ( ('Main Image', 'Main Image'), ('Sub Img 1', 'Sub Img 1'), ('Sub Img 2', 'Sub Img 2'), ) product = models.ForeignKey(Product, related_name='image_set', on_delete=models.CASCADE) image = models.ImageField(upload_to='images/') place = models.CharField(max_length=20, choices=PLACEHOLDER) def __str__(self): return str(self.id) views.py def menu(request): products = Product.objects images = ProductImage.objects context = {'products': products, 'images': images} return render(request, 'store/menu.html', context) Template {% for product in products.all %} <a href="#"> <img src="{{ images.filter(product__id=product.id, place='Main Product Image')[0].image.url }}" class="img-fluid mt-3"> {% if product.discount != 0 %} <span class="bonus">{{ product.discount }}% off</span> {% endif %} </a> settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Media files … -
Hbase login with django
Good morning, I have a question, I am new in apache Hadoop and django. I am creating login in django but i don't know how customing it becouse only know native methods like: "authenticate()" and "login()", now I am using login() but this needs a model user auth instance. I need create a login based in hbase tables. This is my example code user = User.objects.get(username=username) login(request,user) But in the user var recive a instance of mysql model and I need use Hbase Thanks in advance -
Django Form - Create new entries with multiple foreign k
I have searched a lot about this topic here, but i haven't found the right answer. Here is my problem, i want to create a form(not in admin) where the website users can create new entries, and fill the foreign key for my model Market (who has multiple foreignkey to other models). So in this this form the user can create new entries from the models city, provider and service.(i hope i explain it well) What i try to do is to fill 4 models with a single submit for the user. So far i managed to save one foreign key, using instance with and inlineformset_factory, but i want to know what i have to do in order to write the user input in my 4 models. I want to have only one entry for the models that are related as foreign key, that's why i put extra and max_num at 1 and can_delete as false here is my code, hoping you'll be able to help me. Thanks in advance models.py from django.db import models class Market(models.Model): number = models.CharField(max_length=7) title = models.CharField(max_length=200) description = models.CharField(max_length=200) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) service = models.ForeignKey(Service, on_delete=models.CASCADE, null=True) provider = models.ForeignKey(Provider, on_delete=models.CASCADE, … -
In django are @transaction.atomic auto applied to nested methods also
I have just started learning django and came across this confusion consider the below code @transaction.atomic def first_method() doing stuff calling_method() def calling_method() items = item.objects.filter(item_id__in=[list of items]) for item in items: item.save() Will the above code save item records one by one in db or will it save all the items at once because I have used @transaction.atomic at the first method? If I have to save all the item records at once in db should I use @transaction.atomic in calling_method() as well? -
Django: put all loop result into one bloc json
Django - Json I've tried many time to get all the result of the loop ['results'][0]['analyzedInstructions'][0]['steps'][steps] (multiple results) in only one bloc. But that does not work. Do you have any idea to get all this results and put them together? All others fields works, and the json location is good. try: name = response_title_data['results'][0]['title'] ... steps = "" for step in response_title_data['results'][0]['analyzedInstructions'][0]['steps']: steps += step.step current_post = get_object_or_404(Post, slug=self.slug) create_recipe = self.recipe.create(name=name,source=source,url=url,score=score_brut,steps=steps) current_post.recipe.add(create_recipe) except Exception as e: pass -
Django queryset annotation filters (for max)
I have the following model: class Room(models.Model): # model fields class Table(models.Model): room = models.ForeignKey( Room, [...], related_name='tables' ) class Seat(models.Model): table = models.ForeignKey( Table, [...], related_name='seats' ) timestamp = models.DateTimeField(auto_now_add=True) is_vip = models.BooleanField(default=False) I would like to get the timestamp of the latest seat with a vip on it. Getting the latest seat is easy like this: Room.objects.all().annotate(latest_seat=Max('tables__seats__timestamp')) But how do I filter this on is_vip=True only?