Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Iterate over CSV rows using pandas in a faster way
I'm trying to read a CSV file through file upload from html template, and iterating over the rows and creating model object. views.py @login_required def uploadStudents1(request): if request.method == 'POST': uploaded_file = request.FILES['document'] ext = os.path.splitext(uploaded_file.name)[-1].lower() if ext == '.csv': data_file = pd.read_csv( uploaded_file, parse_dates=['date_of_birth']) data_file.fillna('-', inplace=True) for _, row in data_file.iterrows(): Sem1Students.objects.create( fname=row['first_name'], lname=row['last_name'], reg_no=row['reg_no'], gender=row['gender'], birth_date=row['date_of_birth'], ) messages.success(request, 'Uploaded student details successfully!') return redirect('/students') else: messages.error(request, "Invalid file type. Please upload again.") return render(request, 'students/upload1.html') return render(request, "students/upload/upload1.html") However this process is really slow, it takes like 5-6 seconds to read and create 74 records. Is there any better way to do this, i.e make the process faster? -
Many to many relationships-django
I want to build a student portal with a admin page and a client page with django. Every Student should be enrolled in classes and they should have a grade for that class. This is my models.py class Course(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=50) courses = models.ManyToManyField(Course, through='courseInfo') def __str__(self): return self.name class courseInfo(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) grade = models.IntegerField() In the template I want to show the classes the students are enrolled in and the grades for those classes. Eventually I am going to set up a dynamic template syestem Here is my views.py from django.shortcuts import render from main.models import Course, courseInfo, Student def home(request): student_id = 1 context = { 'student': Student.objects.get(id=student_id), 'courses': courseInfo.objects.all().student_set.all } return render(request, 'facultyUi/student.html', context) and here is my template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% for course in courses %} {{ course.grade }} {% endfor %} </body> </html> I cant find any sulution so if anyone can show me what to do here I would very much apreciate it. Thank you. -
searchVector does not show errors but return empty post
i'm trying to add search bar in my django application using searchVector instead of showing the post of my model it return empty post in dashboard template. I'm using heroku postgres. i added this in to my INSTALLED_APPS 'django.contrib.postgres' the model: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = CloudinaryField(blank=False, null=False) description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=12, null=False, blank=False) price = models.CharField(max_length=30,blank=False) location = models.CharField(max_length=20, blank=False) def __str__(self): return str(self.category) the dashboard template: <div class="container"> <div class="row justify-content-center"> <form action="" method="get"> <input name="q" class="form-control me-2" type="search" placeholder="Search" aria- label="Search"> <br> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <br> <div class="container"> <div class="row justify-content-center"> {% for photo in photos reversed %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 style="color: yellowgreen; font-family: Arial, Helvetica, sans-serif;"> {{photo.user.username.upper}} </h2> <br> <h3>{{photo.category}}</h3> <h4>{{photo.price}}</h4> </div> <a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn- sm m-1">Buy Now</a> </div> </div> {% empty %} <h3>No Files...</h3> {% endfor %} </div> </div> the view: def dashboard(request): q = request.GET.get('q') if q: photos = Photo.objects.filter(category__search=q) else: photos = None photos = Photo.objects.all() context = {'photos': photos} return render(request, 'dashboard.html', {'photos': photos} ) -
How do I restart my backend server in ec2 instance using github actions
Pushed the code on master branch of git, the code inside ec2 is getting updated accordingly but now I need to restart my server how do I achieve it using github actions Here is my github workflow on: push: branches: [ master ] jobs: deploy: name: Deploying on EC2 instance runs-on: ubuntu-latest steps: - name: Checking the files uses: actions/checkout@v2 - name: Deploying to the Demo Server uses: easingthemes/ssh-deploy@main env: SSH_PRIVATE_KEY: ${{secrets.EC2_SSH_KEY}} REMOTE_HOST: ${{secrets.HOST_DNS}} REMOTE_USER: ${{secrets.USER}} TARGET: ${{secrets.TARGET_DIR}} -
Django display a dynamic json file content in template
I have a json file on Django server The file content is dynamically changing I don't want to store the json data as Django model in database My question is: is there a techinically low cost and efficient way to display the json content in Django template as a frontend webpage ? All I need is display the json data in Django app web page -
insert to the table inside loop or bulk insert with django
i need to insert all products in the Cart table to the table called (OrderItem), I have used this code: neworder.save() new_order_items = Cart.objects.filter(user=request.user) for item in new_order_items: OrderItem.objects.create( order=neworder, product=item.product, price=item.product.selling_price, quantity=item.product_quantity ) # decrease the product quantity from table order_product = Product.objects.filter(id=item.product_id).first() order_product.quantity = order_product.quantity - item.product_quantity order_product.save() this code above only inserted the first product from the cart inside the Item_orders table? Although I have used the loop? Thanks -
matching query does not exist Error in Django (OneToOneField)
Please help me I don't know what I am doing wrong I am getting an error Available_time matching query does not exist. I use here OneToOneField from the Available_time database from Sunday to Saturday. I don't understand why this error is showing. class Available_time(models.Model): timezone = models.TimeField(auto_now=False, auto_now_add=False) nickname = models.CharField(max_length=30, default='IST_time') def __str__(self): return str(self.nickname) class RMDatabase(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) date_at = models.DateTimeField(auto_now=True) country= models.CharField(max_length=100, blank=True) province = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=True) contact = models.CharField(max_length=100, blank=True) countryCode = models.CharField(max_length=100, blank=True) motherTongue = models.CharField(max_length=100, blank=True) secondSpokenLang = models.CharField(max_length=100, blank=True) secondSpokenLangReason = models.CharField(max_length=100, blank=True) interstedIn = models.CharField(max_length=100, blank=True) skillLevel = models.CharField(max_length=100, blank=True) qualification = models.CharField(max_length=100, blank=True) qualificationAwardedBy = models.CharField(max_length=100, blank=True) qualificationFile= models.FileField(upload_to='folder/') videolink = models.CharField(max_length=100, blank=True) preferredDayTime = models.CharField(max_length=100, blank=True) sunday= models.ManyToManyField(Available_time,blank=True, related_name='sunday') monday = models.ManyToManyField(Available_time, blank=True,related_name='monday') tuesday= models.ManyToManyField(Available_time,blank=True, related_name='tuesday') wednesday = models.ManyToManyField(Available_time, blank=True,related_name='wednesday') thrusday= models.ManyToManyField(Available_time,blank=True, related_name='thrusday') friday = models.ManyToManyField(Available_time, blank=True,related_name='friday') saturday = models.ManyToManyField(Available_time,blank=True, related_name='saturday') def __str__(self): return self.motherTongue **My view.py here I simple takin input from the user and save the database. the problem I facing from **if request.POST.get('sunday-evening'): to till end if conditions. if remove those lines then working fine. def MNFRM(request): x= RMDatabase() # if request.user.is_active: # if x.objects.filter(user_id=request.user).exists(): # return render(request, 'relationshipmanager/userexists.html') if request.method … -
django-tinymce changes internal urls
tinymce to manage my contents. it's ok, works but there is a small thing that i a curious to know is that why tinymce changes urls by it's own. for example: i put a link and using url like /post/post1 but whenever i check my url, tinymce makes it like: ../../../../../post/post1 however, it's ok and does not break my link, but that feels bad to see! this also happens for images Django:3.2.12 django-tinymce: 3.4.0 tinymce (by it's own): TinyMCE 5.10.1 -
django date input format is not interpreted properly
I am trying to setup a Model and a corresponding ModelForm with django containing a DateField/Input. from django.db import models class MyModel(models.Model): myDate = models.DateField() from django import forms class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = "__all__" widgets = { 'myDate': forms.DateInput(format=("%d/%m/%Y")) } But sadly, when I enter a date in the form that results out of MyModelForm, the day and the month get exchanged. E.g. 1/2/22 will result in January 2nd 2022 instead of feburary 1st 2022. What else do I need to do, so the date gets interpreted properly? -
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8)
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested docker: Error response from daemon: could not select device driver "" with capabilities: [[gpu]]. I am facing this error on mac while trying to run this command docker run --rm --gpus all -v static_volume:/home/app/staticfiles/ -v media_volume:/app/uploaded_videos/ --name=deepfakeapplication abhijitjadhav1998/deefake-detection-20framemodel How to solve this error? -
I get an error when I install the SWITIFY package, does anyone know what it means?
when I install the package sweetify, I get the following error Does anyone know what the reason is? I went through all the steps that were in the main dock Traceback (most recent call last): File "C:\Program Files\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\django\apps\config.py", line 228, in create import_module(entry) File "C:\Program Files\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\sweetify\__init__.py", line 1, in <module> from .sweetify import * File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\sweetify\sweetify.py", line 5, in <module> from .encoder import LazyEncoder File "C:\Users\nahid\PycharmProjects\fitshow\venv\lib\site-packages\sweetify\encoder.py", line 2, in <module> from django.utils.encoding import force_text ImportError: cannot import name … -
Fields of Nested serializers
In my nested serializer i want to show only movie name and exclude the other fields [ { "id": 2, "watchlist": [ { "id": 3, "platform": "Netflix", "title": "Martian", "storyline": "A lost astronaut of Mars survived", "average_rating": 4.1, "total_rating": 2, "active": true, "created": "2022-04-05T05:37:35.902464Z" }, { "id": 4, "platform": "Netflix", "title": "Intersteller", "storyline": "Finding new home", "average_rating": 0.0, "total_rating": 0, "active": true, "created": "2022-04-06T04:52:04.665202Z" }, { "id": 5, "platform": "Netflix", "title": "Shutter Island", "storyline": "Psycopath", "average_rating": 0.0, "total_rating": 0, "active": true, "created": "2022-04-06T04:52:51.626397Z" } ], "platform": "Netflix", "about": "streaming, series and many more", "website": "https://www.netflix.com" }, ] In the above data, "watchlist" is the nested serializer data i want to show only "title" and exclude all other data I have included WatchListSerializer class as "nested" serializer in the StreamPlatformSerializer class. I want that on "title should be shown, rest other fields should be excluded from nested serializer part" below is the code... class WatchListSerializer(serializers.ModelSerializer): # reviews = ReviewSerializer(many=True, read_only=True) platform = serializers.CharField(source='platform.platform') class Meta: model = WatchList fields = '__all__' # def to_representation(self, value): # return value.title class StreamPlatformSerializer(serializers.ModelSerializer): watchlist = WatchListSerializer(many=True, read_only=True) # watchlist = serializers.CharField(source='watchlist.title') class Meta: model = StreamPlatform fields = '__all__' after removing other fields it … -
Django middleware to check ios/android app version using request header
I have an app for both Android and iOS platforms which their backend is written with Django and Django-rest-framework . I've been asked to check header of requests are sent from Android/iOS apps which includes app version number and it should respond if it needs require to update the app or not. Because I have to check this for each request before it reaches the views, I guess I have to do it with the help of a middleware. Is there any middleware already written for this? Otherwise, how can I make a custom middleware for this purpose? -
Best way to provide admin role from Django REST to ReactJS
The default django user model has a is_superuser field. I would like to use this field to conditionally render components in react, i.e. get something like this: {isAdmin && <SomeReactComponent/> } What is the best way to do this? I have authentication through JWT-Tokens (SimpleJWT). Can I somehow use them for this purpose? -
i want to make a chained drop down of my django model
please i want a chained dropdown in such away that it is only when you click on country that state will also be displayed class PollForm(forms.ModelForm): class Meta: model = PollingUnitModel fields = ['name','country', 'state', 'lga','ward'] i have been thinking of using autocomplete but i don't understand how it works from dal import autocomplete from django import forms class PollinForm(forms.ModelForm): class Meta: model = PollingUnitModel fields = ('__all__') widgets = { 'country': autocomplete.ModelSelect2(url='country-autocomplete') -
drf-yasg, How to add model choices on api doc?
I have a model like this: class User(AbstractUser): PERMISSION_CHOICES = [ (0, 'boss'), (1, 'leader'), (2, 'bro'), (3, 'sis'), ] permission = models.SmallIntegerField( _('permission'), default=0, choices=PERMISSION_CHOICES, help_text=_('xxx') ) My Serializer is like this: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('permission', ...) Now I have the doc like below: I wanna show the 'boss'/'leader'/'bro'/'sis' in the red rectangle. I googled, but not found solutions, so here is the questions. -
How can I get path of 3rd party app in Django
I install django_celery_beat app in Django settings.py file INSTALLED_APPS = [ ..., 'django_celery_beat', ] It has its own locale dir. As I understand I need to add this path to LOCALE_PATHS in settings.py. How can I get it? Hardcoding is not an option, of cause. -
How can i multiselect in django admin dropdown on foreignkey data just like manytomanyfield?
models.py from django.db import models class Images(models.Model): def upload_path(instance, filename): return '/images/'.join([filename]) image = models.ImageField(upload_to=upload_path, blank=True, null=True) logits = models.BinaryField() #customer = models.ForeignKey(Customer ,on_delete=models.DO_NOTHING, default=None) class Customer(models.Model): customer_id = models.BigIntegerField(unique=True) first_name = models.CharField(max_length=300) last_name = models.CharField(max_length=300) images = models.ForeignKey(Images ,on_delete=models.DO_NOTHING, default=None) def __str__(self): return str(self.customer_id) My problem is i want to be able to assign multiple images to single user which should be possible because of ForeignKey but i don't seem to get it to work like that. I want multiselect field just like in manytomanyfield but in foreignkey field. -
Set the SECRET_KEY environment variable What should I do?
The configuration of my pole diagram is as follows. maninapp ㄴ mainapp ㄴsettings ㄴ init.py ㄴ base.py ㄴ deploy.py ㄴ local.py .env manage.py if you run python manage.py runserver, django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable It looks like this base.py .. . . BASE_DIR = Path(file).resolve().parent.parent to BASE_DIR = Path(file).resolve().parent.parent.parant manage.py . . . os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainapp.settings.local') to os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainapp.settings') There is also a SECRET_KEY key in .env. What should I do? -
href not accepting loop Django
<table id="tabledata" class="tablecenter" style=" position: static; top:50%;"> <tr> <th>Username</th> <th>Email</th> <th>Role</th> <th>Action</th> <th>Remove User</th> </tr> {% for user in all %} <tr> <td>{{user.first_name}} {{user.last_name}}</td> <td>{{user.email}}</td> <td>{% if user.is_staff %} Admin {% else %} Practitioner {% endif %}</td> <td><a class="openButton" onclick="openForm()">Edit</a></td> <td><a href="{% url 'delete_user' pk=user.id %}" class="openButton">Delete</a></td> </tr> {% endfor %} After running the server on local, the page gives syntax error. enter image description here -
URL linking in django is getting failed
Error in line 13, the system shows. It is in Home page of blog project. <h1>Posts</h1> <ul> {% for post in object_list %} <li> <a href=" {% url 'article-detail' post.pk %} "> {{ post.title }} </a> {{ post.author.last_name }} {{ post.author.first_name }} <br /><br /> </li> {{ post.body }} <br /><br /> {% endfor %} </ul> In views.py class AddPostView(CreateView): model = Post template_name = 'add_post.html' fields = '__all__' and in urls.py urlpatterns = [ path('', HomeView.as_view(), name='home' ), path('article/<int:pk>/{% post.title %}', ArticleDetailView.as_view(), name='article-detail'), path('add_post/', AddPostView.as_view(), name='add_post')] Can any one help me please? -
How we can access and save object value of foregn model as default value, if the field is empty while saving the related object model?
class ObjectSEO(models.Model): object= models.ForeignKey(Objects, related_name='seo', on_delete=models.CASCADE) meta_description = models.CharField(max_length=170, help_text="Please add product meta description, max length 170 characters", default="Some Texts" ) meta_keywords = models.CharField(max_length=250, help_text="Please add product keywords separated with comma", default="Some Texts" ) meta_name = models.CharField(max_length=70, help_text="object title" default = Objects.name) Here, I have two models, Objects and ObjectSEO. In ObjectSEO model > site_name column> I want to add foreign key Objects name as default value. How can I do this? Is my approach pythonic? -
Filtering out a foreignkey model out of a foreignkey model
Tryna filter all productimg objects of MainProduct but getting ValueError Cannot use QuerySet for "MainProduct": Use a QuerySet for "Product". but can't use slug or id to filter it out of Product cuz it's homepage home:view [doesnt work] #can't use slug here def home(request): mainproduct = MainProduct.objects.all() productimg = ProductImage.objects.filter( #wanna access all productimg objects of a single product i.e mainproduct product=mainproduct ) shop:view [works] def detail_view(request, slug): products = Product.objects.get(slug=slug) productimg = ProductImage.objects.filter(product=products) shop:model class Product(models.Model): name = models.CharField(max_length=150) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to='somewhere/') home:model class MainProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=50) -
Django, froms in admin are weird, passwords not getting hashed, like what should I do?
I am honestly losing my mind. I just wanted to make a custom user model with an extra field called "CV", and removing the first and lastname and let it be just "name", but... I want to give up programming at tihs point. I had no problem with these small things in the past, liek why is it not working now? I'm literally about giving up my entire programming "career" if you can call it that way... I linked the entire code... ```https://pastebin.com/PeJ4U8wu``` -
Django - profile creation based on is_staff
I am currently working on a job portal project, where I need to create 2 profiles based on is_staff field of default user model of django. one for job seekers and another one for employers (i.e user profile and company profile) I am a beginner to django. I have no idea how to do it, please help me.