Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mqtt over socket in django-channels
I am trying to start a mqtt broker over websocket in django-channels to publish data over specific topics to authorized users. I have defined a url to filter mqtt request in a specific consumer where I am accepting the socket request. This all part is working fine but when I am establishing a mqtt connection the socket is restarting again and again, and I don't have any idea why this is happening!? and also it's a bit confusing how will i send the message from my views. Code snippets: routing.py from django.urls import re_path from . import consumer websocket_urlpatterns = [ re_path(r'ws/data/(?P<room_name>\w+)/(?P<auth_data>\S+)/$',consumer.ChatConsumer.as_asgi()), re_path(r'mqtt', consumer.ChatTwoConsumer.as_asgi()) ] consumer.py class ChatTwoConsumer(WebsocketConsumer): def connect(self): print('here') self.accept() -
Why does form.is_valid return false. Please advice
I have a project where one books a room online then is directed to the checkout page where you input a phone which is required in the backend. Code is as below: forms.py from django import forms class AvailabilityForm(forms.Form): check_in = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'], required=True) check_out = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'], required=True) class PhoneNoForm(forms.Form): phone_no = forms.IntegerField(required=True) views.py class RoomDetailView(View): def get(self, request, *args, **kwargs): category = self.kwargs.get('category', None) got_category = get_room_category(category) print(category) print(got_category) form = AvailabilityForm() if got_category is not None: context = { 'category':got_category, 'form':form } return render(request, 'detail.html', context) else: return HttpResponse("Category Nyet!") def post(self, request, *args, **kwargs): category = self.kwargs.get('category', None) form = AvailabilityForm(request.POST) if form.is_valid(): data = form.cleaned_data available_rooms = get_available_rooms(category, data['check_in'], data['check_out'] ) if available_rooms is not None: room = available_rooms[0] context = { 'room':room } return render(request, 'booking/checkout.html', context) else: return HttpResponse("We're out of those rooms" ) else: return HttpResponse('Form invlid') class CheckoutView(TemplateView): template_name = 'booking/checkout.html' def get_phone(request): if request.POST: phone_no = request.POST.get('PhoneNo', None) print(phone_no) context = { 'phone_no' : phone_no } return render(request, 'booking/checkout.html', context) else: return redirect('booking:RoomDetailView') checkout.html <div> <form action="" method="POST"> {% csrf_token %} <label for="Input No.">Input Phone No. :</label> <input type="number" name="id_PhoneNo" id="PhoneNo"> <input type="submit" value="Proceed"> </form> </div> detail.html <form id="booking-form" action="" method="POST"> {% … -
Django Two Models CreateView
Good Evening / Hello.... I have in essence three models: User / UserAddress / Organisation - simplified for brevity User(model.Models): id = uuid..... address = models.ForeignKey(Address.....) member_of = models.Many2Many(Organisation..... Adress(model.Models): id = uuid ..... Organisation(model.Models): id = uuid .... I have just started practicing MBV class forms. When I create a user - The member_of is filtered in the model.form with no issues - works great. The issue im having is using a create view to Add a user and address on one form. What i have tried: 1) class ActorUserCreateView(LoginRequiredMixin, CreateView): template_name = 'user/create.html' form_class = CreateNewUser address_form_class = PostalAddressForm success_url = reverse_lazy('user_list') def post(self, request, *args, **kwargs): address_form = PostFormSet(request.POST) logging.info("ADDRESS FORM") logging.info(address_form) user_form = self.get_form() logging.info(user_form) if address_form.is_valid() and user_form.is_valid(): return self.form_valid(address_form=address_form, form=user_form) else: messages.add_message(request, messages.WARNING, 'Error in Form') return super().post(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['address'] = PostFormSet return context PostFormSet is in forms as: PostFormSet = formset_factory(PostalAddressForm, max_num=1) This is beginning to put me off CBV's - function based views seem a lots easier but ive been told this is the to go.... The errors: in the terminal - ive run logging on the address form: <tr><td colspan="2"><ul class="errorlist nonfield"><li>(Hidden field TOTAL_FORMS) … -
Can't install uwsgi. I have error: command errored out with exit status 1:
I want to install uwsgi to virtual environment of my Django project, but when I use pip install uwsgi command I have ERROR: Collecting uwsgi Using cached uWSGI-2.0.19.1.tar.gz (803 kB) ERROR: Command errored out with exit status 1: command: 'c:\users\user\desktop\django\elearning\env\scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\user\\AppDat a\\Local\\Temp\\pip-install-rr2kmfru\\uwsgi_4ef6d74e2e904e84ac89967ff6772bba\\setup.py'"'"'; __file__='"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-rr2kmfru \\uwsgi_4ef6d74e2e904e84ac89967ff6772bba\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from s etuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-ba se 'C:\Users\user\AppData\Local\Temp\pip-pip-egg-info-yv8e_7oq' cwd: C:\Users\user\AppData\Local\Temp\pip-install-rr2kmfru\uwsgi_4ef6d74e2e904e84ac89967ff6772bba\ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\user\AppData\Local\Temp\pip-install-rr2kmfru\uwsgi_4ef6d74e2e904e84ac89967ff6772bba\setup.py", line 3, in <module> import uwsgiconfig as uc File "C:\Users\user\AppData\Local\Temp\pip-install-rr2kmfru\uwsgi_4ef6d74e2e904e84ac89967ff6772bba\uwsgiconfig.py", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname' ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/c7/75/45234f7b441c59b1eefd31ba3d1041a7e3c89602af24488e2a22e11e7259/uWSGI-2.0.19.1.tar.gz#sha256=faa85e053c 0b1be4d5585b0858d3a511d2cd10201802e8676060fd0a109e5869 (from https://pypi.org/simple/uwsgi/). Command errored out with exit status 1: python setup.py egg_info Check t he logs for full command output. -
Djano displaying default photo next to each category
Im new to Django and don't really know how to write the part of code. I have few categories under Class Offers, I would like to add default photo for each category, so while adding a new offer the default photo will be connected to the category my Model of offer: CATEGORY = ( ("Babysitting", "Babysitting"), ("Housework", "Housework"), ("Private lessons", "Private lessons"), ("Agro", "Agro"), ) class Offers(models.Model): category = models.CharField(choices=CATEGORY, max_length=20, null=True) description = models.CharField(max_length=255) paid_per_hr = models.IntegerField() created = models.DateTimeField(auto_now_add=True ) updated = models.DateTimeField(auto_now_add=True) i'm bit stuck with problem on how to assign the default photo different to each category class AddOfferView(LoginRequiredMixin, View): def get(self, request): form = OfferForm() return render(request, 'offer.html', {'form': form}) I can add the new offer with default one phono but then each category has same photo. -
Django/Ajax sending 'none' value to view
When i send data from ajax to view in Django I am getting none in data. What seems to be the problem. Here is mycode. Where as if i remove processData: false, contentType: false, then data is printed successfully but on file it gives error. Ajax code <script> function submit_data() { var type = $('#type').val(); var subtype = $('#subtype').val(); var name = $('#name').val(); var price = $('#price').val(); var weight = $('#weight').val(); var details = $('#details').val(); var picture1 = $('#image1')[0].files[0]; var picture2 = $('#image2')[0].files[0]; var picture3 = $('#image3')[0].files[0]; var vedio_url = $('#vedio_link').val(); alert(picture1) $.ajax({ url: '/add_record/', type: 'POST', headers: { "X-CSRFToken": '{{csrf_token}}' }, processData: false, contentType: false, data: { type, subtype, name, price, weight, details, picture1, picture2, picture3, vedio_url, }, success: function (response) { alert("datauploaded successfully!") }, error: function(){ alert('error') } }); } </script> View code def add_record(request): print("Yes i am here") type = request.POST.get('type') subtype = request.POST.get('subtype') name = request.POST.get('name') price = request.POST.get('price') weight = request.POST.get('weight') details = request.POST.get('details') picture1 = request.FILES.get('picture1') picture2 = request.FILES.get('picture2') picture3 = request.FILES.get('picture3') vedi_url = request.POST.get('vedio_url') print (picture1) print(type) print(request.POST) return JsonResponse({'message':'success'},status=200) Error: Yes i am here None None <QueryDict: {}> its returning none, Why is that? -
Django if datefield variable present not working
I have the variable dob which is a DateField from the model StudentUser. I have even checked that I got its value in the template page by the snippet {{ student.dob }}. It displays Jan 12, 1999 But, when I am putting it in an if condition to check if the user has set it or not, it is not showing. Here is the snippet: Template.html <div class="form-group col-md-6"> <label>Date of Birth</label> <input type="date" name="dob" class="form-control" value="{% if student.dob %} {{ student.dob | date:'Y-m-d' }} {% endif %}"> </div> -
How to clear an image from image field in Django forms
Is there a way to display a tick box to clear an image as it has place when I edit a post? When I am creating a new post and adding an image to the image field, then I cant clear the field. To remove the image, I would have to create a post and then edit it. Another question is, If I can change the label "Browse.." and "No file selected" to any other word? -
Django forms for sex
I am working with a database that stores sex as 0 - male and 1 - female. My forms.py looks like this class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = TbUser def clean_username(self): username = self.cleaned_data["username"] try: TbUser.objects.get(username=username) except TbUser.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) class TbUserRegisterForm(CustomUserCreationForm): email = forms.EmailField() class Meta: model = TbUser fields = ['username', 'email', 'cellphone', 'sex', 'role', 'department', 'password1', 'password2'] Django user model class TbUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4) username = models.CharField(max_length=40, blank=True, null=True, unique=True, db_column='usname') password = models.CharField(max_length=255, blank=True, null=True, db_column='dj_psword') email = models.CharField(max_length=255, blank=True, null=True) cellphone = models.CharField(max_length=100, blank=True, null=True) image_id = models.CharField(max_length=40, blank=True, null=True) sex = models.IntegerField(blank=True, null=True) is_available = models.IntegerField(blank=True, null=True) role = models.ForeignKey(TbRole, on_delete=models.CASCADE) department = models.ForeignKey(TbDepartment, on_delete=models.CASCADE) is_superuser = models.BooleanField(default=False, blank=True, null=True, db_column='default_super') is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = TbUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: managed = False db_table = 'tb_user' def __str__(self): return '%s' % self.username Since sex is an integer field, the UI form field is not a choice field but just showing arrows for incrementing the integer. Is there a way to make it a choice field that for m will store 0 and f - 1? -
Access forbidden to Heroku app that I just created [ Error: You do not have access to the app my-app. » Error ID: forbidden]
So I was following a tutorial on how to use Heroku. Smooth sailing until I created the app and immediately got my access denied. I followed the steps provided here: https://medium.com/@qazi/how-to-deploy-a-django-app-to-heroku-in-2018-the-easy-way-48a528d97f9c. Immediately after using this command access was denied : heroku addons:create heroku-postgresql:hobby-dev --app my-app Creating heroku-postgresql:hobby-dev on ⬢ my-app... ! ! You do not have access to the app my-app. I tried to migrate anyway hoping access might be restored and this was the result : heroku run python manage.py migrate -a my-app Running python manage.py migrate on ⬢ my-app... done » Error: You do not have access to the app my-app. » » Error ID: forbidden Help me please. -
Reverse for 'post-list' not found. 'post-list' is not a valid view function or pattern name
I'm still within the very early stages of learning Django and I have just ran in to this error (I am following a tutorial, not too sure where I've messed up!) "Reverse for 'post-list' not found. 'post-list' is not a valid view function or pattern name." In my template file here is how my template tag looks: {% if user.is_authenticated %} href="{% url 'post-list' %}" {% else %} As for my URLs.py: urlpatterns = [ path('', PostListView.as_view(), name='post-list'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/edit/<int:pk>/', PostEditView.as_view(), name='post-edit'), path('post/delete/<int:pk>/', PostDeleteView.as_view(), name='post-delete'), path('post/<int:post_pk>/comment/delete/<int:pk>/', CommentDeleteView.as_view(), name='comment-delete'), path('post/<int:post_pk>/comment/<int:pk>/like', AddCommentLike.as_view(), name='comment-like'), path('post/<int:post_pk>/comment/<int:pk>/dislike', AddCommentDislike.as_view(), name='comment-dislike'), path('post/<int:post_pk>/comment/<int:pk>/reply', CommentReplyView.as_view(), name='comment-reply'), path('post/<int:pk>/like', AddLike.as_view(), name='like'), path('post/<int:pk>/dislike', AddDislike.as_view(), name='dislike'), path('profile/<int:pk>/', ProfileView.as_view(), name='profile'), path('profile/edit/<int:pk>/', ProfileEditView.as_view(), name='profile-edit'), path('profile/<int:pk>/followers/', ListFollowers.as_view(), name='list-followers'), path('profile/<int:pk>/followers/add', AddFollower.as_view(), name='add-follower'), path('profile/<int:pk>/followers/remove', RemoveFollower.as_view(), name='remove-follower'), path('search/', UserSearch.as_view(), name='profile-search'), path('notification/<int:notification_pk>/post/<int:post_pk>', PostNotification.as_view(), name='post-notification'), path('notification/<int:notification_pk>/profile/<int:profile_pk>', FollowNotification.as_view(), name='follow-notification'), path('notification/<int:notification_pk>/thread/<int:object_pk>', ThreadNotification.as_view(), name='thread-notification'), path('notification/delete/<int:notification_pk>', RemoveNotification.as_view(), name='notification-delete'), path('inbox/', ListThreads.as_view(), name='inbox'), path('inbox/create-thread/', CreateThread.as_view(), name='create-thread'), path('inbox/<int:pk>/', ThreadView.as_view(), name='thread'), path('inbox/<int:pk>/create-message/', CreateMessage.as_view(), name='create-message'), ] Could anyone give me any pointers with this? Thanks, Jay. -
I tried to create a second model, but when I try to put it in my html page nothing appears
When I try to create the second model my html page comes out blank. I tried to copy the first model but I don't think I succeeded. Is the error in views.php? This is my code: models.py from django.db import models from colorfield.fields import ColorField # Create your models here. class Aziende(models.Model): immagine = models.ImageField() nome = models.CharField(max_length=250) prezzo = models.FloatField() descrizione = models.CharField(max_length=250) nome_color = ColorField(default='#FF0000') def __str__(self): return self.nome class Meta: verbose_name_plural = "Aziende" class Materie(models.Model): immagine = models.ImageField() nome = models.CharField(max_length=250) prezzo = models.FloatField() descrizione = models.CharField(max_length=250) nome_color = ColorField(default='#FF0000') def __str__(self): return self.nome class Meta: verbose_name_plural = "Materie" admin.py from django.contrib import admin from .models import Aziende from .models import Materie admin.site.register(Aziende) admin.site.register(Materie) views.py from django.shortcuts import render from .models import Aziende from .models import Materie # Create your views here. def Borsa(request): Borsa = Aziende.objects.all() return render(request, 'Borsa/Home.html', {'Borsa': Borsa},) def Materia(request): Materia = Materie.objects.all() return render(request, 'Borsa/Home.html', {'Materie': Materia},) home.html <div class="container"> <div class="row"> {% for Materie in Materia %} <div class="col"><br> <div class="container text-center"> <div class="card" style="width: 18rem;"> <img src="{{ Materie.immagine.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="title" style="color: {{Materie.nome_color}}" >{{Materie.nome}}</h5> <p class="card-text">{{Materie.descrizione}}</p> <p class="card-text fst-italic text-primary">Valore Attuale: €{{Materie.prezzo}}</p> <a href="#" class="btn btn-primary">Investici!</a> … -
Is there any way to use Firebase Phone authentication in Django?
I came to know about the Pyrebase. But it only offers email authentication. I need to use only Phone authentication. Users can login by verifying their OTP. But there doesn't seem to be any proper guideline out there. Anyone want to elaborate this topic little more? Your help is really appreciated. -
Use the same route for with 2 different viewsets, one for writing and one for reading
I have 2 viewsets one for read and other to write: class MenuReadViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = MenuSerializer queryset = Menu.objects filter_class = RelatedEstablishmentFilter class MenuWriteViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = MenuSerializer In my urls.py ... router = routers.DefaultRouter() router.register("menus", views.MenuReadViewSet, basename="menu-read") router.register("menus", views.MenuWriteViewSet, basename="menu-write") urlpatterns = [ path("", include(router.urls)) ] The problem is, when i send a POST, PUT or DELETE , returns this response: { "detail": "Method <METHOD> not allowed" } It seems that the route considers only the first viewset. Exists a simple way to solve this? -
Can I pass additional data to the template if I use UpdateView?
By default, only Schema-related data is passed. But inside the template, I also want to specify the Elements and their characteristics. How can I pass this data to the template? Sorry, I'm at war with Django for the 5th day and not everything is easy for me ): Specifically, I want to pass this data to the template, but the set of this data depends on the Schema: if form.is_valid(): scheme_id = form.cleaned_data['id'] elements = [] dbelements = Element.objects.filter(id=scheme_id) for dbelement in dbelements: elements.append({'id': dbelement.id, 'name': dbelement.name, 'additions_number': len(ElementAddition.objects.filter(element=dbelement.id)), 'transitions_number': len(ElementTransition.objects.filter(element=dbelement.id))}) urls: urlpatterns = [ path('', views.LoginView.as_view(), name='login'), path('users/', views.UsersView.as_view(), name='users'), path('config/', views.ConfigView.as_view(), name='config'), path('schemes/', views.SchemesView.as_view(), name='schemes'), path('schemes/<int:pk>/', views.SchemeUpdateView.as_view(), name='scheme-update'), ] forms: class SchemeForm(ModelForm): class Meta: model = Scheme fields = ['name'] widgets = { 'name': TextInput(attrs={'placeholder': 'имя ветки'}) } views: class SchemeUpdateView(UpdateView): model = Scheme template_name = 'manager/scheme.html' form_class = SchemeForm html: <div> <div class="caption">Схема</div> <a href="{% url 'schemes' %}"> <button>Go back</button> </a> </div> <br> <form method="post"> {% csrf_token %} {{ form }} <span>{{ error }}</span> <button name="save_btn" type="submit">Save</button> <button name="cancel_btn" type="submit">Cancel</button> <br><br> <table> <tbody> <tr> <th>№</th> <th>Element name</th> <th>Number of additions</th> <th>Number of transitions</th> <th>Management</th> </tr> {% for element in elements %} <tr> <td>{{ forloop.counter }}</td> <td>{{ element.name … -
How to create a second model in django?
The more I look for help the more I get confused, so here I am. To many it may seem trivial but to me it is not. I tried to create a second template, but when I try to put it in my html page nothing appears. What should I import and what should I write? Thanks in advance! -
TypeError: create_user() missing 2 required positional arguments: 'username' and 'email'
I am trying to create a super user but i have been getting one error. This TypeError: create_user() missing 2 required positional arguments: 'username' and 'email' here is my models.py file class UserManager(BaseUserManager): def create_user(self, birth_date, fullname, country, username, email, password=None, **other_fields): if username is None: raise ValueError("users should have a username") if email is None: raise ValueError("users should have an email") # if birth_date is None: # raise TypeError( # "users must include their birth date for validation") user = self.model(birth_date=birth_date, fullname=fullname, country=country, username=username, email=self.normalize_email( email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError("Password should not be none") user = self.create_user( username, email, password) user.is_superuser = True user.is_staff = True user.is_active = True user.save(using=self._db) return user I have been seeing a lot of questions similar to this but i still don't understand the answers given, some say add positional arguements, I don't quite understand. Any form of help would be appreciated -
What is AWS_DEFAULT_ACL supposed to be used in django-storages?
I'm a bit of a newbie to django-storages and I'm confused about the purpose of its AWS_DEFAULT_ACL settings variable. I gather that when it's set to None, the bucket policy on my AWS S3 bucket will be honored. That seems to indeed be true. I've turned off public access to my bucket and am using the following bucket policy: { "Version": "2012-10-17", "Id": "Policy1621539673651", "Statement": [ { "Sid": "Stmt1621539665305", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::063896663644:user/mylogin" }, "Action": [ "s3:GetObject", "s3:GetObjectAcl", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::mybucket/*" }, { "Sid": "Stmt1621539600741", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::mybucket/static/*" } ] } I can run python manage.py collectstatic and it uploads files without an issue. However, if I change AWS_DEFAULT_ACL to 'public-read', I get errors when running collectstatic. Copying '/Users/dylan/Dev/myapp/static/css/bootstrap-datetimepicker.css' Traceback (most recent call last): File "/Users/dylan/Dev/myapp/./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/dylan/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/dylan/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/dylan/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/dylan/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/dylan/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle collected = self.collect() File "/Users/dylan/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 118, in collect handler(path, prefixed_path, storage) File "/Users/dylan/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 355, in copy_file self.storage.save(prefixed_path, … -
django admin order of fields and form
I want to arrange (readonly) fields above a form and put some info fields below it: class ProductAdmin(admin.ModelAdmin): list_display = ["nbr", "store", "data", "created", "last_change",] form = pForm ordering = ["nbr", "store", "data", "created", "last_change",] readonly_fields = ["nbr", "store", "created", "last_change",] I want to achieve this order: nbr store data (the only editable field) created -- changed (can I easily put them in one line or do I have to use somehting like: def hlp(self, obj): return f"{obj.created} - {obj.last_change}2)? -
There are incompatible versions in the resolved dependencies
I’m trying to just run my python project that seems to work fine on my Mac (best in pycharm, not as good but can run in VSCode) and terrible on my raspberry pi in VSCode. Whenever I run a pipenv shell and then a pipenv install it just complains with this error: Pipfile.lock (e9a11d) out of date, updating to (47943b)... Locking [dev-packages] dependencies... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! [ResolutionFailure]: File "/home/nick/.local/lib/python3.7/site-packages/pipenv/resolver.py", line 741, in _main [ResolutionFailure]: resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages, dev) [ResolutionFailure]: File "/home/nick/.local/lib/python3.7/site-packages/pipenv/resolver.py", line 709, in resolve_packages [ResolutionFailure]: requirements_dir=requirements_dir, [ResolutionFailure]: File "/home/nick/.local/lib/python3.7/site-packages/pipenv/resolver.py", line 692, in resolve [ResolutionFailure]: req_dir=requirements_dir [ResolutionFailure]: File "/home/nick/.local/lib/python3.7/site-packages/pipenv/utils.py", line 1403, in resolve_deps [ResolutionFailure]: req_dir=req_dir, [ResolutionFailure]: File "/home/nick/.local/lib/python3.7/site-packages/pipenv/utils.py", line 1108, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/home/nick/.local/lib/python3.7/site-packages/pipenv/utils.py", line 833, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again. Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release … -
How to run a terminal command in Django app?
I want to execute a terminal command whenever I visit the index page in my Django app. I've done it outside of the Django app and it worked. Outside of my Django app I ran: import subprocess subprocess.run('python hello.py') The hello.py file which contains a regular print statement print('Hello') and in the terminal from where I ran the command using the above script, it of course prints "Hello" like a charm. My question is, is it possible to run something like below in my Django app? def index(request): subprocess.run('python manage.py process_tasks') today = datetime.now() schedule_time = datetime(year=today.year, month=today.month, day=today.day, hour=today.hour + 5, minute=today.minute + 1, tzinfo=pytz.UTC) run_until = datetime(year=today.year, month=today.month, day=today.day, hour=today.hour + 5, minute=today.minute + 1, tzinfo=pytz.UTC) print_hello(schedule=schedule_time, repeat=20, repeat_until=run_until) return HttpResponse(f'Background task running...') By including this command subprocess.run('python manage.py process_tasks') in the view function it will at least eliminate me opening another terminal to run python manage.py process_tasks to get the app to work in the background for me. The app went to the page successfully but the background tasks aren't picking up and in the terminal it is saying ModuleNotFoundError: No module named 'background_task'. Here's the image with the error message for a better understanding. Thanks! ModuleNotFoundError -
Switch Boolean on selected date and time
I want to switch expiry boolean from false to true at given expiry_datetime ... expiry = models.BooleanField(default=False) expiry_datetime = models.DateTimeField(null=True) Is it possible? -
Django how to generate a filtered queryset
I have got 2 models. Asset and Asset_Type. In my asset_type detail view i would like to list all assets of that asset type. I think I have to use models.Asset.queryset().filter() but i can't get it to work. On my template I would like to loop though the list with a 'for' (example: object in list) and print the values like this {{ object.name }} models.py class Asset(models.Model): # Relationships room = models.ForeignKey("asset_app.Room", on_delete=models.SET_NULL, blank=True, null=True) model_hardware = models.ForeignKey("asset_app.Model_hardware", on_delete=models.SET_NULL, blank=True, null=True) # Fields name = models.CharField(max_length=30) serial = models.CharField(max_length=30, unique=True, blank=True, null=True, default=None) mac_address = models.CharField(max_length=30, null=True, blank=True) purchased_date = models.DateField(null=True, blank=True) may_be_loaned = models.BooleanField(default=False, blank=True, null=True) notes = models.TextField(max_length=448, null=True, blank=True) ip = models.CharField(max_length=90, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: ordering = ["name"] def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("asset_app_asset_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_asset_update", args=(self.pk,)) class Asset_type(models.Model): # Fields name = models.CharField(max_length=30) last_updated = models.DateTimeField(auto_now=True, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False) notes = models.TextField(max_length=448, null=True, blank=True) class Meta: ordering = ["name"] def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("asset_app_asset_type_detail", args=(self.pk,)) def get_update_url(self): return reverse("asset_app_asset_type_update", args=(self.pk,)) views.py class Asset_typeDetailView(generic.DetailView): model = models.Asset_type form_class = forms.Asset_typeForm -
Direct assignment to the forward side of a many-to-many set is prohibited. Use Class.set() instead
When I try to save Class which is in many to many relationship django throws the following error TypeError at /class-create/ Direct assignment to the forward side of a many-to-many set is prohibited. Use Class.set() instead. My views.py looks like this @login_required() def create_class(request): tea_user = request.user.username validate = teacher_validation(tea_user) if validate: if request.method == 'POST': Link = request.POST.get('link') Subject = request.POST.get('Subject') Class = request.POST.get('Class') teacher_user = Teacher.objects.get(User=request.user) teacher = Teacher.objects.get(id=teacher_user.id) created_class = Online_Class(Link=Link, Subject=Subject, Created_by =teacher, Class=Class) created_class.save() return render(request, 'online_class/Teacher/class-create.html') else: messages.warning(request, 'Sorry You Dont have Permission to access this page') return redirect('logout') And my models.py file looks like this class Online_Class(models.Model): Created_by = models.ForeignKey(Teacher, on_delete=models.DO_NOTHING) Class = models.ManyToManyField(Classes) Subject = models.CharField(max_length=100) Link = models.CharField(max_length=200) Joined_by = models.ManyToManyField(Student, blank=True) created_at = models.DateTimeField(auto_now_add=True) choice = (('Yes','Yes'),('No', 'No')) Class_Ended = models.CharField(choices=choice, default='No', max_length=10) Please help me figure it out -
In My Django project My Body Tag In Html is not showing the background?
this is the code when I am trying to do this in another clean HTML file it is working but in my Django project, it is not KINDLY ANSWER ME HURRY PLZ (and I have also copied the same photo in that location where this HTML project is. CODE:` `