Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to get the weather details from an API on django however I am facing an error and I can't get past it
def index(request): if request.method == 'POST': start_city = request.POST['city'] city= str(urlparse(start_city)) start_url = 'https://api.openweathermap.org/data/2.5/weather?city='+city+'&appid=<APPID>' url = start_url.replace(' ','') res = urllib.request.urlopen(url).read() json_data = json.loads(res) context = { 'city': city, 'country': json_data['sys']['country'], 'windspeed':json_data['wind']['speed'], 'temperature':json_data['main']['temp'], } else: city='' return render(request,'index.html', {'city':city}) ERROR HTTPError at / HTTP Error 400: Bad Request Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.0.3 Exception Type: HTTPError Exception Value: HTTP Error 400: Bad Request -
Why LoginRequiredMixin don't stop my dispatch flow, when user is not authenticated
I have no clue why in this View, dispatch does not end after super(): class CreateBookView(LoginRequiredMixin, CreateView): template_name = 'library/create_book.html' form_class = BookForm def dispatch(self, request, *args, **kwargs): result = super().dispatch(request, *args, **kwargs) if self.request.user.is_authenticated and not self.request.user.contactform.is_completed: return redirect(reverse_lazy('edit_contacts') + f"?next={self.request.path}#edit") return result def form_valid(self, form): form.instance.owner = self.request.user form.instance.category = self._set_category(form) return super().form_valid(form) def get_success_url(self): pk = self.request.user.pk default_redirect = reverse_lazy('show_books_dashboard', kwargs={'pk': pk}) next_page = self.request.GET.get('next') return next_page if next_page else default_redirect @staticmethod def _set_category(form): category = form.cleaned_data.get('category') category_name = form.cleaned_data.get('category_name') if category or not category_name: return category new_category, created = Category.objects.get_or_create(name=category_name) return new_category But in this it works as I expected and end it: class DetailsNotificationView(LoginRequiredMixin, AuthorizationRequiredMixin, DetailView): model = Notification context_object_name = 'notification' template_name = 'common/notifications/notifications_details.html' authorizing_fields = ['recipient'] def dispatch(self, request, *args, **kwargs): result = super().dispatch(request, *args, **kwargs) notification = self.get_object() notification.is_read = True notification.save() if notification.offer: return redirect('show_offer_details', pk=notification.offer.pk) return result I expect LoginRequiredMixin to handle error immediately after super() when the user is not authenticated and stop dispatch flow. I cannot figure out why it does not work as expected in CreateBookView. Any ideas ? -
mod_wsgi not using venv
Hello I am trying to setup a Django project using Apache with mod_wsgi. I have set wsgi like this WSGIDaemonProcess Breath python-home=/var/www/vhosts/Breath/env/ WSGIProcessGroup Breath WSGIScriptAlias / /var/www/vhosts/Breath/BreathAlessio/wsgi.py process-group=Breath So I'd like to launch the wsgi.py with the version in the venv, but by checking the version I see it runs it with the default python installation. What am I doing wrong? I have tried to set all the permission to 777 and to change the owner of the project but nothing changed Thanks in advance. -
Pip: Fatal error in launcher: Unable to create process using
I developed a complete Django project on my system. When I try to run on another system, after activating my virtual environment "data". It shows me the path of my system (where it's developed). (data) PS D:\Hafiz\Data_Collection> pip Fatal error in launcher: Unable to create process using '"D:\Masters_FIT\4th\Webdatabese\Project\Data_Collection\Data\Scripts\python.exe" "D:\Hafiz\Data_Collection\data\Scripts\pip.exe" ': The system cannot find the file specified. On other systems python, pip, and Django are installed with their latest versions and paths are also added. I tried a new project there and it's working properly. -
How set username to ForeignKey
I want to set value, but i don't know how do it. Error: RelatedObjectDoesNotExist at /comments/ commentsTabl has no avtor. Request Method: GET Request URL: http://localhost:8000/comments/ Django Version: 4.0.2 Exception Type: RelatedObjectDoesNotExist Exception Value: commentsTabl has no avtor. Exception Location: D:\python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in get Python Executable: D:\python39\python.exe Python Version: 3.9.6 Python Path: ['D:\Django\ForumXT\first', 'D:\python39\python39.zip', 'D:\python39\DLLs', 'D:\python39\lib', 'D:\python39', 'D:\python39\lib\site-packages'] Server time: Thu, 07 Apr 2022 12:20:35 +0000 models.py class commentsTabl(models.Model): Text = models.TextField(verbose_name='Text') date = models.DateTimeField(default=timezone.now, verbose_name='date') avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE, to_field="username") def __str__(self): return f'Comment {self.avtor} at {self.date}' class Meta: verbose_name = "Comment" verbose_name_plural = "Comments" views.py def comments(request): data = { 'com': reversed(commentsTabl.objects.all()) } if request.method =="POST": form = commentsTabl(request.POST) if form.is_valid(): form.save() else: form = commentsTabl() return render(request, 'home/comments.html', data, {'form':form}) -
Django csrf token + react
I'm using django for my API and react for my frontend app. My problem is I do not know how to get csrf token which is needed to submit the login form (I do not need registrition form, just few users). This is the code for handling the /accounts/login : from django.contrib.auth import authenticate, login from django.http import JsonResponse from json import loads def login_user(request): body_unicode = request.body.decode('utf-8') body = loads(body_unicode) username = body['username'] pwd = body['pwd'] user = authenticate(request, username=username, password=pwd) try: if user.is_authenticated: login(request, user) email = User.objects.get(username=username).email return JsonResponse({"username":username, \ "pwd":pwd, \ "email":email }, \ status=200)` except Exception as expt: return JsonResponse({"error": str(expt)}, status=401) And in my react app I'm trying to make a request for logging /accounts/login using the X-CSRFToken header and the csrf token goten by the getCookie() function (found here), but it is always null and the response always rejected with 403 status code. Could you please show me how I can handle that situation please ? (I do not want to use csrf_exempt which pose security issues). -
I can't filter the product vendor for orders
I want special users (vendors) to see their own orders in their django admin. When ever I tried that it filters out the user that ordered the products. Here are the codes. I connected the vendors in my product model. I can't figure out how to connect vendors with their respective orders. class Order(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Preparing', 'Preparing'), ('OnShipping', 'OnShipping'), ('Completed', 'Completed'), ('Canceled', 'Canceled'), ) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) code = models.CharField(max_length=5, editable=False) first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) phone = models.CharField(blank=True, max_length=20) address = models.CharField(blank=True, max_length=150) city = models.CharField(blank=True, max_length=20) country = models.CharField(blank=True, max_length=20) total = models.FloatField() status=models.CharField(max_length=10,choices=STATUS,default='New') ip = models.CharField(blank=True, max_length=20) adminnote = models.CharField(blank=True, max_length=100) create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) class OrderProduct(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Canceled', 'Canceled'), ) order = models.ForeignKey(Order, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) variant = models.ForeignKey(Variants, on_delete=models.SET_NULL,blank=True, null=True) # relation with variant quantity = models.IntegerField() price = models.FloatField() amount = models.FloatField() status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product.title class OrderAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name','phone','city','total','status','create_at'] list_filter = ['status'] readonly_fields = ('user','address','city','country','phone','first_name','ip', 'last_name','phone','city','total') can_delete = False inlines = [OrderProductline] class OrderProductAdmin(admin.ModelAdmin): list_display = ['user', 'product','price','quantity','amount'] list_filter = ['product'] … -
typeError: unsupported operand type(s) for -: 'long' and 'datetime.date'
For this piece of code (the model had other things too, but I deleted them so I can get a minimal example): class Invoice(models.Model): """ Represents one invoice line in the imported data. """ payment_date = models.DateField( blank=True, null=True, help_text="Format: YYYY-MM-DD") date = models.DateField(db_index=True, blank=True, null=True, help_text="Format: YYYY-MM-DD") date_diff = models.IntegerField(default=0) class Meta: app_label = 'analysis' ordering = ('claim_order',) def clean(self): self.date_diff = ( self.payment_date - self.date).days if (self.payment_date and self.date) else 0 I get typeError: unsupported operand type(s) for -: 'long' and 'datetime.date' and I can't see why, because both of the fields are DateFields. Can anybody help me understand why this happens? Thanks. -
Django - Replication lag
Prerequisites: class Task(models.Model): class TaskStatus(models.TextChoices): HIDDEN = 'hidden', _('hidden') NEW = 'new', _('new') IN_PROGRESS = 'in_progress', _('in progress') DONE = 'done', _('done') FAILED = 'failed', _('failed') PLANNED = 'planned', _('planned') REVOKED = 'revoked', _('revoked') title = models.CharField(max_length=500) performer = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(choices=TaskStatus.choices, default=TaskStatus.HIDDEN, max_length=25) class TaskTransition(models.Model): task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, related_name='transitions') actor = models.ForeignKey(User, on_delete=models.RESTRICT, related_name='transitions') old_status = models.CharField(choices=TaskStatus.choices, max_length=25) new_status = models.CharField(choices=TaskStatus.choices, max_length=25) class TaskView(ModelViewSet): queryset = Task.objects.all() serializer = TaskSerializer class CreateTaskTransitionView(mixins.RetrieveModelMixin, generics.CreateAPIView): serializer_class = CreateTaskTransitionSerializer class CreateTaskTransitionSerializer(serializers.ModelSerializer): task = serializers.HiddenField(default=HiddenTaskField()) actor = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = TaskTransition fields = '__all__' def validate(self, attrs): # allowed status transitions: # hidden > new # new > in_progress, failed # in_progress > done, failed return attrs def save(self, **kwargs): task = self.validated_data['task'] new_status = self.validated_data['new_status'] TaskTransition.objects.create( task=task, new_status=new_status, old_status=task.status, actor=self.validated_data['actor'] ) task.status = new_status task.save() return {} We use two databases. First default for writing and replica for reading. Because of validation as you can see only one unique task transition can be done. But sometimes it happens that there can be multiple same transitions. For example 5 transitions in_progress > done. And when retrieve task instance task is with not actual status. It's obvious that this … -
what on_delete option to use in django app?
I have an Article model that allows admins to publish articles. Each article is assigned to a user that is creating this article. I want to make sure that all articles will stay untouched even if I delete the author of this particular article. I chose on_delete=models.DO_NOTHING to be sure that nothing except user account will be removed but I am not quite sure that is the most effective way. class Article(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING) title = models.CharField('Title', max_length=70, help_text='max 70 characters') body = models.TextField('Description') Question Should I use another option to use or DO_NOTHING is good enough. Obviously the most important to me is that author's name will be visible in the article after deletion and the article itself cannot be removed. -
Django admin prepopulated fields and fieldsets
I am using Django 3.2 I have the following model: class Foo(models.Model): title = models.CharField() slug = models.SlugField() # remaining fields listed below In Admin manager, I have the model: class FooAdmin(admin.ModelAdmin): fieldsets = [ ('General', { 'fields': [ 'title', 'description', 'information', 'cover_photo', 'gallery', ] }), ('Details', { 'fields' : [ 'is_cancelled', 'start', 'finish', 'video_url', ] }), ] prepopulated_fields = {'slug': ('title',), } admin.site.register(Foo, FooAdmin) When I attempt to create a new Foo in the admin manager, I get the error: KeyError: "Key 'slug' not found in 'FooForm'. Choices are: cover_photo, description, finish, gallery, information, is_cancelled, start, title, video_url." When I add the slug field to the list of fieldsets, it works, but then the slug field is shown on the form (which I don't want). I know that I can solve this by overriding Foo.save(), but I want the admin manager to handle this for me. So, how do I use fieldsets with prepopulated fields that are not supposed to appear on the form? -
pop up modal appears again when clicked on back button
i have created a confirmation pop up modal using javascript in django's html page, my html template is generating delete links using for loop, so my my logic is i have used target the clicked html element using window event and then i fetch the value of href, store it in varibale, and then apply that value to the yes button of pop modal, and also set the href value of delete link to '#', so it should not work. now my problem is the modal is working properly, but aafter finishing the task, when clicked on browser back button, again the modal is appearing.enter image description here -
django.core.exceptions.ValidationError: ['“TRUE” value must be either True or False.']
I am trying to upload data in the django ORM by a script for which I have written this for index, row in df.iterrows(): allocated = row['is_allocated'] delivery_required_on = row['delivery_required_on'] linked = row['linked'] raised_by = row['raised_by'] raised_for = Company.objects.get(pk=row['raised_for']) ### double check rejected = row['is_rejected'] reason = row['reason'] remarks = row['remarks'] created = row['created_at'] owner = User.objects.get(pk=row['New owner']) j = literal_eval(row['flows']) flows = [] mobj = MaterialRequest.objects.create(owner=owner, is_allocated=allocated, delivery_required_on=delivery_required_on, linked=linked, raised_by=raised_by, raised_for=raised_for, is_rejected=rejected, reason=reason, remarks=remarks, created=created) It is running fine when the data is something like the following: But as soon as is_allocated reaches False it shows the following error: django.core.exceptions.ValidationError: ['“TRUE” value must be either True or False.'] I am unable to find something related to this -
python calculate rating by percent of complete
Let say, when student completed the course then he will get the percentage of his completion. Then we implement the max ratings is 5 stars which following these rules: 0%-4% => 0 star 5%-19% => 1 star 20%-39% => 2 stars 40%-59% => 3 stars 60%-79% => 4 stars 80%-100% => 5 stars So, based on student score: 0% percent complete will get 0 rating star. 10% percent complete will get 1 rating star. Also, another conditionals it can be 30% percent complete will get 2.5 rating stars. NOTE: The max 5 stars is dynamic value, it can be 10 stars. how we can accomplish this? -
Why is Heroku installing SQlite 3 even though I don't have it in requirements.txt
I am deploying a Django 3.2 website (with PG db backend) on Heroku, when I do a git push, this is a snippet of the console output: Enumerating objects: 18, done. Counting objects: 100% (18/18), done. Delta compression using up to 8 threads Compressing objects: 100% (11/11), done. Writing objects: 100% (11/11), 1.04 KiB | 265.00 KiB/s, done. Total 11 (delta 9), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Python has released a security update! Please consider upgrading to python-3.10.4 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.10.3 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip Why is Heroku installing SQlite3 - even though I don't have it in my requirements.txt? Heroku seems to install SQLite3 first, before checking what the requirements are - Why? -
Number of elements in database array using django
I am pretty new in django and I am trying to dispaly using django number of images that appears in my database on my datatable field called number of images Explanation : I have a document that contains several elements. One of these elements is an array called Feedback that contains an array called images with urls of photos. What I need is that I get number of all urls that appears in images array but not only in one but all the document in all Feedback array not only one array image. I have tried this line of code in my django template but it doesn't display the right number of images. Code: <td>{{ product.Feedback.2 | length }}</td> Here is a screenshot of my Mongodb database to clarify my expalanation : Any help would be great !Thank you. -
Reset password email from django doesn't appear in my mailbox
Scenario: In my django application, admin should create users using 'username' and 'email', 'password' will be generated auto .Welcome email will be sent to users with redirect link to reset password. Issue: after entering email for reset password the app should send email with link to confirm reset password. THE PROBLEM is the email it never show in user "inbox" but i can find it in app "outbox mails" How can i make it appear in user mailbox? Any Help or idea? I'm using: -Python3 -Django4 -enable two factor authentication(2FA) for Google account Settings.py: #SMTP Config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = "webapp@app.com" DEFAULT_FROM_EMAIL = "MyApp <no-reply@app.com>" EMAIL_HOST_PASSWORD = "******" APP/URLS: urlpatterns = [ path('',views.login_user, name ='login'), #login fonction path path ('user_logout',views.user_logout, name = 'logout'), #logout function path path('dashboard/', views.dashboard, name='dashboard'),# dashoard view path path ('daily',views.DailyView, name = 'dailydashboard'),#daily view depath path ('monthly',views.MonthlyView, name = 'Monthlydashboard'),#monthly view path path ('yearly',views.YearlyView, name = 'Yearlydashboard'), #yearly view path path("reset_password/", auth_views.PasswordResetView.as_view(template_name="password/password_reset.html"), name="reset_password"), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name="password/password_reset_done.html"), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_confirm.html"), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'), ] -
Foreign Key field cant not be save in Django
I have this two model that is related by a foreign key. I take response from a webhook regarding a transaction and save into the model. What i am trying to do is save the the foreign key element into the Transaction History but i keep getting error when data is about to be saved that Cannot assign "'1'": "TransactionHistory.level" must be a "Level" instance. model class Level(models.Model): name = models.CharField(max_length=200, null=True, blank=True,) fees_amount = models.PositiveSmallIntegerField() class TransactionHistory(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE, null=True, blank=True, ) student_full_name = models.CharField(max_length=120) transaction_id = models.CharField(max_length=120) student_id_number = models.CharField(max_length=120) amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2) status = models.CharField(max_length=120, null=True, blank=True) email = models.EmailField(max_length=120, null=True, blank=True) phone = models.CharField(max_length=120, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) View.py @csrf_exempt def webhook(request): # Verify if request came from Paystack if request.method == 'POST': response_data = json.loads(request.body) if response_data["event"] == "charge.success": transaction_id = (response_data["data"]["reference"]) if not TransactionHistory.objects.filter(transaction_id=transaction_id).exists(): status = (response_data["data"]["status"]) amountraw = (response_data["data"]["amount"]) student_full_name = (response_data["data"]["metadata"]["custom_fields"][0]["student_full_name"]) level = (response_data["data"]["metadata"]["custom_fields"][0]["level"]) student_id_number = (response_data["data"]["metadata"]["custom_fields"][0["student_id_number"]) email = (response_data["data"]["metadata"]["custom_fields"][0]["email"]) phone = (response_data["data"]["metadata"]["custom_fields"][0]["phone"]) amount = (str(int(amountraw) / 100)) if status == 'success': transaction = TransactionHistory( level=level, student_full_name=student_full_name, amount=amount, transaction_id=transaction_id, status=status, student_id_number=student_id_number, email=email, phone=phone, ) transaction.save() return HttpResponse(status=200) This is the error i get: raise ValueError( ValueError: Cannot … -
Django Taggit - insert hyperlink if the word in body matches with tag
I am using django-taggit to handle tags in my app. I am also using django-ckeditor in my body field. I'd like to implement a function or a decorator or anything that will look at the text in the body field, find automatically tags in the text, and insert hyperlink like this one: http://127.0.0.1:8000/tag/test1/. I am not sure where should I start and how to implement such a feature. I know that CKEditor offers such a feature and it can be found here but I believe that I need a premium version of CKEditor5, right? If it is free is there any other way to handle CKEditor configuration than React, Angular, and Vue? Can I use Boostrap to for setting up the link feature? -
Connect via a secure websocket WSS from Django project to Redis/Daphne
I am trying to connect a secure websocket WSS with Redis/Daphne from my Django-Project: new WebSocket('wss://myproject.com:9002/ws/myChat/') But it is not possible to connect. In the Browser-Console I always get the following error: myCode.js:36 WebSocket connection to 'wss://myproject.com:9002/ws/myChat/' failed This is the only error I see, e.g. Nginx (sudo tail -F /var/log/nginx/error.log) shows no related error. The Daphne and Redis-Services seem to work: Redis Status: redis-server.service - Advanced key-value store Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-04-07 08:44:07 CEST; 55min ago Docs: http://redis.io/documentation, man:redis-server(1) Process: 281 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS) Main PID: 381 (redis-server) Tasks: 4 (limit: 60) Memory: 4.1M CGroup: /system.slice/redis-server.service └─381 /usr/bin/redis-server 127.0.0.1:6379 Daphne-Service Config: [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/django_user/appdir/myProject ExecStart=/home/django_user/appdir/env/bin/python3 /home/django_user/appdir/env/bin/daphne -e ssl:9002:privateKey=/etc/letsencrypt/live/myproject.com/privkey.pem:certKey=/etc/letsencrypt/myproject.com/fullchain.pem myproject.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target Daphne-Service Status: daphne_myproject.service - WebSocket Daphne Service Loaded: loaded (/etc/systemd/system/daphne_myproject.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2022-04-07 08:44:04 CEST; 50min ago Main PID: 277 (python3) Tasks: 1 (limit: 60) Memory: 74.8M CGroup: /system.slice/daphne_myproject.service └─277 /home/django_user/appdir/env/bin/python3 /home/django_user/appdir/env/bin/daphne -e ssl:9002:privateKey=/etc/letsencrypt/live/myproject.com/privkey.pem:certKey=/etc/letsencrypt/live/myproject.com/fullchain.pem myproject.asgi:application Nginx-Config: upstream websocket{ server 127.0.0.1:6379; } server { server_name myproject.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django_user/appdir/myProject; } location / { include … -
How I can open page when click on user name in user list and his/her name show in page
I did the list page and user information page but how I can when click on user name in list it open page has name of that user and I can add user email and phone number information and save it in db so when open it again i can see the added information in the page. -
How to show MQTT data on Django webpage?
I am relatively new to Django and I am trying to figure out how I can display some mqtt data in realtime on a django webpage as the client. I have created a python generator that sends data to self created mqtt broker and all of that seems to be working. In my django project I have the following: import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): client.subscribe("TEST/#") def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) pass client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.username_pw_set("broker", password="pass") client.connect("127.0.0.1", 1883, 60) Here you can see me printing the payload that comes through but I can't seem to figure out a way to get this showing on the a webpage in realtime. Any help will be appreciated. Thank you! -
Django - List Filtering using a ForeignKey within a ForeignKey
I can filter the list of Bookings from "housing" using the "Housing" ForeignKey But I need to do it based on the h_type which uses the "HousingType" ForeignKey I am not sure of the correct terminology here but I think I am trying to use a ForeignKey within a ForeignKey, not sure how to accomplish this within the view. models.py class HousingType(models.Model): name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=True) class Housing(models.Model): h_type = models.ForeignKey('HousingType', null=True, blank=True, on_delete=models.SET_NULL) class Booking(models.Model): housing = models.ForeignKey('Housing', null=True, blank=True, on_delete=models.SET_NULL) views.py def view_bookings(request): housing = Housing.objects.all() bookings = Booking.objects.all() if request.GET: if 'housing_type' in request.GET: h_types = request.GET['housing_type'].split(',') bookings = bookings.filter(housing_type__name__in=h_types) h_types = HousingType.objects.filter(name__in=h_types) html template <a href="{% url 'view_bookings' %}?housing_type=apartments">Apartments</a> -
Show file contents to html page in django
I am running one shell script from django views.py. below is code def result(request): if request.method=="POST": process=subprcoess.Popen(cmd, shell=True, stdout=subprcoess.PIPE, stderr=subprcoess.PIPE, universal_newlies=True) while process.poll() is None: print(process.communicate()[0]) continue return render(request, 'result.html') Now here can able to get logs on file, instead directly need to redirect to html page. Could anyone please help here? Thank You. -
Django: add only permissions of specific application
I´m using django for my backend and this backend is managing multiple applications. For example i have app_a and app_b. for app_a i created a lot of custom permissions and groups. Now i want to give another user the permission to access the admin panel, but i wan`t that he can only add permissions and groups to users that belongs to app_a. I tried to use add_group or add_permission, but this is assigned to all apps. Thank you for support!