Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin not allowing superuser to log in (Custom User Model)
I have created a custom user class which appears to be working correctly however whenever I try to log in to the admin, I keep getting the following error on the login page: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. I have already created several superuser which are all saving to the DB correctly with the is_staff/is_superuser/is_active flags set to True as you can see below: CustomUser.objects.all().values() <QuerySet [{'id': 1, 'password': 'test', 'last_login': None, 'is_superuser': True, 'username': 'test1', 'first_name': '', 'last_name': '', 'email': 'test1@test.com', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2020, 6, 1, 0, 17, 30, 297149, tzinfo=<UTC>), 'role_id': 1, 'user_type_id': 1, 'created_by_id': None, 'update_date': datetime.datetime(2020, 6, 1, 0, 17, 30, 298524, tzinfo=<UTC>), 'updated_by_id': None}]> I am officially puzzled as to what I have done incorrectly... Please help me figure this one out... models.py: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.conf import settings class UserType(models.Model): """ This model defines the types of users which are allowed to be created in the application. Examples include: API Read Only User API Full CRUD User Business User """ name = models.CharField(max_length=50, blank=False, null=False) description = models.TextField() active = models.BooleanField(default=True) … -
How to edit user's profile view with django
I am making a form in which the user can edit their profile, so currentley I have 2 forms, one that edits the User model(first_name, Username and Email) and other one that edits the Profile model(biography). The problem is that everytime I edit, just the User model is the one that gets saved while the Profile model doesnt. I think that the error is on the views.py file. views.py def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) form1 = UpdateProfileForm(request.POST, instance=request.user) if form.is_valid: form.save() form1.save() return redirect('profile') else: form = EditProfileForm(instance=request.user) form1 = UpdateProfileForm(instance=request.user) args = { 'form': form, 'form1': form1, } return render(request, 'profile-edit.html', args) forms.py class EditProfileForm(UserChangeForm): class Meta: model = User fields = ( 'first_name', 'username', 'email', ) exclude = ('password',) class UpdateProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'bio', 'profile_pic', ) exclude = ('user',) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=400, default=1) def __str__(self): return f'{self.user.username} Profile' profile-edit.html (I replaced the {{form.as_p}} and {{ form1.as_p }} to the following html code) <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="edit-profile"> <h3>Name</h3> <input type="text" name="first_name" value="{{ user.first_name }}" maxlength="30" id="id_first_name"> <h3>Username</h3> <input type="text" name="username" value="{{ user.username }}" maxlength="150" required="" id="id_username"> <h3>Bio</h3> … -
How do I get my Django context variables into my JS file?
I'm trying to get data from a Django Backend to display on a map with Google Maps API, but I can't figure out how to pass the variables into the Javascript. Can someone please help me figure out what I'm doing wrong? Django Method: def home(request): //stuff that processes the method return render(request, 'map/index.html', {'lats': lats, "longs": longs, 'lat': lat, 'long': long, 'names': names, 'scores': scores}) HTML Snippet: <script> src = getlocation.js></script> <!-- this implements the navbar--> <div id="navbar"></div> <script type = "module" src = ../../static/navbar.js></script> <!-- input tag--> <form method="post"> {% csrf_token %} <input id="address" type="text" name="address"> <input type="submit" style="display: none" /> </form> <script> var names = {{ names }}; var lats = {{ lats }}; var longs = {{ longs }}; var scores = {{ scores }}; var lat = {{ lat }}; var long = {{ long }}; </script> <!-- this implements the map--> <div id="map"></div> <script src = ../../static/index.js> </script> Javascript Snippet(index.js): let locations = new Array(names.length); for(let count = 0; count < names.length; count++){ locations[count] = [names[count], lats[count], longs[count], scores[count]]; } let curlat = lat, curlong = long; -
slice requires 2 arguments, 1 provided
I'm trying to add some values from another list synchronously in the for loop of django ’s template. When I use a given number everything works fine, but when I replace it to {{forloop.counter}} it reports an error slice requires 2 arguments, 1 provided I Googled it and the suggestion is that there should be no spaces in the code, but there are no spaces in my code, here the code in question. {% for i in invtypes %} <li> ... <p>{{data|slice:":{{forloop.counter}}"}}</p> </li> {% endfor %} The {{data}} is a list of extra data for invtypes so they have same length and sort。 -
Django: How to use javascript variable in url template tag
I want to use a javascript variable as the pk for my django url template tag. It has been asked before, but none of the solutions work for me. See for example Get javascript variable's value in Django url template tag. I tried the solution suggested by @Mike Lee, i.e.: var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, var.toString()); However, when I try this, it redirects to /12345, in other words the replacement is not made. A bit of context of what I am trying to do: I have flashcards. Studying flashcards is done via javascript. In my js file, there are variables to get the necessary cards, show the current card etc. I have a button in my html that is supposed to redirect to a page where you can edit the flashcard. So for example, I have: <a id="button" class="btn btn-default btn-warning" id='button-study' href="{% url 'flash:edit' card.id %}">Edit</a> card.id is just a placeholder - I need this to refer to whichever card is showing at any given time. When studying, when I look at the console, I can see the details of the current card, including the id, which is what I need to put in the url … -
Show different requests in different endpoints in Swagger (DJANGO)
I have 4 requests A,B,C and D defined in urls.py What I want to accomplish is -> I want A and B to be seen in the swagger form that can be accessed with url mydomain/firstapi and C and D to be seen in the swagger form that can be accessed with mydomain/secondapi. But what ends up happening is that both of these urls show the same swagger form. Requests A and B are listed below firstapi and request C and D are listed below secondapi as expected (but both of these groups can be seen in both urls which is precisely what I wanted to avoid) What I have tried is #urls.py firstapipatterns= ([ path('a', AView.as_view()), path('b', BView.as_view()), ], 'secondapi') secondapipatterns= ([ path('c', CView.as_view()), path('d', DView.as_view()), ], 'secondapi') urlpatterns = [ path('firstapi/', include(firstapipatterns)), path('secondapi/', include(secondapipatterns)), ] -
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 :)