Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to conver this PHP sql query to Django queryset?
How to convert this php sql to django query set? I've been stuck for 3 days. Please help me -
Video recorded through OpenCV not loading on html
I am recording videos with the help of OpenCV. Now after the video is saved, I am trying to load that video into HTML, with the help of video and iframe tags, but it is not loading in either of the tags. I have saved the video in .avi/.mp4 format. Locally in VLC the videos are playing fine, but are not loading in HTML. For recording video with openCV, I have referred to : https://www.dynamsoft.com/codepool/web-camera-recorder-oepncv-flask.html. -
Who to post multiple options to database in Django?
I have a table that contains items and another table with a foreign key referenced with that table to check the post operation. A user adds an item to the cart. I am unable to find the way to post all the <options> in <select>. My problem statement is to send all the add <options> to my table that contains a foreign key. Table that contain items: Table in which I want to post data: models.py: from django.db import models from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from datetime import datetime, date from django.core.validators import MaxValueValidator, MinValueValidator import uuid # Create your models here. class Tbl_Category(models.Model): cat_Id = models.AutoField(primary_key=True) cat_Name = models.CharField(max_length=20, unique=True) def __str__(self): return self.cat_Name # def __str__(self): # return [self.cat_Id, self.cat_Name] class Tbl_Item(models.Model): item_Id = models.AutoField(primary_key=True) item_Name = models.CharField(max_length=30, unique=True) cat_Idf = models.ForeignKey(Tbl_Category,on_delete=models.CASCADE) item_Price = models.IntegerField() def __str__(self): return self.item_Id class Tbl_postchk(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) itmid = models.ForeignKey(Tbl_Item, on_delete=CASCADE) HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% load static %} <link rel="stylesheet" href="{% static 'css.css' %}"> <title>DATA COLLECTION</title> </head> <body> <div class="container"> <div class="order-screen"> <div class="element"> <label for="coffee-tea">Coffee-Tea</label> <select name="coffee-tea" id="coffee-tea" class="s"> {% for opt in all_A … -
django form gettting error while posting data
form.py while creating new data based on city getting error(\forms.py", line 709, in init super(IncentiveForm,self).init(*args,**kwargs) TypeError: init() got an unexpected keyword argument 'city_id') class IncentiveForm(forms.ModelForm): city_id = CityModelChoiceField( required=False, queryset=City.objects.all(), label='City', widget=Select2Widget) class Meta: model=Incentive fields= ['start_date','end_date','no_of_trips','incentive'] def __init__(self,*args,**kwargs): self.request = kwargs.pop('request', None) super(IncentiveForm,self).__init__(*args,**kwargs) views.py def incentive_form(request,city_id=None): city = City.objects.get(pk=city_id) create=Incentive.objects.filter(city_id=city_id) if request.method == 'POST': form=IncentiveForm(request.POST,city_id=city_id) if form.is_valid(): start_date=form.cleaned_data['start_date'] end_date=form.cleaned_data['end_date'] no_of_trips=form.cleaned_data['no_of_trips'] incentive=form.cleaned_data['incentive'] if create is not None: create.start_date=start_date create.end_date=end_date create.no_of_trips=no_of_trips create.incentive=incentive create.city_id=city_id create.save() messages.success(request,'Incentive data created successfully!') else: form=IncentiveForm() context={ 'menu_incentive': 'active', 'submenu_incentive_list': 'active', 'city_id': city_id, 'city': city, 'form':form, } return render(request,"hiringprocess/incentive.html",context=context) -
How to change table data with Django and Ajax
I have a pandas dataframe that I am displaying in a Django Template as follows views.py def display(request): if request.method == 'POST': temp_df_path = './temp_match.csv' option = 'all' animals_data = helper(temp_df_path, options=option) json_records = animals_data.reset_index().to_json(orient='records') data = [] data = json.loads(json_records) context = {'d': data, 'data_columns': animals_data.columns} return render(request, 'results.html', context=context) Here I am displaying a DataFrame filtered using the helper function. In the template I have a set of radio buttons with which I can change the option variable. Here is my template <div class="container center"> <div class="table_options action_panel_centered"> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3" checked> <label class="form-check-label" for="inlineRadio3">Show all animals</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1"> <label class="form-check-label" for="inlineRadio1">Show only carnivores</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2"> <label class="form-check-label" for="inlineRadio2">Show only herbivores</label> </div> </div> </div> <div class="container-fluid root center"> <div class="table_container"> <table class="table table-hover" id='results_table'> <tr> <th class="index_th">#</th> {% for col in data_columns %} <th>{{col}}</th> {% endfor %} <th class='action_cell'>Actions</th> </tr> {% if d %} {% for i in d %} <tr> <th scope="row"> {{forloop.counter}} </th> ... </table> </div> </div> I want to change the content using Ajax. How do I do that? I have an Ajax … -
form.html in Django CreateView
Below is my code. class ArticleCreateView(OwnerCreateView): model = Article fields = ['title', 'text'] class OwnerCreateView(LoginRequiredMixin, CreateView): """ Sub-class of the CreateView to automatically pass the Request to the Form and add the owner to the saved object. """ # Saves the form instance, sets the current object for the view, and redirects to get_success_url(). def form_valid(self, form): print('form_valid called') object = form.save(commit=False) object.owner = self.request.user object.save() return super(OwnerCreateView, self).form_valid(form) In my /home/JongRok/dj4e-samples/myarts/templates/myarts I have acticle_form.html {% extends "base_bootstrap.html" %} {% load crispy_forms_tags %} {% block content %} <p> <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Submit"> <input type="submit" value="Cancel" onclick="window.location.href='{% url 'myarts:all' %}';return false;"> </form> </p> {% endblock %} I don't understand How Django CreateView find form. I don't put form in ArticleCreateView and I don't have form.py. How Django CreateView find it self has a model form?? -
auth_middleware.<locals>.middleware() got an unexpected keyword argument 'user_id'
I am trying to apply my custom auth middleware in the url path that has id . But getting this error. from .views import Profile app_name = 'account' from employer.middlewares.auth import auth_middleware urlpatterns =[ path('dashboard/pages-profile/<int:user_id>', auth_middleware(Profile.as_view()), name='profile'), ] And my auth middleware is this: from django.http import HttpResponseRedirect def auth_middleware(get_response): def middleware(request): return_url = request.META['PATH_INFO'] if not request.session.get('user_id'): return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}') response = get_response(request) return response return middleware -
How to convert doc to pdf supported by all the operating systems using python
I want to convert my word doc file to pdf using Python. Most of the modules I tried creates pdf on win and mac machines but not on linux. What module should I use which will convert doc to pdf supported on all the platforms? -
django app static files are not loading on shared hosting (cpanel)
static files or my django project are not working when i try to access via domain name I'm using Linux based shared hosting cpanel. Here is the settings.py for static files. I run collectstatic command and now all site statics are collect in home/username/project_static but those files are not working on my site. Please help me in this regard or guide me correct process of static files for production STATIC_URL = 'domain.net' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'home/username/project_static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) MEDIA_URL = '' STATICFILES_DIRS =[ BASE_DIR/ 'static', "home/username/project_static/", ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
AttributeError: module 'authentication.views' has no attribute 'ajax_load_messages'
I am creating a clone twitter application for a project, very basic. no styling. As i started to implement a Direct Messaging. i encounter a problem. with the urls.py file. it seems to want a view of my ajax_load_messages from within authentication but i put that view within the chat app itself. i am unable to run server. what can i do to solve this? Image of urls.py file with error msg and directory visible -
How to set a loading page while Django views are loading
I have a Django app which has a view that pulls data from Bigquery before I render the data to the Frontend. This process of pulling data takes quite some time and it will load the frontend once the view is finished loading the data. Is there a way I could show a loading page while the Django Views are pulling the data then make it disappears once everything is ready? I tried using the code below: function onReady(callback) { var intervalId = window.setInterval(function() { if (document.getElementsByTagName('body')[0] !== undefined) { window.clearInterval(intervalId); callback.call(this); } }, 1000); } function setVisible(selector, visible) { document.querySelector(selector).style.display = visible ? 'block' : 'none'; } onReady(function() { setVisible('#app', true); setVisible('.loading', false); }); But it seems that it still waits for the data to load, then shows the loading page for 1-2 seconds then immediately loads the frontend. -
Django - Full test suite failing when adding in TestCase class, but full test suite passes when it is commented out and all individual TestCase pass
So this seems to be an issue talked about here and there on StackOverflow with no real solution. So I have a bunch of tests that all pass when run individual. They even pass when run as a full test suite, EXCEPT when I add in my TestCase ExploreFeedTest. Now ExploreFeedTest passes when run by itself and it actually doesn't fail when run in the full test suite as in running python manage.py test, it causes another test HomeTest to fail, which passes on it's own and passes when ExploreFeedTest is commented out from the testsuite. I hear this is an issue with Django not cleaning up data properly? All my TestCase classes are from django.test.TestCase, because apparently if you don't use that class Django doesn't teardown the data properly, so I don't really know how to solve this. I'm also running Django 3.2.9, which is supposedly the latest. Anyone have a solution for this? ExploreFeedTest.py from django.test import TestCase from django.urls import reverse from rest_framework import status class ExploreFeedTest(TestCase): -
No input passed from django form in modal to model
I want to write a mock payment function and database that receives card information from Django and proceeds with payment. So, I wrote the code as follows, and even if I input information in the modal and press the charge button, the instance does not enter the Payments model. html <!-- Modal --> <div class="modal fade" id="myFullsizeModal" tabindex="-1" role="dialog" aria-labelledby="myFullsizeModalLabel"> <div class="modal-dialog modal-fullsize" role="document"> <div class="modal-content modal-fullsize"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Payment</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% for cart_item in cart_items %} <div> <h2>주문내역</h2> Title : {{ cart_item.timetable.movie.title_eng }} <br> Qty : ${{ cart_item.timetable.ticket_price }} x {{ cart_item.quantity }} <br> Your total is : <strong>${{ total }}</strong> <br> </div> {% endfor %} <br> <br> <br> <form action="{% url 'cart:charge' %}" method="post">{% csrf_token %} <div> <h2>Card Number</h2> <input type="text" class="moveNumber" onKeyup="inputMoveNumber(this);" maxlength="4" placeholder="****"/>&nbsp;-&nbsp; <input type="text" class="moveNumber" onKeyup="inputMoveNumber(this);" maxlength="4" placeholder="****"/>&nbsp;-&nbsp; <input type="text" class="moveNumber" onKeyup="inputMoveNumber(this);" maxlength="4" placeholder="****"/>&nbsp;-&nbsp; <input type="text" class="moveNumber" maxlength="4" placeholder="****"/> </div> <br> <div> <h2>Validity</h2> <!-- maxlength의 값을 5로지정하여 다섯자리 이상의 값이 등록되는것을 막는다. --> <input type="text" class="validThru" onKeyup="inputValidThru(this);" placeholder="MM/YY" maxlength="5"/> </div> <br> <h2>CVC</h2> <input type="text" maxlength="3" placeholder="***"/> <br> <h2>Password</h2> <input type="text" maxlength="2" placeholder="**"/> <div> <input type="submit" value="charge"> </div> </div> </form> <div class="modal-footer"> <button type="button" class="btn … -
Deploy Django with SSL without Nginx
Is it possible to deploy a django project without using third party tools like nginx or apache just to serve up https:// webpages? Being forced to setup a reverse proxy or some other web server just to serve https seems a bit overkill. -
Highlight item of navigation lost after ajax call
I make highlight item on navigation by: {% if "/people/" in request.path %}class="active"{% endif %} It worked on the first time page loading. request.path = "/people/" After, i call a ajax function, certainly not re-render navigation, but highlight is lost. request.path = "/people/update/" -
Django adding data into db thru form doesn't including primary key
I'm new to Django and was building a project with it right now. I faced a problem while adding a new data thru form into db but it doesn't autofield with a new primary key and replace with a null instead. here is my code: models.py from django.db import models class recipe_models(models.Model): PKG_type_choice = ( ('BGA', 'BGA'), ('POP', 'POP'), ('Avalon', 'Avalon'), ('mNAND', 'mNAND'), ('NAND', 'NAND'), ) PKG_type = models.CharField(max_length=100, blank=True, null=True, choices=PKG_type_choice) Recipe_name=models.CharField(max_length=100, blank=True, null=True) DID=models.CharField(max_length=100, blank=True, null=True) Lead_count=models.IntegerField(blank=True, null=True) Die_qty=models.IntegerField(blank=True, null=True) Package_Width=models.FloatField(blank=True, null=True) Package_Height=models.FloatField(blank=True, null=True) Z_height=models.FloatField(blank=True, null=True) HVM_Status_choice = ( ('YES', 'YES'), ('NO', 'NO'), ) HVM_Status=models.CharField(max_length=100, blank=True, null=True, choices=HVM_Status_choice) # HVM_Status=models.CharField(max_length=100) Machine_choice = ( ('AIHEXAM-0005', 'AIHEXAM-0005'), ('AIHEXAM-0011', 'AIHEXAM-0011'), ('AIHEXAM-0012', 'AIHEXAM-0012'), ('AIHEXAM-0013', 'AIHEXAM-0013'), ('AIHEXAM-0014', 'AIHEXAM-0014'), ('KT390-0002', 'KT390-0002'), ('KT390-0002', 'KT390-0003'), ('KT390-0005', 'KT390-0005'), ('KT390-0006', 'KT390-0006'), ('KT390-0007', 'KT390-0007'), ('KT390-0012', 'KT390-0012'), ('KT390-0013', 'KT390-0013'), ('KT390-0016', 'KT390-0016'), ('KT390-0014', 'KT390-0014'), ('KT390-0020', 'KT390-0020'), ('KT390-0026', 'KT390-0026'),) Machine=models.CharField(max_length=100, blank=True, null=True, choices=Machine_choice) Owner=models.CharField(max_length=100, blank=True, null=True) Workweek=models.CharField(max_length=100, blank=True, null=True) Note=models.CharField(max_length=2000, blank=True, null=True) class Meta: db_table = 'avi_recipe' def __str__(self): return self.Recipe_name + ' ' + self.Machine forms.py from django import forms from .models import recipe_models from django.db import models class RecipeForm(forms.ModelForm): class Meta: model = recipe_models fields = ['PKG_type', 'Recipe_name', 'DID', 'Lead_count', 'Die_qty', 'Package_Width', 'Package_Height', 'Z_height', 'HVM_Status', 'Machine', 'Owner', 'Workweek', 'Note'] Any … -
Django filtering relation in ListView
Given the models class TaskGroup(models.Model): name = models.CharField(max_length=256) class Task(models.Model): name = models.CharField(max_length=256) group = models.ForeignKey(TaskGroup, on_delete=models.CASCADE) completed = models.BooleanField(default=False) completed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) and the list view class TaskGroupListView(ListView): model = TaskGroup I'd like to display the list of task groups with corresponding tasks. The catch is - I only want to show the tasks that have not been completed or have been completed by the user, or if the user as the attribute user.type == "ADMIN" set show all groups and all tasks. Right now I have a template that looks like: {% for taskgroup in object_list %} <h1>{{ taskgroup.name }}</h1> <ul> {% for task in taskgroup.task_set.all %} <li>{{ task.name }}</li> {% endfor %} </ul> {% endfor %} I know that I can modify the queryset of a list view by overriding get_queryset like: def get_queryset(self): if self.request.user == "ADMIN": return TaskGroup.objects.all() else: ... but I'm not sure how to go about filtering the Task relations on the TaskGroups in the else clause. I've thought about creating a manager subclass for Task that can filter based on .completed and .completed_by that I can use in the template but that seems against the philosophy of Django - I'd … -
Can I use PHP-hashed password with Django?
I am working on building an Android App, which uses PHP backend. So everytime a user registers and enters password, it is hashed using bcrypt. Subsequently, I am building a Django based admin panel for the same on the web. What can be the best approach to build/customise the authentication system in Django, so that it can authenticate with the passwords generated through bcrypt? Important: I do not have the option to change the PHP backend of my Android app. -
Updating fiield in PostgreSQL table using .update() not working in django
I've been trying to update the invo_payment_method value from a table called Invoices. This is the code that I currently have to try to achieve this: if total_payments_for_invoice.all().count() == 1: invoice_object = Invoice.objects.get(slug=slug) invoice_object.invo_payment_method = request.POST.get('payment_method') invoice_object.save() So what I'm trying to do is if it's the first payment for the invoice I want to get invoice_object which has the slug of the invoice that just got a payment and update the invo_payment_method field in the table and save the changes. But that's not working. I also tried doing the following: if total_payments_for_invoice.all().count() == 1: Invoice.objects.filter(slug=slug).update( invo_payment_method=request.POST.get('payment_method')) And it's not working either. After that I tried adding a the following to the code above: if total_payments_for_invoice.all().count() == 1: Invoice.objects.filter(slug=slug).update( invo_payment_method=request.POST.get('payment_method')).save() And this one actually updated the value in the database, but it made the webpage crash because of the following exception: AttributeError: 'int' object has no attribute 'save'. In case more information is needed, if I print the value of Invoice.objects.get(slug=slug) I get the following: INV-bb1c 21. And if I print the value of Invoice.objects.filter(slug=slug) I get the following: <QuerySet [<Invoice: INV-bb1c 21>]>. In both cases I'm getting the invoice number which is INV-bb1c and the invoice pid which is … -
How to manage & register different types of users with different fields and Profiles in Django?
【BACKGROUND】 I am working on a project integrating Django and NextJS using Django REST-API Framework. I configured the default user model by creating Custom User Model where email address is the unique and primary field. In my project, there are 3 different types of users : Client, Student & Teacher. In my custom user account models file, I have set a is_usertype flag for each user type; for example: is_client, is_student, is_teacher. Each user types (Client, Student, Teacher) have different profiles containing different fields. The extra fields for each user types are as follows: Client Profile: country Student Profile: interests Teacher Profile: bio I have one common user registration API Endpoint for all types of users which is http://127.0.0.1:8000/user-api/register. At the time of registering user, the specific user type is set to True. For example, if I am trying to register a Client user type, I need to set is_client flag to True, for a Student user type, I need to set is_student flag to True and for a Teacher user type, I need to set is_teacher flag to True. When I am trying to register a specific user type, the user type is not getting registered. I am using … -
django channels. subscribe channel of certain user in receive_json
in JsonWebsocketConsumer i using this code for subscribe socket of certain user (which is not current socket) for messages from new dialog def receive_json() # ... async_to_sync(self.channel_layer.group_add)(f'dialog-{dialog_id}', f'user-{dialog.answerer.id}') # ... but it not works because, i can't just set channel_name like that: def connect(self): self.channel_name = f'user-{self.scope["user"].id}' can i somehow subscribe socket of other user to group, having user_id? -
How do I use a html file to link to another html file?
homepage_template.html <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8"> <meta name="keywords" content="HTML, CSS"> <meta name="description" content="My programing resume in the form of a django project built from scrarch"> <title>Resume Homepage</title> </head> <body> <h1>Welcome To My Django Resume Webpage !&copy;</h1> <img src="main_photo.jpg" alt="Image Unable To Be Displayed"> <p </p> <h2>Coding Projects </h2> <a href="homepage_photos/test.html"> text!</a> </body> </html> The above html file is located in a folder named templates. In templates I have another folder named homepage_photos. In homepage_photos I have a html file called test.html Consider when I'm viewing homepage_template.html (on my website) that my URL looks like this - "mywebsite" Whenever the link is clicked the URL would go to mywebsite/homepage_photos/test.html instead of just going to the file itself Side note: I'm using Django -
Django admin display many-to-many field as links
Trying to get my Django admin to display a list of related objects as links to those objects. These objects are related through a many-to-many relationship. Using a combination of this answer and this answer, I came up with: class MyObject(models.Model): related = models.ManyToManyField(RelatedObject) class RelatedObject(models.Model): name = models.CharField(max_length=191) class MyAdmin(admin.ModelAdmin): list_display = ("rel") def rel(self, obj): return[self.link_to_object(related_object) for related_object in obj.related.all()] def link_to_object(self, obj): link = reverse("admin:<app>_relatedobject_change", args=[obj.id]) return format_html(f"<a href={link}>{obj.name}</a>") However, this gives me a list of hrefs, not a list of links. If I instead change: def rel(self, obj): return self.link_to_object(obj.related.get(pk=1)) It returns a nice link where that relationship exists (i.e. related.get(pk=1) in obj.related.all()). Is there a way to get admin to return a list of links? I'll note that there's also this linkify method floating around, but it only works for a ForeignKey, not many-to-many, and I don't see how to adapt it. -
Assign permission to all objects of a type using django-guardian
I'm trying to make a group with django-guardian that has access to all objects of a type instead of a single object, like such: from guardian.models import UserObjectPermission from django.contrib.contenttypes.models import ContentType from apps.myapp.models import Website # Create groups that can edit websites (admin can edit every website, the other group only a specific website) admins = Group.objects.create(name='admins') website_44_editors = Group.objects.create(name='website_44_editors') # This works, assigning permission to edit website 44 to the correct group website_44 = Website.objects.get(pk=44) UserObjectPermission.objects.assign_perm('change_website', website_44_editors, obj=website_44) ####### This doesn't work, as an object is needed ####### UserObjectPermission.objects.assign_perm('change_website', admins) Any way to do this? Google / StackOVerflow Searches only yield unrelated results -
How to configure SSL with docker-compose & github actions?
I'm trying to figure out how could I deploy to server my Django app using docker-compose & github actions. I've made some progress, in fact, the project works on http. But I need to make it work with SSL (https://). I tried to use certbot, but couldn't make it work :( This is my docker-compose file version: '3.8' services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env web: image: madrider/yamdb_final restart: always volumes: - static_value:/code/static/ - media_value:/code/media/ depends_on: - db env_file: - .env nginx: image: nginx:1.19.3 ports: - "80:80" volumes: - ./nginx/default.conf:/etc/nginx/conf.d/default.conf - static_value:/var/html/static/ - media_value:/var/html/media/ depends_on: - web volumes: static_value: media_value: And this is nginx/default.conf server { listen 80; server_name 127.0.0.1; location /static/ { root /var/html/; } location /media/ { root /var/html/; } location / { proxy_pass http://web:8000; } } And, finally, my Github actions yml-file name: Django-app workflow on: [push] jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python -m pip install --upgrade pip pip install flake8 pep8-naming flake8-broken-line flake8-return flake8-isort pip install -r requirements.txt - name: Test with flake8 run: | python -m flake8 - name: Test with pytest run: …