Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use actions in django admin to update from a different model list in bulk
Populate action list automatically from a another model class Post_admin(admin.ModelAdmin): list_display = ('title', 'category', 'author', 'created', 'draft') search_fields = ('title', 'content', 'created', 'slug') list_filter = ('author', 'created', 'draft') actions = ['publish_drafts', 'draft_published'] def draft_published(self, request, queryset): queryset.update(draft=True) def publish_drafts(self, request, queryset): queryset.update(draft=False) -
Handling ForeignKey in GraphQL (graphene)
I'm using Django-Graphene to build and API for my webapp. I've built this simple structure where I have Product that belong to a category: from graphene_django import DjangoObjectType import graphene from .models import ProductModel, CategoryModel class CategoryType(DjangoObjectType): class Meta: model = CategoryModel class ProductType(DjangoObjectType): category = graphene.Field(CategoryType) class Meta: model = ProductModel class CategoryInput(graphene.InputObjectType): title = graphene.String() class ProductInput(graphene.InputObjectType): title = graphene.String() category = graphene.Field(CategoryInput) class Query(graphene.ObjectType): products = graphene.List(ProductType) categories = graphene.List(CategoryType) def resolve_products(self, info): return ProductModel.objects.all() def resolve_categories(self, info): return CategoryModel.objects.all() class CreateProduct(graphene.Mutation): class Arguments: product_data = ProductInput(required=True) product = graphene.Field(ProductType) @staticmethod def mutate(self, info, product_data): product = ProductModel.objects.create(**product_data) product.save() return CreateProduct(product=product) class CreateCategory(graphene.Mutation): class Arguments: title = graphene.String() category = graphene.Field(CategoryType) def mutate(self, info, title): category = CategoryModel(title=title) category.save() return CreateCategory(category=category) class Mutations(graphene.ObjectType): create_product = CreateProduct.Field() create_category = CreateCategory.Field() schema = graphene.Schema(query=Query, mutation=Mutations) But when I try to mutate, I need to pass an instance of the CategoryModel, which I can't figure out how to do: mutation X { createProduct(productData: {title: "title", category: {}}) { product { id } } } My goal is to create products which require a title and a category. I'm sure there is a way to do this. Thanks in advance! Let … -
Custom font on simple html website will not load
I have been following code and examples online to try and use a custom font on my very basic html website. If it matters, I am using django. Files of note: aurebesh_translator.html <!DOCTYPE html> <html> <link rel="stylesheet" type="text/css" href="main.css"> <p>This should be in aurebesh</p> </html> main.css @font-face { font-family: "aurebesh"; src: url(aurebesh.ttf); font-style: normal; font-weight: 100; } p { font-family: aurebesh; font-weight: 100; } These are arranged as follows: | templates | - ... | - main.css | - aurebesh_translator.html | - fonts | -- aurebesh.ttf ... where the aurebesh.ttf file is the associated font file for the font I want to use. From what I can tell online, this seems to be the way it is supposed to be formatted to use my custom font. The weird thing is, if I just copy the above files to my desktop (so that only main.css, aurebesh_translator.html, and fonts/aurebesh.ttf are present) and run the aurebesh_translator.html in a browser, it loads and uses the font successfully! This is super weird to me, because when I include these files in the context of the rest of my website's files, it somehow stops working! I have tried opening it in chrome as well as firefox … -
Set language of PasswordResetForm in Django?
I am manually resetting passwords but wonder how to set the language to the user's language instead of my own. I see there are many extra context fields but which one needs to be set? for user in qs: reset_form = PasswordResetForm({'email': user.email}) # reset_form.language? assert reset_form.is_valid() reset_form.save(request=request) I have added a field CustomUser.language which would be available in user.language above. -
How to request user login in models or views
I am newbie in Django, and I can’t figure out how to get username through request. I’m working on vocabulary type site and I need that every entry user creates would have username. Here is my models.py from django.db import models class EngDict(models.Model): orig_word = models.CharField(max_length=500, null=False,blank=False, verbose_name='Слово') translate = models.CharField(max_length=500,null=False,blank=False, verbose_name="Перевод") remarks = models.TextField(null=True, blank=True, verbose_name="Примечания") published_by = models.CharField(max_length=50, verbose_name="Добавлено") published_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Дата добавления") category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT, verbose_name = 'Категория') class Meta: verbose_name = ("Перевод") verbose_name_plural = "Англо-русский словарь" ordering = ['-published_date'] А это views.py from django.shortcuts import render from django.template import loader from .models import EngDict, Category from django.views.generic.edit import CreateView from .forms import EngDictForm from django.urls import reverse_lazy from django.views.generic import TemplateView, ListView, FormView from django.db.models import Q from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login class EngDictCreateView(CreateView): template_name = 'dict/create.html' form_class = EngDictForm success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.objects.all() return context I see that I need some function like def user_name(request) , but I can’t understand where i should write it and what must be inside of it. I need that published_by variable was automatically filled in with user login -
Trouble with Email Verification in Django
Is there any packages that are working on Django 3 that is easy to use for email-verification (just an email for an activation link)? I'm having a tough time finding anything that works. Thanks -
Django template tags method inside javascript
in my product model i have a choice field : TAG_CHOICES = ( ("New", "primary"), ("Sale", "secondary"), ("Fresh", "success"), ) so in my template if i want to display the TAG value (not the Tag name ) of a product list i cant do something like this: {% for obj in products %} {{ obj.get_Tag_value}} {% endfor %} which will result in displaying:primary or secondary or success but how can i do the same thing when am using a an Ajax get request and the JSON response array look like this: [{"model": "products.product", "pk": 1, "fields": {"title": "t-shirt", "description": "awesome t-shirt", "price": "39.99", "discount": "0.00", "slug": "", "category": "Mens Collection", "Type": "T-shirts", "TAG": "New"}}, {"model": "products.product", "pk": 2, "fields": {"title": "women t-shirt", "description": "awesome women t-sshirt", "price": "39.99", "discount": "0.00", "slug": "tshirt-2", "category": "Women Collection", "Type": "T-shirts", "TAG": "New"}}] because get_Tag_value is a a method not field value -
Django Queryset How to add field using reverse foreign key
I have below two models, class Person(models.Model): name = models.CharField(unique=True, max_length=45) nationality = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class UserOption(DFModel): user = models.ForeignKey('User', on_delete=models.CASCADE) option = models.CharField(max_length=40) person = models.ForeignKey('Person', on_delete=models.PROTECT, null=True) status = models.BooleanField(default=False) Below is the viewset class PersonViewSet(viewsets.ModelViewSet): queryset = apis_models.Person.objects.all() serializer_class = apis_serializers.PersonSerializer permission_classes = [HasPermPage] In above Person view I need to add useroption value associated with it for current logged in user. UserOption model has User as well as Person. { "id": 151, "name": "Emma Watson", "nationality": "USA", ”option”: “True”. ##This is what needs to be added } This is really very complicated and I did not find any answer yet. Please advise. -
Edit saved embedded youtube video height and width using django ckeditor
I have been successful in embedding Youtube video in Django admin using django ckeditor. The problem is, if I have saved a Youtube video and set a certain height and width of the embedded video, I can't seem to be able to edit the width and height. The only way I can do it is by deleting the old embedded video and add a new one which is not ideal. Is there a way to do this without re-embedding this video? My ckeditor configs in settings.py: CKEDITOR_CONFIGS = { 'default': { 'height': 800, 'width': 1200, 'toolbar_Full': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['CodeSnippet'], ['Youtube'], ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['NumberedList', 'BulletedList'], ['Indent', 'Outdent'], ['Maximize'], ], 'extraPlugins': 'justify, liststyle, indent, codesnippet, youtube', # this setting is needed so that you can see the embedded ytv # once saved in the editor 'allowedContent': True, 'removePlugins': 'iframe', } } -
Consuming API in django
I am trying to access NASA's Astronomy Picture of the day with django, Please how should i do it def apod(request): response = requests.get('https://api.nasa.gov') run = response.json() return render(request, 'apod.html', {'run': run}) -
Django send data to Javascript File
I know how to send data from Django to html with the view def index(request): coord = "[[1, 2], [2, 1]" return render(request, 'index.html', {'coord': coord}) In the html I able to use it any where like this {{ coord }}, example : <script type="text/javascript"> var geojsonObject = { "coordinates": {{ coord }} }; </script> But when I try to do this in my 'index.js' I get an error: Uncaught SyntaxError: Unexpected token '{' index.html <script src="{% static 'index.js'%}"></script> index.js var geojsonObject = { "coordinates": {{ coord }} }; I could keep everything in index.html, but I find it not practical to debug. How can I pass my coor object to the JavaScript through html? -
How to use TextField from Django in JavaScript?
I have a Django model: class MyModel(models.Model): charField = models.CharField(maxLength=200) textField = models.TextField() and an HTML template with a JS function that displays charField and textField like this: document.getElementById("someElement").innerHTML = "{{ myObject.charField }}"; document.getElementById("someOtherElement").innerHTML = "{{ myObject.textField }}"; The former works fine, but the latter doesn't. I assume the problem is the fact that it is a TextField because there is no other difference between the two. How can I fix this? -
Django: how to generate activate_url that Django allauth generates for email confirmation
Django allauth sends an account confirmation email with activate url which is {{activate_url}}. One example for this url is http://127.0.0.1:8000/accounts/confirm-email/NTM:1jfPhE:KyDCaadIYlHM23UbccSVcDnzdJU/. But I can't use allauth to handle for sending confirmation emails as I am using Gmail account for sending emails and Gmail is not allowing to send email with allauth because it was not secure enough. So I used Gmail API to send emails and using @receiver(user_signed_up) to send confirmation emails. But I want to allauth to handle the activation process and I see that allauth uses {{activate_url}} link for verifying the email for the account. How do I generate this {{activate_url}} so that I send the email with this link and allauth handles confirming email from there? -
How to generate model in a deployed django app for loading excel data
Recently started crash course in django due to a project requirement at work and started building a simple app to read and write data using form with filefield to the oracle database. two questions whr i need your expert advise - one of the page i am building will allow the user to upload excel data to a database table using the model. 1) since thr r multiple tables where the data needs to loaded. can i create a dropdown of table names to load the data to that tble dynamically based on model section 2) if thr are new tables created in future without any chages needed on the ui side whr users shld load data to tht new table with diff columns, does django have the ability to create models without having to deploy the app again. can we use something like inspectdb directly with a click of a button from ui so that those models are generated allowing the users to load data. side note - I am disabling the admin app since our project does not need it. your advise would a great guidance and help for my project. Thank you. -
Loading Map in GeoDjango Admin Interface
I am currently following this tutorial, attempting to load a user's location on an open street map. When testing in my admin interface the map is not loading properly When going through the tutorial I tried a different method of registering the map in my admin interface. Is this the problem? or do I just need a different browser? #admin.py from django.contrib.gis.admin import OSMGeoAdmin, register class LocAdmin(OSMGeoAdmin): list_display = ('street1', 'city', 'state', 'zip', 'loc') admin.site.register(Loc, LocAdmin) -
Permssion for View Set not working (Django Rest Framework)
I have custom permission for Profile View Set: class PermissionsForProfile(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True else: return obj.user == request.user Profile view set: { "url": "https://.../api/v1/profiles/2/", "user": "https://.../api/v1/users/2/", "gender": null, "status": null, "birthday": null, "city": null, "about": null, "first_name": "Test", "last_name": "Test", "image": "https://.../images/users/2/test.jpg", "points": 0, "profile_type": 1 } I logged in from the user with ID = 2 ("user" field equal user's URL) and I can not do PUT request. Looks like this user is not an owner of this object. How to fix it? -
Do I need to user Angular.js AND Django to create SPAs?
I am trying to create a dashboard SPA. I am confused on what Angular and django can offer. I have read a lot of descriptions and examples online but was unable to learn the actual use of Angular and Django. Also I need to create a good looking SPA with gradients, animations, and transitions. Is Angular enough for that? Below is an example of what I am trying to create. Also, how can I use Angular.js and Django to create such application ? Thanks! -
Django NoReverseMatch and wrong URL Pattern matching attempt
I am new to Django and trying to learn by creating a Blog App. Now I ran into an error I am not able to solve. I tried everything and compared it to the tutorial I am following but it seems to be the same but for me it is not working. So I have some posts which are listed on my feed page and when I want to click on the post title to get to the 'post-detail' page I am getting a NoReverseMatch Error because Django somehow tries to match with a wrong URL pattern, which is 'user-feed' but instead I am expecting to match with 'post-detail'. Error Message: Reverse for 'user-feed' with arguments '('',)' not found. 2 pattern(s) tried: ['feed/user/(?P<username>[^/]+)/$', 'user/(?P<username>[^/]+)/$'] Feed.html: {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-feed' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"d. F Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} My urls.py for my feed app looks as follows: urlpatterns = [ path('', login_required(PostListView.as_view()), name='feed-home'), path('user/<str:username>/', login_required(UserPostListView.as_view()), name='user-feed'), path('post/<int:pk>/', login_required(PostDetailView.as_view()), name='post-detail'), path('post/new/', … -
Deploying to Heroku: ImportError:Couldn't import Django
my StackOverflow friends, When I want to deploy my code to Heroku using git push heroku master I have ImportError:Couldn't import Django. So I try python manage.py runserver to see what is going on and it shows this in the terminal. Full description of ImportError:Couldn't import Django. Before I tab all the process for deploying my code to Heroku,python manage.py runserver works well (the system gives me a link to open my Web page). I am very new in PyCharm and Heroku and I do not know what is going on. I read a little bit about virtualenv, but I still do not know what is that. If you can help me, please tell me in details what should I do in basic programming language. Thank you so much :) -
TemplateDoesNotExist : Template Not being detected on Django
Thanks to land at my concern. I would be thankful if you will help me out. Earlier i was doing same procedure to fetch the template, that time working. But recently i tried to make another project, now this time, getting "TemplateDoesNotExist" error. TemplateDoesNotExist at / technicalcourses/Courses.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.4 Exception Type: TemplateDoesNotExist Exception Value: technicalcourses/Courses.html Exception Location: C:\Program Files\Python37\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Program Files\Python37\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\ravik\Desktop\Django_New_Project\edureka', 'C:\Program Files\Python37\python37.zip', 'C:\Program Files\Python37\DLLs', 'C:\Program Files\Python37\lib', 'C:\Program Files\Python37', 'C:\Program Files\Python37\lib\site-packages', 'C:\Program Files\Python37\lib\site-packages\win32', 'C:\Program Files\Python37\lib\site-packages\win32\lib', 'C:\Program Files\Python37\lib\site-packages\Pythonwin'] Server time: Sun, 31 May 2020 19:54:29 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\ravik\Desktop\Django_New_Project\edureka\template\technicalcourses\Courses.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Program Files\Python37\lib\site-packages\django\contrib\admin\templates\technicalcourses\Courses.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Program Files\Python37\lib\site-packages\django\contrib\auth\templates\technicalcourses\Courses.html (Source does not exist) ****Here Below I have completed- Kindly attached images **** enter image description here enter image description here enter image description here -
Best practice for using Django templates and connect it to database
I am trying to build a database for my website. There are currently three entries with different attributes in my database. I have not created these entries in order, but I have assigned a 'Chapter number' attribute which indicates the order 1,2,3. I am now trying to inject this using 'context' and 'render' function in my views. I am using the method 'objects.all()' to add all objects to my context. I have a simple Html file where I am inserting the data from the database by looping over (a simple for loop) these added objects. Now the output that is being generated (naturally) is that it is following the order in which I created the database. I am not sure how I can have the loop run in such a way that I get these chapters in correct order. Thank you for patiently reading my question. Any help will be appreciated. -
Link a button to a counter in HTML
For an easy project, I want to match up a button to a counter and is there anyway to do that without having a token and a post method? I know that the post just refreshes my page each time, and the button animation gets cut off. In the end, I would want a counter to go up when a button is clicked. Here is my code already: <form method="POST"> {% csrf_token %} <button class="asdf btn-floating btn-large waves-effect waves-light red darken-3" type="submit"><i class="material-icons">exposure_plus_1</i></button> </form> So is there any way to do this without the POST request? I already know that I can get it to work, but not without reloading the page after each click. -
Django Settings and GitHub Action Secrets
I have a Django project and am using a Postgres database. I want to figure out a simpler way to store my credentials locally and on Github so that I can run tests in both places but where none of my sensitive info is in the git repo. Even though the database only exists on my computer (and the Github test database only exists for about a minute at a time on GitHub) I want to use the best practice possible for SECRETS so when I do go live, I am all set. Currently, the only sensitive data I have is database passwords. Here is how I am keeping my real passwords out of GitHub. settings.py (in Git): VAR_1='abc' VAR_2 = '123' #DOES NOT INCLUDE DATABASE CONFIG VAR_3 = 'efg' # Add settings from local file into main settings try: from .localsettings import * except ImportError: import sys print('localsettings not defined.') localsettings.py (not in Git): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'real-db-name', 'USER': 'real-user', 'PASSWORD': 'real-password', 'HOST': 'localhost', 'PORT': '', } } testsettings.py (in Git): # import main settings and then overright certian values try: from .settings import * except ImportError: import sys print('settings not defined.') DATABASES = … -
django custom manager manytomany field add
My code for custom manager below: class CustomManager(models.Manager): def create(self, **kwargs): obj, created = Group.objects.get_or_create(name='group1') kwargs.update({'groups': obj}) return super(CustomManager, self).create(**kwargs) which creates TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead.. -
Django model to record transactions from two different apps of a Bookstore website
I am new to Django and i'd like to build a bookstore. The site will sell 2 types of products (Books and Individual question solutions) and i have split those into 2 different django apps. How can i handle the final individual purchases. Is there a way to for example have 1 'Purchase' model that will recieve either Books or Solutions and save transaction into database upon completion of purchase ? I want this Purchase model to have title, date of purchase, customer info (name and email).