Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Same coda as in tutorial and getting error
I'm learning Django with Tim. He have this code: Code And I have such a code: def create(response): if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): name_of_form = form.cleaned_data['name'] lista = ToDoList(name=name_of_form) lista.save() else: formularz = CreateNewList() return render(response, 'main/forms.html', {'form': formularz}) It's simply the same code but still I get an error: "local variable 'formularz' referenced before assignment" What can I do with it other that asagning None to a form like this: def create(response): formularz = None if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): name_of_form = form.cleaned_data['name'] lista = ToDoList(name=name_of_form) lista.save() else: formularz = CreateNewList() return render(response, 'main/forms.html', {'form': formularz}) It works with an error, but after sending a form, the page is rendering blank like This Not like for Tim, where after sending, he still have a form on a page: pic -
Django ERR_insufficient Resources
I have a Django app and for some reason I see this error when loading a page - see picture. It seems like there are a lot of icons being loaded but as far as I know I am not loading much in my template. Also, the page is SO slow to load. A screen-recording here: https://www.loom.com/share/f458664230f14bc9975852647812ef82 Here below the template {% extends 'action/project/project_base.html' %} {% load static %} {% load crew.tables %} {% load crew.availability %} {% load action_extras %} {% block p_header_cta %} <a href="{% url 'action:NewPosition' project.id %}" class="btn-red-border rounded-2"> New Position </a> {% endblock p_header_cta %} {% block project_content %} <!-- Top List --> <div class="row justify-content-between mt-5"> <div class="col"> <ul class="nav nav-pills minimalist mb-3" id="pills-tab" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" data-role="tab" data-tab-selector=".tab-dates" type="button" role="tab" aria-controls="tab-dates" aria-selected="true">Dates</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" data-role="tab" data-tab-selector=".tab-notes" type="button" role="tab" aria-controls="tab-notes" aria-selected="false">Notes</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" data-role="tab" data-tab-selector=".tab-files" type="button" role="tab" aria-controls="tab-files" aria-selected="false">Files</button> </li> </ul> </div> </div> <!-- Top List --> <!-- Data container --> <div class="flex-grow-1 d-flex flex-row w-100 card bg-white border-1 rounded-2"> <!-- Left data container --> <div class="crew-title-column d-flex flex-column border-end ps-3"> <!-- Positions/status header --> <div class="crew-header d-flex flex-row align-items-center"> <div class="d-flex … -
Authentication with three fields in django-rest-framework-simple-jwt
I am working on custom authentication in DRF. User should send 3 fields (phone, email, password). I was following this answer Adding custom user authentication to django-rest-framework-simple-jwt (I was overriding TokenObtainPairSerializer and TokenObtainPairView) I was using this source code https://github.com/jazzband/djangorestframework-simplejwt/blob/master/rest_framework_simplejwt/serializers.py Problem: for the request below I received an empty response {} { "email": "admin1@admin2.ru", "password": "admin123456", "phone_number": "123132" } My code: views.py class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer serializers.py class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): username_field = CustomUser.USERNAME_FIELD def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() self.fields['password'] = PasswordField() self.fields['phone_number'] = serializers.CharField() # authentication requires 3 fields def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], 'password': attrs['password'], 'phone_number': attrs['phone_number'] } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass self.user = authenticate(**authenticate_kwargs) if not api_settings.USER_AUTHENTICATION_RULE(self.user): raise exceptions.AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) return {} -
Django rest framework + Scrapy [twisted.internet.error.ReactorNotRestartable]. (Flutter + Dart)
I am working on a project that mixes a Django API with Scrapy, the idea is to run the API from my cell phone, said API will run the spider and then return all the information that I will get on my cell phone. When I do the search for the first time on the cellphone, everything works perfectly, but when I try to do another search, I get "twisted.internet.error.ReactorNotRestartable" Here's my API class Prueba(APIView): def post(self, request): dato = request.data['dato'] if dato: imprimir = self.execute(dato) res = json.dumps([o.dump() for o in imprimir], indent=3) return HttpResponse(res, content_type='application/json', status = status.HTTP_200_OK) else: return HttpResponse("NO", content_type='application/json') def execute(self, peticion): url = ['https://listado.mercadolibre.com.co/'+peticion] url2 = ['https://www.olx.com.co/items/q-'+peticion] process = CrawlerProcess({'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'}) process.crawl(ProductoSpider, start_urls=url) process.crawl(ProductoSpiderDos, start_urls=url2) process.start() return outputResponse #global variable in my spider Here's one of my spiders, I know it's a bit weird, but it's because I've been testing a few things. class ProductoSpiderDos(CrawlSpider): name = 'olx' item_count = 0 allowed_domain = ['www.olx.com.co'] def __init__(self, **kwargs): super().__init__(**kwargs) #//button[@data-aut-id="btnLoadMore"] #//div[@class="JbJAl"] rules = { Rule(LinkExtractor(allow = (), restrict_xpaths = ('//button[@data-aut-id="btnLoadMore"]'))), Rule(LinkExtractor(allow = (), restrict_xpaths = ('//li[@data-aut-id="itemBox"]/a')), callback = "parse_item", follow = False), } def parse_item(self, response): global outputResponse lista … -
How to add Wagtail blog categories as links in header and footer
I am building simple blog with posts and posts categories. I would like to add links to posts by category to header and footer, so they appear on every page, to just home page (as routable pages). How do I go about it? -
DRF How to select specific fields only in a nested serializer?
I have a serializer class CategoryListSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["id", "name", "name_en", "about", "parent",] It is used in two locations: All Categories API: Used to view rich details about the categories. All Posts API: Used to know the name of the category only. In my Posts Serializer, I used: class PostListSerializer(serializers.ModelSerializer): categories = CategoryListSerializer(many=True, ) class Meta: model = Post fields = ["id", "title", "description", "publish_date", "thumbnail", "owner", "categories", ] And in my Post ViewSet: class PostViewSet(ReadOnlyModelViewSet): queryset = Post.objects.all().filter(is_published=True) serializer_class = PostListSerializer This returns All posts with All Categories Details mentioned in CategoryListSerializer, as it should be. Question: I want the PostListSerializer to return only the "name" field from the related Categories, without having to define another CategorySimpleSerializer that selects "name" field only. (I still need the CategoryListSerializer fields in another API) Is it possible to do that? Note: This is only an example, I'll have more usecases for this and want to know ahead if i'll have to create many custom "to-be-nested" Serialzers, to avoid exposing some unnecessary data to some of the APIs. It seemed like lots of redundant update work if a model or API needs change later. -
django: how to make a search bar?
I am new to django. I have done an online order management page using django, where registered users can view their own list of orders. Now I want to add a search bar for users to easily search for any orders. I noticed that in django admin user page, there is a search bar function. and This is exactly what I want. Can some one help to advise how to do the same search bar, incl. html and view.py, plus javascripts if needed. many thanks -
How to set up nested serializers without error
I am new to DRF and have been trying for the past weeks to set up a nested serializer structure. Essentially, I have a User model, and a Social Media model that has User as a Foreign Key: models.py class CustomUser(AbstractUser): id = models.UUIDField(default = uuid.uuid4, editable = False, primary_key = True) country = CountryField(blank_label='(select country)') updated_at = models.DateTimeField(auto_now = True, editable = False, null = True) gender = models.CharField(max_length=50, choices=Gender.choices, default = Gender.OTHERS) avatar = models.ImageField(upload_to = "avatar_pics", default = "avatar_pics/default.jpg", null = True) class UserSocialMediaAccounts(models.Model): id = models.UUIDField(default = uuid.uuid4, editable = False, primary_key = True) user = models.ForeignKey(CustomUser, on_delete = models.CASCADE) social_media = models.CharField(max_length=50, choices=SocialAccounts.choices) social_media_url = models.URLField(null = False) So far, my serializers for displaying the user and the associated social media accounts are: serializers.py class CustomUserSocialMediaSerializer(serializers.ModelSerializer): class Meta: model = UserSocialMediaAccounts fields = ('user','social_media', 'social_media_url') class CustomUserDetailSerializerSM(CountryFieldMixin,serializers.ModelSerializer): social_media = CustomUserSocialMediaSerializer(many = True) class Meta: model = CustomUser fields = ('email','first_name','last_name','country','gender','avatar','social_media') My view that I want to use to display the queried user's associated social media accounts: views.py class CustomUserDetailSocialMediaView(generics.ListCreateAPIView): serializer_class = CustomUserDetailSerializerSM permission_classes = (IsAuthorOrReadOnly,) def get_queryset(self): username = self.kwargs['username'] return UserSocialMediaAccounts.objects.filter(user__username = username) urls.py urlpatterns = [ path('detail/<str:username>/socialaccounts/',CustomUserDetailSocialMediaView.as_view()), ] However, if I tried to … -
Django Python Invalid Syntax When Deployed on Digitalocean
I have a Django project on local machine running on Python 3.10.3 Now I deployed it to a DigitalOcean machine running Ubuntu 20 and Python 3.8.10 When I run the project on local machine there is no issue, but when I do run it on the DO instance, it gives me a syntax error. Here is the code where it gives me the error: def get_day_by_date(date): weekday = date.weekday() match weekday: case 0: return "Lundi" case 1: return "Mardi" case 2: return "Mercredi" case 3: return "Jeudi" ....... This is the error I get in DO: [![enter image description here][1]][1] Is it a problem of the Python version? PS: I have already done pip freeze and installed the exact same requirements on both machines. [1]: https://i.stack.imgur.com/SM8Pt.png -
Response.__init__() takes 1 positional argument but 2 were given Django + Vue3
I build a project with django and vue3 I have problem with creating object. Code below throw a error: TypeError: Response.init() takes 1 positional argument but 2 were given this is my view.py class AddProjectView(viewsets.ModelViewSet): queryset = PassProjects.objects.all() serializer_class = AddProjectSerializer def create(self, request): data = request.data title = data.get('title') body = data.get('body') PassProjects.objects.create(who_create=request.user, title=title, body=body) return Response({'message': ' Project created'}) this is my urls.py router = DefaultRouter() ... router.register('addproject', AddProjectView, basename='addproject') urlpatterns = [ path('', include(router.urls)), ] serializer.py class AddProjectSerializer(serializers.ModelSerializer): class Meta: model = PassProjects fields = '__all__' what i need to change to fix this error? Thank's -
Django Annotate with one model and include "annotated" records in queryset
I am fairly new to Django and have figured out the "basic" annotate function, but I would like to include the records from the annotated values. For example, qs = People.objects.values('status').annotate(total=Count('id'),totalScore=Sum('score'),averageAge=Avg('age')) I would like to include the summarized records in the result, in this case the individual people, like so... [ {'status': 'One', 'total': 2, 'totalScore': 150, 'averageAge': 36, 'people': [ { 'id': 1, 'status': 'One', 'name': 'Jim', 'score': 80, 'age': 40 }, { 'id': 5, 'status': 'One', 'name': 'Jill', 'score': 70, 'age': 32 } ]}, {'status': 'Two', 'total': 1, 'totalScore': 85, 'averageAge': 42, 'people': [ { 'id': 3, 'status': 'Two', 'name': 'Jack', 'score': 85, 'age': 42 } ] },... Thanks for any help. -
How do you add pK's in a django url
I am makeing a blog and I want to go to a specific blog post by clicking on a button. I know I need to use a pk in the URL but I do not know the syntax or how to implement it any help would be appreciated. -
How to Merge values of 2 variable together Django
I have 2 Variables for which the values keep changing. I want to generate barcode for those 2 values side by side. For example {% assign boxes = 2 %} {% for x in (1..boxes) %} {% for sale in picklist.sales -%} {% barcode value: sale.marketplace_id %} {% endfor -%} {% endfor -%} this currently gets id and prints it as barcode. but i want to print id and x together in 1 barcode eg id=13423 boxes=2 so first barcode will be 13423 1 and next will be 13423 2 Please help... -
Access Model Method for Multiple Objects in Django
Let's say I have created a model in Django that looks like this: class Book(models.Model): author = models.CharField(max_length=64) ... (other attributes) def author_pretty(self): return "[··" + self.author + "··]" I need to get from all objects in DB the method author_pretty, as of now I'm doing this: authors = Book.objects.values_list('author', flat=True) authors_pretty = ["[·" + author + "·]" for author in authors] # or books = Book.objects.all() authors_pretty = [book.author_pretty() for book in books] Is there any way of doing this in a single call? Django would still have to make a query to DB and the call the method, but maybe there is a cleaner solution that I'm missing. -
How to consume using RabbitMq Consumer in a synchronous way in Python(Django)
I have a system that publishes order data into a Rabbitmq queue. I want to consume that order data into another system in a synchronous manner. For e.g. if the queue contains 100 orders data at a time then I want to collect those 100 orders one by one (collect 1st order data and process that data then collect 2nd orders data and process that one also and so on....). What can be an ideal approach for that using Python(Django)? -
Django - Filter objects from child class with parent class primary key passed in URL
I'm a newbie in Django and I'm trying to pass all the Posts made for each vehicle in a vehicle detail html page. My vehicles/models.py: *vehicles/models.py* class Vehicle(models.Model): TESLA = 'TESLA' MAZDA = 'MAZDA' VOLVO = 'VOLVO' VEHICLE_CHOICES = ( (TESLA, "Tesla"), (MAZDA, "Mazda"), (VOLVO, "Volvo"), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) model = models.CharField(max_length=9, choices=VEHICLE_CHOICES, default=TESLA) def __str__(self): return self.model class Meta: db_table = "vehicles" My Posts models.py: *blog/models.py* from django.db import models from django.contrib.auth.models import User class Post(models.Model): date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, default=None ) def get_absolute_url(self): return reverse('post-detail', kwargs ={'pk': self.pk} ) class Meta: db_table = "chargehistory" I am already passing in a html file all the Vehicles for each User and now i would like to get all the posts made for each User's vehicle. *vehicles/views.py* class UserVehicleListView(ListView): model = Vehicle template_name = 'vehicles/vehicles.html' # <app>/<model>_<viewtype>.html context_object_name = 'vehicles' def get_queryset(self): return Vehicle.objects.filter(owner_id= self.request.user.id) class UserVehicleDetailView(DetailView): model = Vehicle *vehicles/urls.py* urlpatterns = [ path('vehicles', UserVehicleListView.as_view(), name='vehicle-list'), path('vehicles/<int:pk>', UserVehicleDetailView.as_view() , name='vehicle-detail'), ] urlpatterns += staticfiles_urlpatterns() Since i'm passing the vehicle primary key in the path, is there any way for me to filter the posts based on that key and pass it … -
Unexpected Keyword argument using formset_factory
I'm working on a project in which a teacher can add marks to his students, I want to use formset_factory so the teacher can add many marks at the same time, but I want a teacher to see only his students, and not the students who are not in his class. I got it when using a single form, but when I try to use the formset_factory, I get this error: init() got an unexpected keyword argument 'request' This is my working code in views: class AddNotaBlock(FormView): template_name='notas/insertar_nota.html' form_class= NotaCreateFormTeacher success_url= reverse_lazy('home') def get_form_kwargs(self): """ Passes the request object to the form class. This is necessary to only display members that belong to a given user""" kwargs = super(AddNotaBlock, self).get_form_kwargs() kwargs['request'] = self.request return kwargs in forms: class NotaCreateFormTeacher(ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(NotaCreateFormTeacher, self).__init__(*args, **kwargs) usuario=self.request.user profe=Teacher_profile.objects.get(profesor=usuario) colegio=profe.colegio self.fields['Username'].queryset = Student_profile.objects.filter( colegio=colegio) class Meta: model = Nota fields = ('Username', 'nota', 'colegio') widgets= {'colegio':HiddenInput()} formset=formset_factory(NotaCreateFormTeacher, extra=2) when I use: form_class= NotaCreateFormTeacher Everything works (but only a form is displayed) If I use: form_class=formset I get the unexpected keyword argument error: init() got an unexpected keyword argument 'request' What I'm I doing wrong? Thanks for helping. -
How can I fix a 'ModuleNotFoundError' in django python?
I am trying to create a Django python API, and when I created the first app 'authentication' with 'python manage.py startapp authentication', I got the following error while running the server: generated error I did add the app name to the 'setting.py' file : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authentication.apps.AuthenticationConfig', 'orders.apps.OrdersConfig',] I am pretty sure that I need to specify the path, but I don't know how !!! Note that my folder is organized as follows, and the main project is named 'pizza': folder content Can anyone help me please ??? -
Django: is not a valid view function or pattern name when trying to add a url using url tag in django
i want to add a url to my project that would get the id of a video and append it to url like this http://127.0.0.1:8000/course/learn-angular/contents/?lecture=1 <a href="?lecture={{v.serial_number}}" instead of the regular django {% url '?lecture={{v.serial_number}}' %}. when i do this <a href="{% url '?lecture={{v.serial_number}}' %}"> that is when i get this error Reverse for '?lecture={{v.serial_number}}' not found. '?lecture={{v.serial_number}}' is not a valid view function or pattern name.. NOTE: when i add the url as ?lecture={{v.serial_number}} is show this error when i click on the url Page not found (404) Directory indexes are not allowed here and all these are happening i think becuase i have this line <base href="{% static '/' %}"> in my base.html where i am extending all my static files from. And if you asking why i have this line base href="{% static '/' %}">, it's becuase my static files are not loading up as usual, it keep showing a MIME type not supoorted error, refused to apply 127.0.0.1:8000/assets/css/style.css so the only way i could fix this was to add that line to my base.html. Back to the main question, what is the right way to write tihs url withot getting this error Page not found (404) … -
Django / Model with ManytoManyField gives en entry by default
Models.py class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) description = models.TextField(blank=True) fileGltf = models.FileField(null=TRUE, blank=False, upload_to="3dfiles/") record_date = models.DateTimeField('Scene date') manager = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) prev = models.ForeignKey( 'self', related_name='previous', blank=True, null=True, on_delete=models.SET_NULL) next = models.ManyToManyField( 'self', blank=True, ) Views.py (extract) if form.is_valid(): nextSceneSlug=form.cleaned_data.get('name') scenes=form.save(commit=False) scenes.manager = request.user scenes.record_date = now scenes.prev = ScenePrevious form.save() When I record a new entry with the models.py, there is a default value for this next field/ (World is the scene origine) But when I add it with the admin panel, there is not. How can I do it in my views.py so it leaves a blank field ? -
How can i display count of each column in django
Display I would like to count the number of students for each subjects but currently it only displays the number of students for one subject. it only counts the number of student for one subject but i would like to count the number of students in each subject views.py class SubjectView(TemplateView): template_name='subjects.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) username=self.request.user.id #filter subject taught by lecturer classdets=ClassDetail.objects.all().filter(teacher=username).values_list('subject_id') print(classdets) #filters all subjects from the class details subj=Subject.objects.filter(id__in=classdets) print(subj) #counts number of students subjID=Subject.objects.values('id') num_student=ClassDetail.objects.filter(id__in=subjID).count print(num_student) context['subjects'] = subj context['no_students'] = num_student return context template {% for subject in subjects %} <tbody class="list" style="text-transform: capitalize"> <tr> <th scope="row"> <div class="media align-items-center"> <a href="#" class="avatar rounded-circle mr-3"> {% if subject.thumbnail %} <img alt="Logo" src="{{subject.thumbnail.url}}" /> {% endif %} </a> <div class="media-body"> <span class="name mb-0 text-sm">{{subject}}</span> </div> </div> </th> <td class="budget">{{subject.code}}</td> <td> <div class="d-flex align-items-center"> <span class="completion mr-2">{{no_students}}</span> </div> </td> <td> {% comment %} <div class="d-flex align-items-center"> <span class="completion mr-2">{{attendace_code}}</span> </div> {% endcomment %} </td> </tr> </tbody> {% endfor %} {% endif %} -
server returns list of tuples to an ajax request but back in the html I need to work on it and html(data) doesn't give a proper structure
I manage to send the ajax request to the server, and the server replies with a list of tuples or it could be a dictionary too, but back in the html that sent the request, this list or dict gets sort of turned into a string and I can't iterate or work on it. This is because of the html(data), but I don't know any other variant other than text(data) but that doesn't solve the problem. So, once I have sent that list or dict, how can I work on it (like doing iterations) I am using DJANGO. I simplify the code because this is what matters, suppose I already have a dictionary that I turn into a list: SERVER (VIEW FUNCTION) RETURNS: dictionary = { "key1": "value1", "key2": "value2" } lista = list(dictionary.items()) return HttpResponse(lista) Then back in the html code that sent the request, this results don't keep the nature of the list, but seems like a string HTML PAGE: ... .. datatype:'html' }).done(function(data) { $("#received_answer").html(data); }); // closing ajax group console.log(value); }); // closing the click function });// closing document ready </script> I get this: ('key1', 'value1')('key2', 'value2') -
Is it safe to put .env file on AWS elastic beanstalk
I am fairly new to web app development. I am developing a web app using react+django. I am hosting django on AWS elastic beanstalk. My question is: is it save to put .env(contains important secret keys) elastic beanstalk? Can people read or download it once they have my elastic beanstalk url? -
remote rejected main -> main (pre-receive hook declined) Heroku
I'm trying to deploy my Django app on Heroku and when I do the command "git push heroku main" it seems to load successfully but I get this error. $ git push heroku main Enumerating objects: 834, done. Counting objects: 100% (834/834), done. Delta compression using up to 4 threads Compressing objects: 100% (736/736), done. Writing objects: 100% (834/834), 12.68 MiB | 394.00 KiB/s, done. Total 834 (delta 479), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: decd3fcfff0786fdab8daa8569c30886446ee4aa remote: ! remote: ! We have detected that you have triggered a build from source code with version decd3fcfff0786fdab8daa8569c30886446ee4aa remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are … -
how to filter a model in a listview
I have a page that displays a list of interviewers and some important info about each user. One of the things that I want it to show is the number of users who have been interviewed by that specific interviewer. I wrote a view like this: class ManagerUsers(ListView): model = User template_name = 'reg/manager-users.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['scientific_interviewers'] = User.objects.filter(role='theory_interviewer').all() context['interviewed_number'] = len(ScientificInfo.objects.filter(user__role='applicant', is_approved=True, interviewer=?????)) the interviewer field should be equal to that object's user but I don't know what to do exactly. the output should be something like this: object 1 : user's name, user's other info, user's interviewed_number ....