Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django checkbox do not return nothing
I mading a project and i need to get checkbox values in sequence, but django do not return anything when that checkbox are unchecked. how can i do that return False instead of nothing? forms.py class myFormExemple(forms.Form): checkbox = forms.BooleanField(required=False) views.py def MyViewExemple(request): if request.method == 'POST': print(request.POST.getlist('checkbox')) context = { 'form': myFormExemple } return render(request, "cadastro/myHTMLTemplate.html", context) and myHTMLTemplate.html: <form method="post" id='form'> {% csrf_token %} {{form.checkbox}} <button type="submit">save</button> </form> -
About django operation templates display screen
About django operation templates display screen I use django to write duplicate content into the base_generic.html page (including navbar sidebar footer), but because base_generic.html is one page and polls_list.html is another page content, I hope they can be combined, but My current situation is that the base_generic.html page covers the polls_list.html page, and the polls_list.html page disappears directly, unless it is hidden {% extends "base_generic.html" %} , My polls_list.html page will come out. Can someone help me answer this question? I don't know where I am not familiar, and I missed the process of learning. Please help, thank you. views.py def polls_list(request): context = { 'title': 'test index', 'user': request.user, } return render(request, 'polls/polls_list.html', context) polls_list.html {% extends "base_generic.html" %} {% block head %} <title>list profile</title> {% endblock %} {% block content %} <div class="container-fluid background-color: red;"> <div class="row"> <p>{{ user }}</p> </div> <div class="row"> <h1>Author List</h1> {% if author_list %} <ul> {% for author in author_list %} <li> <a href="{{ author.get_absolute_url }}"> {{ author }} ({{ author.date_of_birth }} - {% if author.date_of_death %}{{ author.date_of_death }}{% endif %}) </a> </li> {% endfor %} </ul> {% else %} <p>There are no authors available.</p> {% endif %} </div> {# /* row #} … -
Sending email to a specific user using Django
How can I send an email from the superuser to a specific user (which I want to select from a dropdown list) using Django? -
A part of Passed context not rendering in template django
A part of context doesn't render in my template. I have function based view as def index(request): context = { 'blogs': BlogPost.objects.all(), } context['likes'] = 1 return render(request, 'index.html', context) inside template.html {% for post in blogs %} {{post.id}} {# this renders perfectly #} {% endfor %} {{ likes }} {# this part doesn't render #} what could be the error? I am unable to figure it out. -
How to output multiple options during Django shopping mall implementation
I am a student who is learning Janggo. I'm asking you a question because I have a question while processing shopping mall options. The data for the ongoing project are as follows. Cardigan has two options, Size and Color, and I want to use Select in the template to import the Value of Size and Value of Color separately. I want to know if this is possible. For example, I would like to write: I wonder if it's possible, and if possible, I'd appreciate it if you could let me know how it can be implemented. -
Get schema and options in Django Rest Framework
In a particular API that is used to manage production data for the visual effects and animation industry, there is a call in the python API to get the available fields for an entity (a model basically). I am looking at trying to get the same things from my Rest API to dynamically add new or remove attributes to a react frontend with the correct field types. Does something like this already exist in DRF or will I need to create a custom view to get this data from the meta on the model? An example response may be something like... {model: { field1: { type: "charField", choices: ["A", "B", "C"], default: "A", required: True }, field2: { type: "boolField", default: True, required: False } } Thanks! The Example API I mentioned: https://developer.shotgridsoftware.com/python-api/reference.html#shotgun_api3.shotgun.Shotgun.schema_field_read -
Django - Finding Subtotal
I am trying to create a page that displays a users events and there total hours and mileage. I can get the tables to display for each user but I cannot figure out how to sum up the hours and mileage for each. I have the following Model. class VolunteerRecord(models.Model): eventname = models.CharField(max_length=50, blank=False, default='') category = models.CharField(max_length=100, blank=False) hours = models.FloatField(blank=False) date = models.DateField(help_text=_('Enter the date of the event')) mileage = models.FloatField(blank=False, null=True, default=0.0) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) The following queryset in views.py records = VolunteerRecord.objects.filter(date__range=(first_day,last_day)).order_by('owner_id__username', 'date') records_list = list(records.values('id','owner_id__username', 'category', 'eventname', 'date', 'hours', 'mileage')) and the following in my html template {% regroup records_list by owner_id__username as byMember %} {% for owner_id__username in byMember %} <div class="content"> <h1>{{ owner_id__username.grouper }}</h1> <table class="table" border="1" style="width: 100%;white-space:nowrap;"> <tr> <th style="text-align:left">Category</th> <th style="text-align:left">Event Name</th> <th style="text-align:left">Date</th> <th style="text-align:right">Hours</th> <th style="text-align:right">Mileage</th> </tr> {% for record in owner_id__username.list %} <tr> <td>{{ record.category }}</td> <td>{{ record.eventname }}</td> <td>{{ record.date }}</td> <td style="text-align:right">{{ record.hours }}</td> <td style="text-align:right">{{ record.mileage }}</td> </tr> {% endfor %} <tr> <td colspan="3">&nbsp;</td> <td id="total_hours">[WHERE TOTAL HOURS PER USER GOES]</td> <td id="total_mileage">[WHERE TOTAL MILEAGE PER USER GOES]</td> </tr> </table> </div> <p>&nbsp;</p> {% endfor %} I am trying to solve for … -
Django: How to render a list horizontally on the index route
I'm building a Django application and ran into a problem rendering a list of categories horizontally on the index route. Here is my code: models.py class Category(models.Model): class Meta: verbose_name_plural = 'categories' name = models.CharField(max_length=255) def __str__(self): return self.name views.py def categories(request): return render(request, 'test_app/index.html', { 'categories': Category.objects.order_by('name').all() }) def category(request, category_id): category = get_object_or_404(Category, pk=category_id) listings = Listing.objects.filter(category=category).order_by('-timestamp').all() return render(request, 'test_app/index.html', { 'title': category.name, 'listings': listings }) index.html {% extends "layout.html" %} {% block body %} <div class="container-fluid"> <div class="card-columns mx-auto col-10"> {% for listing in listings %} <div class="mx-auto card h-100 mb-3" style="max-width: 480px"> <a href="{% url 'listing' listing.id %}"> <img class="card-img-top" src="{{ listing.image.url }}" alt="{{ listing.title }}"> </a> <div class="card-body"> <h5 class="card-title">{{ listing.title }}</h5> <p class="card-text">{{ listing.description }}</p> <class="card-text"><small class="text-muted">Posted in {{ listing.category }}</small> </div> </div> {% endfor %} </div> </div> {% endblock %} urls.py urlpatterns = [ path('', views.index, name='index'), path('categories', views.categories, name='categories'), path('categories/<int:category_id>', views.category, name='category'), path('listings/<int:listing_id>', views.listing, name='listing'), path('purchase/<int:listing_id>', views.purchase, name='purchase'), ] layout.html <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}My Site{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <ul class="nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'categories' %}">Categories</a> </li> <ul> {% for category in categories %} <li> <a href="{% url 'category' … -
How Do I continue working on a deployed Django project without deleting the database data?
I have deployed my django application on heroku. My application on heroku runs a command that adds data to my mySQL database on AWS daily. Now I want to continue working on the django app, and I want to test new code, but that will create new data which I do not want to be stored on the live database, instead I would like to use SQLlite for production. How would I switch back to the MySQL database that has all the real data once I am ready to deploy the new version of my django app, without deleting all the data on the live database? I know I can save the data in the current database using these commands and load it into SQLlite from MySQl: python manage.py dumpdata > datadump.json python manage.py migrate --run-syncdb python manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() python manage.py loaddata datadump.json But I'm not sure how I am meant to migrate back to the MySQL database without erasing the live MySQL Database's data when I redeploy. Any help would be much appreciated. -
why thumbnail are not displayed in img tag using the values() method in views?
I have a model with 10 fields. But in the template I just want to return four fields('slug', 'code', 'area', 'thumbnail') . To do this, I used the Values() in View. But the thumbnail is not displayed in img tag of template and the src of the photo is empty. views.py: def home(request): allVilla = Villa.objects.filter(status='p').values('slug', 'code', 'area', 'thumbnail')[:8] context = { 'allvilla': allVilla, 'allproduct': allproduct, } return render(request, "wooden/home.html", context) home.html (template): <div id="slider_villa_home" class="owl-carousel owl-theme box_slider_villa dir_left"> {% for v in allvilla %} <div class="item position-relative box_item wow flipInY"> <div class="position-absolute bg"></div> <img class="img_item" src="{{ v.thumbnail.url }}" alt="{{ v.code }}"> <p class="position-absolute p_item"> <b>{{ v.code }}</b> <br> <b>{{ v.area }}</b> </p> <a class="position-absolute link_item" href="{% url 'wooden:singlevilla' v.slug %}"> </a> </div> {% endfor %} </div> pls help -
DRF Serializer How do I place serialize my data and display
I have following Serializer I am facing problem with Json with serializing. I have user named daniel james and he have multiple subject like maths science I am providing nested serializer to fill all subject but based on subject users name also repeats below is more specific qsn class ListResultSerializer(ResultSerializer): user = serializers.CharField() semester = serializers.CharField() subject = serializers.SerializerMethodField() class Meta(ResultSerializer.Meta): fields = ( 'user', 'semester', 'subject', ) def get_subject(self, instance): return SubjectSerializer(instance).data And In my views.py I have done like this. class ListResultView(rest_generics.ListAPIView, UserMixin): serializer_class = serializers.ListResultSerializer permission_classes = (AllowAny,) def get_object(self): return self.get_user() def get_queryset(self): return usecases.ListResultUseCase( user=self.get_user() ).execute() I use usecases.py to filter the data here is further code class ListResultUseCase: def __init__(self, user: User): self._user = user def execute(self): self._factory() return self._result def _factory(self): self._result = Result.objects.filter(user=self._user) Now this is the Json I am getting right now from above code. [ { "user": "daniel james", "semester": "first", "subject": { "gpa": "a+", "subject": "maths" } }, { "user": "daniel james", "semester": "first", "subject": { "gpa": "A", "subject": "data structures" } } ] I want my json to be in this format [ { "user": "daniel james", "semester": "first", "subject": [ { "gpa": "a+", "subject": "maths" }, { … -
My apache server starts but then stops immediately
I am trying to put my django app on an Apache24 server but i when i start the server with httpd.exe it starts but then stops completely right after. I am guessing the error is in my configuration. httpd.conf Define SRVROOT “c:/apache24/Apache24” ServerName localhost Include conf/extra/httpd-vhosts.conf LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" httpd-vhosts.conf <VirtualHost *:80> ServerName localhost ServerAlias localhost WSGIScriptAlias / “C:/Users/Administrator/Desktop/myapp/myapp/wsgi_windows.py” <Directory C:/Users/Administrator/Desktop/myapp/myapp/> <Files wsgi_windows.py> Require all granted </Files> </Directory> wsgi_windows.py import os import sys import site from django.core.wsgi import get_wsgi_application # Add the app’s directory to the PYTHONPATH sys.path.append(‘C:/Users/Administrator/Desktop/myapp/’) os.environ[‘DJANGO_SETTINGS_MODULE’] = myapp.settings’ os.environ.setdefault(‘DJANGO_SETTINGS_MODULE’, myapp.settings’) application = get_wsgi_application() -
how to create payment source to be used with stripe subscription with invoice
I need to create a subscription in stripe where customers pay using invoices the receive to go to payment page so i dont have a customer card details which is required when i try to create a payment source for customer this is what i did def createStripeCustomer(profile,request): host=request.build_absolute_uri() parts=host.split('/') host=parts[0]+'//'+parts[2] source=stripe.Source.create( type='card', currency='gbp', redirect={'return_url':host + '/payments/success/'}, owner={ 'email': profile.user.email } ) customer=stripe.Customer.create( description="My First Test Customer ", email=profile.user.email, name=profile.full_name, phone=profile.phone_no, address={'line1':profile.address}, ) source = stripe.Customer.create_source( customer.id, source=source.id ) profile.stripe_customer=customer.id profile.stripe_source=source.id profile.save() and for subscription def createStripeSubscription(subscription): price=subscription.course.get_pay_price() stripe_price=stripe.Price.create( unit_amount=price, currency=subscription.course.currency, recurring={"interval": "week"}, product=subscription.course.stripe_product, ) stripe_subscription=stripe.Subscription.create( customer=subscription.student.stripe_customer, items=[ {"price": stripe_price.id, 'quantity': 1, }, ], metadata={ "subscription_pk": subscription.pk }, ) subscription.stripe_price=stripe_price.id subscription.stripe_subscription=stripe_subscription.id subscription.save() can anyone helps out plz to get people to enter their card through invoices -
Try to create a database with python Django and use it with React! Db does not display on my react wep app
I tried to use React and Python for creating a web app. I used Python and Django to create a DB which do not appear on my React website. All of this was made on a local server. To verify that my code work, I simultaneously start localhost 3000 and localhost 127.0.0.1.8000. I verify all the files and could not see the problem. In my console appear only this error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. GitHub repository-https://github.com/margelatufml/Problem-React-Python -
Invalid connection string attribute in Django
DATABASES = { "default": { "ENGINE": "mssql", "NAME": " DJANGOOSQL", "USER": "sa", "PASSWORD": "Daytek00", "HOST": "LAPTOP-KBFP4DGE", "PORT": "", "OPTIONS": {"driver": "ODBC Driver 11 for SQL Server", }, }, } -
WARNING: No metadata found in ./venv/lib/python3.9/site-packages on PyCharm
Let's point out I have I have not added any environment variables or touched the python paths. The environment variables, I used where added beforehand from another heroku branch. I was adding AWS_Software in the Project.settings, along with other software recommended by Django guide for heroku. when it needed to import storages when I ran pip freeze > requirements.txt this pops up: WARNING: No metadata found in ./venv/lib/python3.9/site-packages WARNING: No metadata found in ./venv/lib/python3.9/site-packages WARNING: No metadata found in ./venv/lib/python3.9/site-packages WARNING: No metadata found in ./venv/lib/python3.9/site-packages Never ever had this issue until now, committing too github and pushing to heroku has no problems. I don't want to mess around with the python files. I tried updating Pip and Django in the Python interpreter. Not luck with Django when getting to install on requirements.txt(below) asgiref==3.4.1 boto3==1.18.5 botocore==1.21.5 certifi==2021.5.30 charset-normalizer==2.0.3 click==8.0.1 dj-database-url==0.5.0 Django==3.2.5 django-admin-honeypot==1.1.0 django-heroku==0.3.1 django-storages==1.11.1 gunicorn==20.1.0 idna==3.2 Pillow==8.3.0 psycopg2==2.9.1 pytz==2021.1 requests==2.26.0 sqlparse==0.4.1 urllib3==1.26.6 whitenoise==5.3.0 Any possible solutions? -
How do I set a default user for blog posts in Django?
My Blog model has a User field like following: from django.contrib.auth.models import User class Blog: author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog', default=User('monty')) This works as in I can see 'monty' set as a default user in the admin interface when I create a blog post. However, when I make migrations, I get the following error: ValueError: Cannot serialize: <User: > There are some values Django cannot serialize into migration files. I also tried this: default=User.objects.filter(username='monty')) and that returns a slightly different error when I make migrations: ValueError: Cannot serialize: <User: monty> There are some values Django cannot serialize into migration files. Anyone know how do I get past this error? -
POST and GET Method in Django api including Django ManyToManyField
I have a model that includes the ManyToManyField field and I have to use this model in Django API (POST(Saving Data) and GET Method) Here is my code: models.py class medDetails(models.Model): name=models.CharField(max_length=1000) notes=models.CharField(max_length=1400) duration=models.CharField(max_length=100) serve=models.CharField(max_length=100) Where I am calling medDetails model as a ManyToManyField medicine = models.ManyToManyField(medDetails) serializers.py class ReportsSerializer(serializers.ModelSerializer): class Meta: model = report fields = ('id','user', 'patient','medicine','description', 'created', 'time') class medDetailsSerializer(serializers.ModelSerializer): class Meta: model = report fields = ('id','name', 'notes', 'duration', 'serve') views.py create = report.objects.create(user=user, patient=patient,medicine=request.data['medicine'],description=des,created=datetime.date.today(), time=str(datetime.datetime.now().hour) +':'+ str(datetime.datetime.now().minute)) Error Coming: Direct assignment to the forward side of a many-to-many set is prohibited. Use medicine.set() instead. -
Django runserver isn't updating after .py file changes
I am learning django and using manage.py runserver for a live server. When I make changes to html and css files in my project, I only have to refresh the web page to see the changes, but when I make changes to the .py files (views.py or urls.py for example) I have to stop and restart the live server manually before refreshing the web page to see the changes. Is there a setting that I can change to avoid this manual reset? I am using visual studio code in windows and the actual command I'm using is: python manage.py runserver -
Celery task doesn't save model
I have post_save signal, that holds task.delay(). Task contains some code, that ends with saving model. I handled recursion and I know, that task is succeeded. The problem is, in my task I change one field of a model, in logs of task I see correct info, but when I go to db or in Django admin, field contains info like "before celery task". So the question is, what's wrong. If need, can provide code. Code throws no exceptions. -
How to add custom select input options in a form in Webflow
I'm trying to create a table as a select input field in Webflow as the following: but I couldn't find any option to do that in Webflow, the options are showing like that: So is there a way to do it or should I use Django or React libraries to do it later in the implementation? -
Django test MEDIA return 404 whereas browser return 200
I'm trying to check default media file availability with django test but it's appear that is not working. By referring to this post my code bellow : @override_settings(DEBUG=True) class Test_ProfileMedia(TestCase) : def setUp(self) : self.client = Client(HTTP_HOST = '127.0.0.1:8000') self.password = F.password() self.profile = ActiveProfile(password = self.password) self.user = self.profile.account self.client.login( username = self.user.username, password = self.password ) print("") print("MEDIA_URL: " + settings.MEDIA_URL) print("MEDIA_ROOT: " + settings.MEDIA_ROOT) def test_profile_home_default_image_GET(self) : response = self.client.get(self.profile.image.url) self.assertEquals(response.status_code, 200) Test Result : test_profile_home_default_image_GET (core.tests.test_media.Test_ProfileMedia) ... MEDIA_URL: /media/ MEDIA_ROOT: /mnt/c/Users/CallMarl/Wsl/dev/website/application/media Not Found: /media/default/default_profile.png FAIL By standard client : curl http://127.0.0.1:8000/media/default/default_profile.png --output download % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 135k 100 135k 0 0 12.0M 0 --:--:-- --:--:-- --:--:-- 12.0M If anyone can help me understand my mistake. -
Creating a monthly table with a fix first column
I’m new to Django, Did a couple of tutorials (Django official documentation and Tango with Django), but a can’t find a solution to my problem. I want to create a table (Canvas) that: • Is created monthly. • Has a fix first column. • Allow the frontend users to create these monthly tables and add, edit and delete the data. Here is an example of the table: enter image description here I just need some guidance as where to start in term of: • How my database table should look like • How to create table forms PS: Sorry for the English, I’m Algerian. -
Different OpenCV augmentation output in local webcam and web app webcam
I'm trying to apply this image augmentation project in a web app. I tried this locally in my laptop and it worked well, but when I load it on my web app it failed to output the same result. I tried to print out the outputs in my terminal and it seems like it's working fine. class VideoTest(object): def __init__(self): self.cap = cv2.VideoCapture(0) self.cards = Card.objects.get(id=2) self.target_image = cv2.imread(self.cards.card_image.path) self.video = cv2.VideoCapture(self.cards.card_video.path) def __del__(self): self.cap.release() def get_frame(self): success, webcam_input_image = self.cap.read() success, video_image = self.video.read() hi, wi, ci = self.target_image.shape video_image = cv2.resize(video_image, (wi, hi)) detection = False frame_counter = 0 orb = cv2.ORB_create(nfeatures=1000) kp1, des1 = orb.detectAndCompute(self.target_image, None) target_image = cv2.drawKeypoints(self.target_image, kp1, None) augment_image = webcam_input_image.copy() kp2, des2 = orb.detectAndCompute(webcam_input_image, None) webcam_image = cv2.drawKeypoints(webcam_input_image, kp2, None) if detection == False: self.video.set(cv2.CAP_PROP_POS_FRAMES, 0) frame_counter = 0 else: if frame_counter == self.video.get(cv2.CAP_PROP_FRAME_COUNT): self.video.set(cv2.CAP_PROP_POS_FRAMES, 0) frame_counter = 0 success, video_image = self.video.read() video_image = cv2.resize(video_image, (wi, hi)) bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2, k=2) good = [] for m, n in matches: if m.distance < 0.75*n.distance: good.append(m) img_features = cv2.drawMatches(target_image, kp1, webcam_image, kp2, good, None, flags=2) print('len good', len(good)) if len(good) > 30: detection = True src_points = np.float32([kp1[m.queryIdx].pt for m … -
No module named 'rest_framework_simplejwt'
I am trying to connect rest_framework_simplejwt, i am using official documentation but i have error: No module named 'rest_framework_simplejwt' I am using django 3.1. I installed all need modules If i am starting my programm by command: "docker-compose run server poetry add djangorestframework-simplejwt" all working, but how can i start without this? I need to use "fab dev" settings.py only need: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } installed_apps.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework_simplejwt', ] LOCAL_APPS = [ ] INSTALLED_APPS += LOCAL_APPS LOCAL_MIGRATIONS = [app_path.split('.')[1] for app_path in LOCAL_APPS] MIGRATION_PATH = 'config.migrations.' MIGRATION_MODULES = {app_name: MIGRATION_PATH + app_name for app_name in LOCAL_MIGRATIONS} urls.py from django.conf import settings from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] if settings.DEBUG: import debug_toolbar from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ]