Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: This queryset contains a reference to an outer query and may only be used in a subquery
I have a queryset which returns an error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I need a little help to know that what I am doing wrong. Below is my query def get_queryset(filters: dict) -> QuerySet: return JobDest.objects.filter( line__j_id=filters["j_id"] ).annotate(c_count=(Value(Subquery(Candidate.objects.filter(job=filters["j_id"], is_d=False, stage=OuterRef('id')).count())))) -
how to create custom flag like is_staff and is_anonymous in django
There are some Boolean fields in django User Model, for example is_staff, is_anonymous. how can in create my own Boolean for example is_student and add it into django User model -
How to activate an account that has been registred trough e-mail with Django
I want to when my user is registred to generate a token and that token to be sent to e-mail to when I click the link verify the account code: def register_account(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' email_body = 'i dont know to do do it' email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to], fail_silently=False //////////////////// def activate_account: if the link is clicked: check the link than activate the account -
digital ocean django website deployment in a function
I'm designing a website and I would like to use digitalocean hosting. I have seen the tutorials to set up django on a server or on the app platform but i havent seen anything to set up django as served by a function (like aws lambda). I'm looking for documentation on the subject or for a step by step tutorial. Can anyone provide feedback on this? Thank you -
Django and Vue: I keep geetting "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" in my website
I'm doing this project using Vue and Django, but when I run my code, I keep getting this error "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yellow-jacket-with-no-zipper:1" I kept reloading and waited 30 minutes for this error to go away, but it keeps appearing. I don't know if there is a problem in my javascript, because I don't have any errors when I run the vue project. Here's my code I think has the problem. Back end: urls.py module in Products package urls.py module in product package: from django.urls import path, include from product import views urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('products/<slug:category_slug>/<slug:product_slug>', views.ProductDetail.as_view()), ] Front end: Product.vue script: <template> <div class="page-product"> <div class="columns is-multiline"> <div class="column is-9"> <figure class="image mb-6"> <img v-bind:src="product.get_image"> </figure> <h1 class="title">{{ product.name }}</h1> <p>{{ product.description }}</p> </div> <div class="column is-3"> <h2 class="subtitle">Information</h2> <p>Price: <strong>{{ product.price }}</strong></p> <div class="field has-addons mt-6"> <div class="control"> <input type="number" class="input" min="1" v-model="quantity"> </div> <div class="control"> <a class="button is-dark">Add to Carts</a> </div> </div> </div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'Product', data() { return { product: {}, quantity: 1 } }, mounted() { this.getProduct() }, methods: { getProduct() … -
How To maintain two sessions at a time in django using sso and custom login
User should have two logins: 1.Microsoft sso login using djano which will generate session id and set cookie 2.custom login to custom page after sso is generating again session id and set cookie. 3. we need to logout only from custom login when logout(request) called. but logging out from both custom login and sso login. Any help will appreciable. -
why does set_all() attribute is not taking values(message_set()
I am new with Django, in this view .i planned to show the name of the message sender in the template.so in the view i created a room message variable. in the template section i used a loop for alliterating the values. but the loop is not alliterating. view def room(request, pk): room = Room.objects.get(id=pk) **room_messages = room.message_set.all()** context = {'room': room, 'room_messages': room_messages} return render(request, 'room.html', context) models class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() update = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] template {% block content %} <h1>{{room.name}}</h1> <p>{{room.description}}</p> <div class="comment-wrapper"> <h3>Conversation</h3> <hr> **{%for message in room_messages%}** <div> <h1>{{message.user}}</h1> </div> {%endfor%} </div> {% endblock %} the loop is not alitrating, -
django-s3direct multibytes uploading error
When uploading the multibyte file such as (テスト.jpg) with django-s3direct This error comes in browser console. Uncaught (in promise) TypeError: n.includes is not a function (s3direct.js:51) at m.warn (s3direct.js:51:2581) at S.y.error (s3direct.js:44:28150) If you don't use multibytes there is not error occurs. Is there a any setting I should do for S3 or django-s3direct ? -
Django: My attempt to update an instance instead creates a new instance
Description: I'm fairly certain I'm misunderstanding something obvious here, but I've stripped the code back to its basics and for whatever reason I can't find the problem. It actually worked in an earlier iteration (following the advice of other S/O posts), but evidently I broke something when editing my code at some point. Note: I've removed code that seems extraneous to this topic. Expected behaviour/s: If the user selects the "Edit" button on the index.html page they are taken to edit_booking.html where the CustomerForm is populated by the selected Customer instance. (This appears to work as expected. I think it's possible that there's a fault with my mental model, but I'm not sure what.) If the user selects the "Save" button on the edit_booking.html page, the selected Customer instance is updated/replaced by whatever the user has entered (or was already in) the form. (This does not work as expected. Instead, when the user selects the "Save" button, a new Customer instance is created from the contents of the edit_booking.html form.) What I've tried: I replaced the passing of the customer variable in views.edit_customer (and edit_customer.html) with just the customer_id instead (i.e., "customer_id": customer_id), but that didn't help. I mean I … -
Building Web Applications with Django
File “C:\Users\ASUS\vidly\movies\admin.py”, line 2, in from .models import Genre, Movie ImportError: cannot import name 'Movie' from 'movies.models' (C:\Users\ASUS\vidly\movies\models.py) How to solve this problem? [admin.py] : https://i.stack.imgur.com/tHm6q.png -
from .forms import usernameForm,DateForm,UsernameAndDateForm, DateForm_2 ImportError: attempted relative import with no known parent package
This problem arose when I tried to run the views.py file of the Django template.When I run python manage.py runserver on terminal. I got from .forms import usernameForm,DateForm,UsernameAndDateForm, DateForm_2 ImportError: attempted relative import with no known parent package image This is a face_recognition attendance system. -
Table not getting created from model in django rest api python
I have created a django project with 3 tables. I was able to create the connection to mysql and migrate succefully two of them. But, there is one table which is not getting created. I have tried deleting the migration folder and run the migration again using the makemigration command. Can you please help? This is the exception which I get. Exception Type: ProgrammingError at /admin/mitr_api/invitedetails/add/ Exception Value: (1146, "Table 'mitr.mitr_api_invitedetails' doesn't exist") This is the model which I created- class InviteDetails(models.Model): inviter_id = models.IntegerField( primary_key = True,) invitee_phonenumber = models.CharField(max_length = 10) invitecode = models.CharField(max_length = 5) invitee_name = models.CharField(max_length = 45) isd_code = models.CharField(max_length = 3) I have registered this model in admin.py and maintained other necessary connections and settings. from django.contrib import admin from .models import InviteDetails # Register your models here. admin.site.register(InviteDetails) -
How to filter queryset by the most recent datetime field using Django?
I have the following model which I want to perform a query to extract rows with the most recent created_at date given a list of names ordered by the most recent effective date: class Foo(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) effective_date = models.DateField() So for example the data can be the following: name | created_at | effective_date ================================== testA | 2022-01-01 | 2021-01-01 ---------------------------------- testA | 2022-02-01 | 2021-01-01 <--- pick this row since it has the most recent created_at ---------------------------------- testA | 2022-01-01 | 2021-02-01 ---------------------------------- testA | 2022-02-01 | 2021-02-01 <--- pick this row since it has the most recent created_at ---------------------------------- testB | 2022-01-01 | 2021-02-01 ---------------------------------- testB | 2022-02-01 | 2021-02-01 <--- pick this row since it has the most recent created_at ---------------------------------- Then given names = ['testA', 'testB'] I want to obtain the following results: name | created_at | effective_date ================================== testA | 2022-02-01 | 2021-02-01 ---------------------------------- testA | 2022-02-01 | 2021-01-01 ---------------------------------- testB | 2022-02-01 | 2021-02-01 ---------------------------------- Right now, I have tried the following queries: names = ['testA', 'testB'] # This doesn't isolate the rows with the most recent created_by date queryA = Foo.objects.filter(name__in=names).order_by("-effective_date") # This returns a single Foo object rather … -
(Django jwt) ValueError: not enough values to unpack (expected 2, got 1)
I have created a UserViewSetin my Django project to get user data via a get request, the viewset should be expecting a bearer type access token in the body. However, when I make the request through postman, it return a error: ValueError: not enough values to unpack (expected 2, got 1) My UserViewSet looks like this: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = (IsAuthenticated,) def get_object(self): lookup_field_value = self.kwargs[self.lookup_field] obj = Account.objects.get(lookup_field_value) self.check_object_permissions(self.request, obj) return obj Now I know it is also expecting me to include a lookup field in the request, but I have not idea how and where to put it. My lookup field should be the id by default, so I just make the request by this endpoint: http://127.0.0.1:8000/account/auth/user/2/ in order to get user data of user id=2. Anybody has an idea why I am getting this error, and how to solve it? -
How to auto generate a field value with the input field value in Django Model?
I want to make an API that automatically generate a value to a field when POST to this api with Django. def gen_code(k): return # a value class generate_code(models.Model): code = models.CharField(max_length=100, default="", unique=True) generated_code = gen_code(code value) #generated with code Something like the code above. How can I make that -
How to resolve MultiValueDictKeyError in django
The purpose of the program is to give a user access to edit certain details in their database. This is the views.py file def edit_profile(request): user_info = UserInfo.objects.all() if request.method == 'POST': username_edit = request.POST['edit_username'] firstname_edit = request.POST['edit_firstname'] lastname_edit = request.POST['edit_lastname'] email_edit = request.POST['edit_email'] phone_number_edit = request.POST['edit_phone'] if len(phone_number_edit) == 11: if int(phone_number_edit) / 1 == 0: if User.objects.filter(username=username_edit).exists(): messages.info(request, 'Username already exists!') return redirect('edit') elif User.objects.filter(email=email_edit).exists(): messages.info(request, 'Email has already been used') return redirect('edit') else: new_user_info = User.objects.all() new_user_info.username = username_edit new_user_info.first_name = firstname_edit new_user_info.last_name = lastname_edit new_user_info.email = email_edit new_user_info.save() new_user_info_phone = user_info new_user_info_phone.phone_number = phone_number_edit new_user_info_phone.save() return redirect('profile') else: messages.info(request, 'Phone number not valid') return redirect('edit') else: messages.info(request, 'Phone number not valid') return redirect('edit') else: return render(request, 'profile_edit.html', {'user_info': user_info}) this is the html.file <form action="", method="post"> {% csrf_token %} {% for message in messages %} <p style="color: red;">{{message}}</p> {% endfor %} <h3>Click done after editing</h3> <p>Username: <input type="text", name="edit_username", value=" {{user.username}}"></p> <p>First Name: <input type="text", name="edit_firstname", value=" {{user.first_name}}"></p> <p>Last Name: <input type="text", name="edit_lastname", value=" {{user.last_name}}"></p> <p>Email: <input type="email", name="edit_email", value="{{user.email}}"></p> {% for user in user_info %} <p>Phone Number: <input type="text", value="{{user.phone_number}}", name="edit_phone"></p> {% endfor %} <input type="submit", value="Done"> </form> this is the urls.py file from django.urls … -
Testing views Error, where is the error please?
class Edit_RecipeViews(TestCase): """Unit Test Edit Recipe Page View""" def test_edit_recipe_page(self): response = self.client.get(f'/edit_recipe/{post.slug}') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'edit_recipe.html') -
create a superuser and adminuser using django restframework
i have a custom user model and i want to create a superuser from a view right, am currently using django restframework, below is my custom model and serializer with the views. model.py class CompanyUserManager(UserManager): def _create_user(self, username, email, password, **extra_fields): """ Create and save a user with the given username, email and passsword """ if not username: raise ValueError('The given username must be set') if not email: raise ValueError('The email must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username: str, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) def create_admin_user(self, username: str, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_admin', True) # if extra_fields.get('is_staff') is not True: # raise ValueError('Super user must have is_staff=True') # if extra_fields.get('is_admin') is not True: # raise ValueError('Super user must have is_admin=True') # if extra_fields.get('is_superuser') is True: # raise ValueError('Superuser must have is_superuser=False') return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username: str, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_admin', True) if extra_fields.get('is_staff') is not True: raise ValueError('Super user must have is_staff=True') if extra_fields.get('is_admin') is not True: raise ValueError('Super user must have is_admin=True') if extra_fields.get('is_superuser') is not True: … -
Can't print JSON for my GET request, Django
I have been trying to figure out Django and am confused with the views. I am not sure what I am doing wrong. The goal is to call Resource, a model, from the stored database and print serialized JSON on the webpage. @api_view(['GET']) def getResources(request): return Response(ResourceSerializer(Resource.objects.all()).data) Can you help me with this? -
MyPy, VSCode, Django, ModuleNotFound
I am working on a Django project. I want to be able to check the types in my project. For this purpose, I have installed django-stubs and mypy. Moreover, I want it to work with the VSCode extension. It saves time because I don't have to run mypy in terminal every time I have to check everything. However, MyPy simply crashes because it cannot find Django settings for some reason..... I have already tried moving around the mypy.ini file. It does not help. BTW, it works if I run MyPy in terminal. Error: ModuleNotFoundError: No module named 'my_project.settings' mypy.ini: [mypy] plugins = mypy_django_plugin.main, mypy_drf_plugin.main [mypy.plugins.django-stubs] django_settings_module = "my_project.settings" settings.json: { "python.linting.mypyEnabled": true, "python.linting.enabled": true, "mypy.runUsingActiveInterpreter": true, "mypy.configFile":"my_project/mypy.ini", "mypy.targets":[ "." ] } wsgi.py: """ WSGI config for web_app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_project.settings') application = get_wsgi_application() myvenv | | .vscode |---settings.json | my_project |----mypy.ini |----my_project | | | |--settings.py | | -
Django Rendering Form in HTML Issue
Hello so I'm attempting to render a form, in html and have tried the normal {{ form }}. However when I go to the site set up by: python manage.py runserver. I get the following where the form should go (highlighted section on screen-capture) webpage This is the code for the form in question. forms.py from django import forms from django.forms import ChoiceField, ModelForm, RadioSelect from .models import command_node from .models import beacon class Command_Form(ModelForm): class Meta: model = command_node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=beacon.objects.all(), widget=forms.Select( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=[ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ]) This is the html in question. I've removed non-relevant segments home.html </br> </br> <form action="" method=POST> {% csrf_token %} {{ form }} <button type="Submit" class="btn btn-secondary btn-sm">Submit</button> </form> </body> </html> Lastly I've included the views as I suspect it might have something to do with it but I'm not certain. I'm trying to make it so that when the form is submitted the page is reloaded. Views.py from … -
Javascript, resize an image and convert to base64
I want to resize image and convert it to base64 before sending via network. It takes so long if it is 10MB or more image so I need first to resize it on front, convert it and then send it to the server html: <div class="file__item ui-state-default current_ad current_ad_files"> <img width="88px" height="88px" src="{{ photo.image.url }}" alt=""> <input type="hidden" class="photo-base64" id="{{ photo.pk }}" value="{{ photo.get_base64_image }}" multiple> <a href="" class="file__delete" atr='sorok'></a> </div> js: function convertToBase64(file, inputId) { var reader = new FileReader(); reader.onload = function () { let base64String = reader.result.replace("data:", "") .replace(/^.+,/, ""); $(`#${inputId}`).val(base64String) } reader.readAsDataURL(file); } function getUploadedFileNode(file) { let randomId = getRandomID(); return { inputId: randomId, node: ` <div class="file__item ui-state-default file__item--sortable ui-sortable-handle"> <img width="88px" height="88px" src="${URL.createObjectURL(file)}" alt=""> <input type="hidden" class="photo-base64" id="${randomId}" value="" multiple> <a href="" class="file__delete"></a> </div> ` } } let addedFileNode = getUploadedFileNode(lastFile) // lastFile is an regular image from looping over multiupload convertToBase64(lastFile, addedFileNode.inputId) This issue is very urgent for me now, please help! Thanks a lot in advance! PS: front is written in pure javascript and jquery. -
Django subclass ContentTypeManager
I'm designing an app which has 3 models: Musician Album Song I'd like to code a custom ContentTypeManager method that I can call in views.py which allows me to access all three models with one method. e.g. music_data = ContentType.objects.get_music(musician='Beatles') This method would return a dictionary which I can pass to a template. The dictionary would look similar to the below: music_data = {'Abbey Road': ['Song 1', 'Song 2', 'Song 3', etc. ]} I have no issue writing the method that returns the music_data dictionary. However, I am not sure how to subclass ContentTypeManager to create a custom ContentTypeManager method. I tried creating a creating a model which inherits from ContentType and subclassing the manager in a similar way as a custom model manager would typically be created but this created a new database table and didn't reference the existing ContentType table. The code I tried is as follows: #models.py from django.contrib.contenttypes.models import ContentType from .managers import CustomContentTypeManager class CustomContentType(ContentType): objects = CustomContentTypeManager() #managers.py from django.contrib.contenttypes.models import ContentTypeManager class CustomContentTypeManager(ContentTypeManager): def = get_music(self): # Insert code to query models via ContentType model Any help would be greatly appreciated. -
Reverse for 'user-profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<pk>[^/]+)/\\Z']
I am a beginner in learning code and am working on making a simple django site where users can click on other users to view their comments (by clicking their profile). However django keeps throwing this error when I run the site. My urls.py from django.urls import path from . import views urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('', views.home, name="home"), path('room/<str:pk>/', views.room, name="room"), path('profile/<str:pk>/', views.userProfile, name='user-profile'), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>', views.updateRoom, name="update-room"), path('delete-room/<str:pk>', views.deleteRoom, name="delete-room"), path('delete-message/<str:pk>', views.deleteMessage, name="delete-message"), my template page 1(profile.html) {% extends 'main.html' %} {% block content %} <h1>{{user.username}}</h1> {% endblock content %} other template(feed component on my home page) <div> {% for room in rooms %} <div> {% if request.user == room.host%} <a href="{% url 'update-room' room.id%}">Edit</a> <a href="{% url 'delete-room' room.id %}">Delete</a> {% endif %} <a href="{% url 'user-profile' room.host.id %}">@{{room.host.username}}</a> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> my views.py def userProfile(request, pk): user = User.objects.get(id=pk) context = {'user': user} return render(request, 'base/profile.html', context) -
Django - Unable to pass page title as url parameter in template
I have a BIG problem. I need to pass article title to URL in the template This is my urls.py urlpatterns = [ *** re_path(r'^view/(?P<id>\w+)/(?P<title>\w+)/$', views.view, name='view'), *** ] view.py def view(request, id, title): return render(request, 'view.html', {'id' : id, 'title' : title}) At first I tried <a href="{% url 'view' id=3685 title='What a terrible weather' %}">What a terrible weather</a> And I got that error message: NoReverseMatch at /view/7/6999/ Reverse for 'view' with keyword arguments '{'id': 3685, 'title': 'What a terrible weather'}' not found. 1 pattern(s) tried: ['view/(?P<id>\\w+)/(?P<title>\\w+)/$'] *** Error during template rendering In template D:\Django\gtunews\templates\view.html, error at line 8 Reverse for 'view' with keyword arguments '{'id': 3685, 'title': 'What a terrible weather'}' not found. 1 pattern(s) tried: ['view/(?P<id>\\w+)/(?P<title>\\w+)/$'] *** Then I tried {% with thevarable= "What a terrible weather" %} <a href="{% url 'view' id=3685 title=thevarable %}">What a terrible weather</a> {% endwith %} The result: TemplateSyntaxError at /view/7/6999/ 'with' expected at least one variable assignment *** Error during template rendering In template D:\Django\gtunews\templates\view.html, error at line 8 'with' expected at least one variable assignment *** Also I tried {% with my_var = 'What a terrible weather'.replace(' ','_') %} <div>Hello, {{my_var}}!</div> {% endwith %} As a result I go the …