Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it secure to log in a user without a password? [closed]
I am thinking of logging a user in to my Django website by verifying the email rather than them having to write a password. If this is not clear, this is what I'm thinking: User enters email User gets a email containing a code User enters code in website User is logged in Is this safe to do without hackers accessing the accounts of other users? -
How to remove django-celery-beat models from admin?
I'm trying to remove the default django_celery_ beat models from admin page. I tried to to use unregister method but it giving an error from django_celery_beat.models import ( IntervalSchedule, CrontabSchedule, SolarSchedule, ClockedSchedule, PeriodicTask, ) admin.site.unregister(SolarSchedule) admin.site.unregister(ClockedSchedule) admin.site.unregister(PeriodicTask) admin.site.unregister(IntervalSchedule) admin.site.unregister(CrontabSchedule) Error: raise NotRegistered('The model %s is not registered' % model.name) django.contrib.admin.sites.NotRegistered: The model SolarSchedule is not registered def INSTALLED_APPS(self): rv = [ 'django.contrib.admin', 'django.contrib.auth', ... 'django_celery_beat', ] How can I solve that? -
Representing django table in HTML display custom subset of columns
I want to display a table in django based on a model with lots of columns but only display columns based on a form selection by the user delivered as a get request. The view looks like this: from utils import potential_col_list def display_table(request): cols_to_display = [] model_filter = ModelFilter(request.GET) query_set = model_filter.qs.values(*potential_col_list) for key, value in request.GET.items(): if key in potential_col_list: cols_to_display.append(key) return render(request, 'project/display_table.html', {'queryset': query_set, 'cols_to_display': cols_to_display}) What I want to have displayed is the query set but only the columns that the user has specified in the get request used in the filter. The display_table.html template looks like this. <table> <thead> <tr> {% for col in cols_to_display %} <th> {{ col }} </th> {% endfor %} </tr> </thead> <tbody> {% for item in queryset %} <tr> {% for col in cols_to_display %} <td> {{ item.col }} </td> {% endfor %} </tr> {% endfor %} </tbody> </table> The table headings render correctly but none of the data from the queryset appears. When I try to display everything without the cols_to_display it renders fine. -
Adding data from a form written in vue.js to a Django model
I am building a (relatively simple) booking system for a website using Django. The frontend of the website is written in Vue.js in a single-page format. I need one form that user fills to reserve a given room at a given datetime. Initially, I wanted to create the form myself using Django ModelForms but found it might be hard for the front-end to style it later on. Hence, I'm considering letting the front-end create the form but the question is how do I get the data from that form and input it in my Django model so it appears in the SQLite database. The form should also communicate with my database so the user can book only available timeslots. I am quite new to all this and a bit confused on how to proceed. Any tips or guidance will be very much appreciated. For now I have Reservation model that should be fiiled with data when form is submitted: class Reservation(models.Model): room=models.ForeignKey(Room, on_delete=models.CASCADE) time_slot= models.ForeignKey(TimeSlot, on_delete=models.CASCADE) first_name=models.CharField(max_length=255) last_name=models.CharField(max_length=255) number_of_ppl=models.IntegerField() email= models.EmailField(max_length=255) phone_number=models.CharField(max_length=50) invoice=models.BooleanField(default=False) comments=models.CharField(max_length=255) time_slot references TimeSlot model which contains a datetime linked to a particular room. -
Find queryset where one field is greater than another one
I have model Shop, I want to get all shops which time_open(opening time) is more than time_closed(closing time). For example 23:00:00 is more than 07:00:00 (Shop_2(Night shift shop)). class Shop(models.Model): time_open = models.TimeField() time_closed = models.TimeField() for example i have two objects: shop_1 = { "time_open": "08:00:00", "time_closed": "22:00:00" } shop_2 = { "time_open": "23:00:00", "time_closed": "07:00:00" } My goal is to output queryset in which shop_2 would be. These timestamps in these objects only for visual example, i want to do it without putting any data in sql query. I want to achive this by comparing time_open and time_closed fields. I found similar question in pure SQL: Find rows where one field is greater than another one My goal is to do it with Django ORM. -
How to fiilter isnull false value in Django-filters?
I want to only filter category which has channels__livestream__isnull=False. The Queryset is working fine with this paremter but the Django-filters getting error TypeError: 'FilterSetMetaclass' object is not iterable. filters.py class CategoryFilterSet(django_filters.FilterSet): has_live_stream = django_filters.BooleanFilter( field_name='channels__livestream', lookup_expr='isnull', ) class Meta: model = YTCategory fields = ['has_live_stream'] views.py class CategoryList(generics.ListAPIView): authentication_classes = [] permission_classes = [] queryset = YTCategory.objects.active() pagination_class = Pagination serializer_class = CategorySerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = CategoryFilterSet search_fields = ['id', 'name'] -
when I want to put my django app to elastic beanstalk in aws it gives me this error and I do not know how to fix it
when I want to put my Django app to elastic beanstalk in AWS it gives me this error and I do not know how to fix it -
NoReverseMatch at / - not understanding reason
I am trying to create a 'edit settings/ view profile page' drop down item in my navbar. The functionality was working prior to being called from the drop down which now throws the NoReverseMatch error as shown below: Reverse for 'show_profile_page' with arguments '('',)' not found. 1 pattern(s) tried: ['subs/(?P[0-9]+)/profile/\Z'] I am struggling to understand why this error is occuring when I am calling this url in other templates with no issues, but now that I tried putting this in a dropdown, I am getting this. Should I be doing a reverse call in the views.py? Would appreciate any pointers... **urls.py ** (subs app) from django.urls import path from .views import UserRegisterView, UserEditView, PasswordsChangeView, ShowProfilePageView, EditProfilePageView #from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register'), path('edit_profile/', UserEditView.as_view(), name='edit_profile'), #path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change-password.html')), path('password/', PasswordsChangeView.as_view(template_name='registration/change-password.html')), path('password_success', views.password_success, name="password_success"), path('<int:pk>/profile/', ShowProfilePageView.as_view(), name="show_profile_page"), path('<int:pk>/edit_profile_page/', EditProfilePageView.as_view(), name="edit_profile_page") ] views.py (subs app) from django.shortcuts import render, get_object_or_404 from django.views import generic from django.views.generic import DetailView from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm from django.urls import reverse_lazy from .forms import SignUpForms, EditProfileForm, PasswordUpdateForm from django.contrib.auth.views import PasswordChangeView from nooz2.models import Profile # Create your views here. class UserRegisterView(generic.CreateView): form_class = SignUpForms template_name … -
How to override the default formfield for a read only foreign keys field in Django ModelAdmin?
I am overriding the default formfield of foreign keys on ModelAdmins as described here. However, I am not overriding it to return a subset, but instead to defer fields in order to optimize the performance. For example: class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "car": kwargs["queryset"] = Car.objects.only("name") return super().formfield_for_foreignkey(db_field, request, **kwargs) It works for most of my use cases, but the problem occurres when the foreign key is set as a read only field. While debugging, I noticed that when it is set as read only, the field is never passed through formfield_for_foreignkey method and the query retrieving the foreign key selects all fields instead of only the necessary ones. In my case, some of the fields are too big causing an unecessary terrible performance. I also tried the second method described in the docs, using ModelForm.__init__(), but it is not really useful for my use case. -
WORKON is not recognized as the name of a cmdlet
PS C:\Users\HP\travelproject> workon myproject workon : The term 'workon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + workon myproject + ~~~~~~ + CategoryInfo : ObjectNotFound: (workon:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException your text Already installed virtual enivronment in cmd . -
How to change model attribute in template django?
There are model: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hired_at = models.DateField(auto_now=True) salary = models.DecimalField(max_digits = 9, decimal_places= 2) boss = models.ForeignKey('self', null=True,blank=True, on_delete=models.CASCADE) has_boss = models.BooleanField(null=True) def __str__(self): return f'<{self.pk}> {self.name} - {self.position}' And there are template for nested bosses: {%if employee.has_boss %} <div class="nested_leaf" <ul> {% include "tree_view_template.html" with employee=employee.boss employee.has_visited = True %} </ul> </div> {% endif %} <div class="leaf"> {% if not employee.has_visited %} <li> <{{ employee.id }}>{{ employee.name }} - {{employee.position}} </li> {% endif %} </div> Can i change attribute in django template? In this configuration i have an error with employee.has_visited=True -
django foreignkey and create index
Im currently working on a DRF api, and need to remove ForeignKey from model in models Note and Comment. I was told i need to replace the FK with an index in that column instead. Ive looked into the relationship and can't think of a way to maintain the many to one. Im working with a Postgresql db and Note as the parent model and comment as the child. My question- Is there an altenative way of making this happen(removeing the FK on both models and still maintaining the ManyToOne? and how would i replace the FK column with an index?) thank you for any possible help. Models.py class Note(models.Model): creator = models.CharField(auth.models.User, on_delete = models.CASCADE) content = models.TextField(max_length= 200) def __str__(self): return self.content class Comment(models.Model): content = models.TextField(max_length= 200) creator = models.ForeignKey( auth.models.User, related_name="comments", on_delete=models.CASCADE note = models.ForeignKey("Note", related_name="comments", on_delete=models.CASCADE) serializer.py class CommentSerializer(serializers.ModelSerializer): creator = serializers.ReadOnlyField(source="creator.username") class Meta: model = Comment fields = ["uuid", "content", "creator", "notes"] class NoteSerializer(serializers.ModelSerializer): creator = serializers.ReadOnlyField(source="creator.username") comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Note fields = ["type", "content", "creator", "comments"] -
Why django filter is not working for not case sensitive search
I am trying to fetch the data from django models, where as TaskBlockers.objects.filter(task__project=1,task__team='Backend') gives queryset with 3 objects TaskBlockers.objects.filter(task__project=1,task__team='backend') gives empty queryset. it was supposed to return same for both the queries isn't it? if now why is this happening and how can I rectify it for both type of input. here are my models. class TaskBlockers(models.Model): task = models.ForeignKey(ProjectTask,on_delete=models.SET_NULL,null=True,related_name='task_id_related') blocker = models.CharField(max_length=100,null=False) class ProjectTask(models.Model): project = models.ForeignKey(Projects,on_delete=models.SET_NULL,null=True) team = models.CharField(max_length=10) task_title = models.CharField(max_length=200,null=False) task_desc = models.TextField(blank=True) -
How to give the data to serializer with JSONField
I have model and serializer with JSONField class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) detail = models.JSONField(default=dict) def __str__(self): return self.user.username class ProfileSerializer(ModelSerializer): class Meta: model = m.Profile fields = '__all__' Then,I want to set the data to serializer class, However some how serializer.is_valid() faild. I have tested two pettern data1 data2 temp_data = {"data":"test"} data1 = {"detail":temp_data} # test_data1 data2 = {"detail":json.dumps(temp_data)} # test_data2 print(data1) # {'detail': {'data': 'test'}} print(data2) # {'detail': '{"data": "test"}'} instance = self.get_object() serializer = self.get_serializer(instance,data = data1) # or data2 if serializer.is_valid(): # serializer else: print("is_valid failed") What data should I give to this serializer? And is there any method to debug is_valid()? -
How to migrate a Django app with postgres database
I have just inherrited a jDango app with .tar.gz compression extention and a .sql file which is a postgreSQL database dump. My mission which I did not choose to accept is to somehow find its way onto AWS. I'm not familier with Django. I believe the app was built with the Ubuntu OS. I thought that maybe the best thing would be to get postgreSQL and Django working on my local machine. I have all working in vanilla on Windows, and Ubuntu (virtual box) and have set up Amazon Lightsail with a postgreSQL database.. I'm a bit stuck as to what to do next to migrate the app. Would it all be CLI/Cmd Prompt/Terminal or is there a procedure I should be using. I'm guessing it's not as simple as importing the database and then copying files over and replacing existing vanilla Django ones? Any pointers would be of great help. Thanks. -
How can i use django_channels and django_hosts libraries together?
I have added the django_channels library for realtime logic on my site. I have included the following websockets URL patterns (file my_project/asgi.py): application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( news.routing.websocket_urlpatterns ) ) ), }) Everything worked fine until I decided to configure wildcard subdomains using the library django_hosts(file my_project/hosts.py): host_patterns = patterns('', host(settings.DEFAULT_SUBDOMAIN, settings.ROOT_URLCONF, name='www'), host(r'(?P<p_category>\w+)', 'my_site.hostsconf.urls', name='category'), ) And after that I can't connect to the websocket using javascript: Is there a way to configure these two libraries so I can connect? I can't find the way to configure django_hosts to connect using the ws:// scheme. -
When logged in as a user, the cart does not clear after completing the transaction via paypal in my Django project. It works when not logged in
I recently completed a YouTube tutorial series from Dennis Ivy on building a Django-based ecommerce website. My website works except for 1 major bug. When the user is logged in and goes through the checkout process, the cart does not clear after completing the paypal checkout. When the user is not logged in ("AnonymousUser"), it works correctly. I'm struggling to find the source of this bug. Any suggestions? I'm including the parts of the code I think might be relevant. cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } function addCookieItem(productId, action){ console.log('User is not authenticated') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[productId]; } } console.log('CART:', … -
Prefetch Related, Select Related on a Through Model in Django Admin Form
Several Duplicate Queries in Django Admin Form. I have models something similar to below examples. I am giving inlines in my django admin and I have declared prefetch related but still it is giving many duplicate queries on foreign key fields present in the inline model. I have tried .prefecth_related('b1','b1__a') etc... no luck on reducing the queries and the page is loading very slowly due to the amount of queries running class A(models.Model): name = models.CharField(max_length=10) b1 = models.ManyToManyField(B) class B(models.Model): name = models.CharField(max_length=10) class C(models.Model): name = models.CharField(max_length=10) class D(models.Model): name = models.CharField(max_length=10) class E(models.Model): a = models.ForeignKey(A, on_delete=models.DO_NOTHING) b = models.ForeignKey(B, on_delete=models.DO_NOTHING) c = models.ForeignKey(C, on_delete=models.DO_NOTHING) d = models.ForeignKey(D, on_delete=models.DO_NOTHING) class EInline(admin.TabularInline): model = E extra = 0 can_delete = False show_change_link = False def get_queryset(self, request): queryset = super(EInline, self).get_queryset(request).select_related( 'a', 'b', 'c') return queryset class Aadmin(admin.ModelAdmin): inlines = [EInline,] def get_queryset(self, request): queryset = super(Aadmin, self).get_queryset(request) queryset = queryset.prefetch_related('b1') return queryset -
How to generate a uml diagram from c++ source code dynamically
I am busy developing code that parses through c++ source code and examines the inheritance there. I want to have the program dynamically generate html for representing a UML class diagram of the source code being analysed. Some information: The program has been written in Python and the UI is a django webpage The program already extracts the relevant information and can display the files The class diagram is only for user reference so they can navigate the files with some insight I am looking into using mermaid and javascript for these purposes but am having some trouble. Any advise would be appreciated. How to create a dynamic UML-diagram from HTML Tables? This comes close to a solution but not quite. Right now I dynamically generate lists the store the relevant class information. -
Django select2 with ModelChoiceField/ createTag (how to create a create new record)
How do I handle using select2 with ModelChoiceField, but enable adding a new record I have the Select2 JS in place, and everything works well. I can use my queryset for the ModelChoiceField, and that works. However, if I try to add a new record all I get is the error "Select a valid choice. That choice is not one of the available choices". Which is true - in the view I tried to grab "ID 0" to then create a new record, but can't get past validation without the above error Also, if I do get this to work, it will provide the "0" ID, but ultimately I require the "term" for the new record, but can't see how this is done <script type="text/javascript"> $("#id_indoor_cooler").select2({ theme:"bootstrap4", search_fields: ['model_number'], tags: true, createTag: function (params) { var term = $.trim(params.term); if (term === '') { return null; } return { id: 0, text: term, newTag: true, // add additional parameters, value: "myCustomValue" } } }); </script> -
Is there a way to see which libraries are being monkey patched when running celery with eventlet pool in a Django application?
I am currently running a Django project that offloads work to celery background workers. For CPU-bound tasks the fork pool is working great running like so: celery -A myApp worker -l INFO -E -n worker --concurrency=<CPU-core-count> However, with a growing set of long-running tasks mostly scraping APIs from background workers I am looking create a separate queue to make use of eventlet (or gevent pool) for better scaling these workloads. I am running eventlet it like so which starts the worker and seems fine when I test it. celery -A myApp worker -l INFO -E -n worker --concurrency=100 -p eventlet I have tested two different version setups for eventlet. First off with these versions: - Celery 5.1.0 - Eventlet 0.33 When running this setup I get the same error as reported here when making API polls + database queries in my workers:DatabaseWrapper objects created in a thread can only be used in that same thread Other suggestions have proposed simply updating eventlet and Celery to the latest version and after I did the workers seems to run well with this setup: - Celery 5.2.7 - Eventlet 0.33 Lastly, I've tried running gevent like so for comparison: celery -A myApp worker … -
I can not deploy my django project to heroku server when I want to deploy in it gives me error
I can not deploy my Django project to the Heroku server when I want to deploy it gives me the error I deploy it with Heroku CLI this is the error remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection- failure remote: remote:! Push failed remote: Verifying deployment... remote: remote:! Push rejected to RBclass. remote: To https://git.heroku.com/rbclasss.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/rbclasss.git' -
From postman I am Trying to send multiple zone details in a array like zone = ["zone1","Zone2"] but i am not able to store it in django
Views.py class EmployeeRegistrationViewSet(viewsets.ViewSet): """ API endpoint that allows employee details to be viewed or edited. """ def list(self, request): platform = EmployeeRegistration.objects.all() serializer = EmployeeRegistrationSerializer(platform, many=True) return Response(serializer.data) def create(self, request): api_status = False serializer = EmployeeRegistrationSerializer(data=request.data,many=True) if serializer.is_valid(): api_status = True serializer.save() return Response( { "status": api_status, "errors": serializer.errors, "results": serializer.data, }, status=status.HTTP_201_CREATED if api_status else status.HTTP_400_BAD_REQUEST, ) Url.py router = routers.SimpleRouter() router.register('employee_reg', views.EmployeeRegistrationViewSet, basename='employee_reg') urlpatterns = router.urls modal.py -> note and city is coming from another model.py -> address.modal.py class AddressAbstractModel(BaseAbstractModel): address = models.CharField(max_length=255) pin_code = models.CharField(max_length=10) zone = models.ManyToManyField(Zone) state = models.ForeignKey(State, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) class Meta: abstract = True class Zone(BaseAbstractModel): name = models.CharField(max_length=64) def __str__(self): return self.name Serializer.py class EmployeeRegistrationSerializer(serializers.ModelSerializer): class Meta: model = EmployeeRegistration fields = '__all__' read_only_fields = [ 'is_active', 'soft_delete', 'created_by', 'created_at', 'last_modified_at', 'deactivated_at', ] postman data { "user_type": "Administrator", "code": "123456", "name": "Aashish Giri", "email": "hopeone476@gmail.com", "mobile_no": "9846695452", "alternate_mobile_no": "9846695452", "designation": "sss", "state": 1, "city": 1, "user": 2, "zone": [ "1", "2" ] } I am trying to send data as a array in many-to-many field but I was not able to save data I got error like - "detail": "JSON parse error - Got AttributeError when attempting to … -
Django: How to automatically fill previous users in the user field of a new model that uses OneToOne relation
I have a conventional project that stores users in auth_user django table. Later, I decided to implement a profiles app. The views.py code is below class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) I do makemigrations and migrate. The table is created with empty data, i.e., previous users that exist in auth_user were not populated in the profiles_profile table. How can I populate old data in my new table? Thanks -
How to check when was last time the User logged in?
I would like to update my model if the user did not logged in the day before . @receiver(post_save, sender=user_logged_in) def user_logged_in_streak(sender, instance, *args, **kwargs): if user_logged_in <check if the user logged in yesterday> <NOT SURE WHAT TO DO HERE >: current_streak = UserStatisticStatus.objects.filter(user=instance.user).first().day_streak UserStatisticStatus.objects.update(day_streak=current_streak + 1) ```