Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In need of clear explanation the usage of get_form_kwargs method in django
i have been working with django for quite a while now, trying to deepen my knowledge. Hence started using Generic Class Base Views, overriding some django methods and its been fun. However, i haven't been able to understand get_form_kwargs() method and its implementation. Will be most grateful if someone could share what it all entails succinctly or drop a link that perfectly explains its implementations and usage. -
Exception Value: name 'start_date' is not defined
I'm getting this error during my admin testing on save of a habit in my Habit app. I don't know what to add to this code that would satisfy a definition of 'start_date'. Will you please show me where I've gone wrong. Exception Value: name 'start_date' is not defined Exception Location: //models.py in duration, line 20 which is, a = datetime.strptime(str(start_date), date_format) class Habit(models.Model): name = models.CharField(max_length=60) goal_nbr = models.IntegerField(default=0, null=True, blank=True) goal_description = models.CharField(max_length=60, null=True, blank=True) start_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( User, related_name="habit", on_delete=models.CASCADE) @property def duration(self): date_format = "%m/%d/%Y" a = datetime.strptime(str(start_date), date_format) b = datetime.strptime(str(end_date), date_format) delta = b - a return f'{ delta } days' def __str__(self): return f"Goal Name: {self.name} Goal Target: {self.goal_nbr} Description: {self.goal_description} Duration: {self.duration} days Beginning: {self.start_date} Ending: {self.end_date}" -
how to display uploaded files or images on template in django3
I only see the file path in the template. I can't see the file itself. (django 3.x) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') model.py class EkleModel (models.Model): aKaydi = models.CharField(max_length=50, verbose_name='A KAYDI') bKaydi = models.CharField(max_length=50, verbose_name='B KAYDI') cKaydi = models.CharField(max_length=50, verbose_name='C KAYDI') upload = models.FileField(upload_to='media/%Y/%m/%d/', verbose_name='DOSYA YÜKLE') yuklemeTarihi =models.DateTimeField(default =timezone.now) views.py def index(request): girdiler = EkleModel.objects.filter(yuklemeTarihi__lte=timezone.now()).order_by('-yuklemeTarihi') return render(request, 'sayfalarUygulamasi/index.html', {'girdiler': girdiler}) index.html <img class="card-img-top" src="girdi.upload"> <h4 class="card-title">{{girdi.aKaydi}}</h4> <h4 class="card-title">{{girdi.bKaydi}}</h4> <h4 class="card-title">{{girdi.cKaydi}}</h4> <h4 class="card-title">{{girdi.yuklemeTarihi}}</h4> -
Django, error in manage.py when run migrate
I have the following message error when I try to run "python manage.py migrate, I don't understand where is my problem, someone could help me????": (v_env) C:\Users\Federico\Desktop\Prova test\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: Applying app.0004_income_date...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) ..... To help you to identify the problem I have attached below my setting.py. I don't identify any issue or code error: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!60gpatqgt*q&6da*u3m@0nq&ml-^c7d#$bijk_5ge%b7p@r0b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'djmoney', 'django_tables2', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = … -
How To add Linebreak on specific characters in django?
I Want To add Linebreaks after specific characters but i don't know how to do that! Here is the image Look at this image i want to add line breaks after 50 characters Here is my HTML FILE: {% extends 'blog/base.html' %} {% block content %} <div class="container mt-3"> <h3>{{ post.title }}</h3> <hr> {% if post.blog_img %} <div class="card-image" style="background-image: url({{ post.blog_img.url }}); height: 370px;background-size: cover;background-repeat: no-repeat;background-position: center center;"></div> <hr> {% endif %} <p>{{ post.content }}</p> <hr> <p>About <a href="{% url 'category' slug=post.category.slug %}">{{ post.category.name }}</a> By <a href="{% url 'profile' username=post.author.username %}">{{ post.author.username }}</a> Posted At: <strong>{{ post.timestamp|timesince }}</strong></p> </div> {% endblock %} Here is my views.py def detail(request,slug=None): post = get_object_or_404(Post,slug=slug) if post.status == 'published': context = {'post':post,} return render(request,'blog/detail.html',context) else: return redirect(index) -
Error while installing mysqlclient in py3
rohit@rohit:~/Desktop/django_project$ pip3 install mysqlclient Collecting mysqlclient==1.3.12 Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-6bic4vtr/mysqlclient/setup.py", line 17, in metadata, options = get_config() File "/tmp/pip-build-6bic4vtr/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-6bic4vtr/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-6bic4vtr/mysqlclient/ I've also tried install with version pip3 install mysqlclient==1.3.12, it shows same error. -
Which one is better Dot net or django
I am a fresher in IT sector so i am confused to choose dot net or django .Please give me advise what i will choose. In both of them which have more jobs and more salary. Please compare them in accordance of jobs and salary to. -
ValueError at /basic_app/register/
The view basic_app.views.register didn't return an HttpResponse object. It returned None instead. ... Please Help me I am tired to solve or find out this error even couldn't understand this that where it's located The view basic_app.views.register didn't return an HttpResponse object. It returned None instead. views.py from django.shortcuts import render # from django.http import HttpResponse from basic_app.forms import UserForm, UserProfileInfoForm # Create your views here. def index(request): return render(request, 'basic_app/index.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'basic_app/registration.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): # user = models.OneToOneField(User) user = models.OneToOneField(User, on_delete=models.CASCADE) # user = models.ForeignKey(User,models.SET_NULL,blank=True,null=True) # user = models.ForeignKey(User, on_delete=models.PROTECT) # additional profile_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username -
How to create a 'Text to HTML' generator app in Django?
I want to create this app but I have no clues on how I can get it done. I have tried googling for a solution but can't find any. Anyone help? -
I have configured every thing but django says page not found
can any one help me with this problem? this is my blog/urls.py: from django.urls import path from .views import * urlpatterns = [ path("/testTemplate", template_testing, name="testtemplate"), ] and this is my website/urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and this is blog/views.py: from django.shortcuts import render # Create your views here. def template_testing(request): return render(request, "blog/index.html", {}) every things looks OK but when I want to go to this url: 127.0.0.1:8000/testTemplate I get a page not found error. What is going wrong here? please help me! -
What *args, **kwargs doing in this save method overriding
I'm new to Django. I understand what are the usage of *args and **kwargs. And also know how to use them in method overriding. But, I don't understand what purpose they serve while overriding the save() method in a model class. My observation is that no number of arguments, either non-keyworded or keyworded, were assigned to them anywhere. Still why do I must use them and how. Have this example: class DemoModel(models.Model): title = models.CharField(max_length = 200) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.title) super(DemoModel, self).save(*args, **kwargs) Please explain. -
Use self in ModelForm fields
I have a Formview and pass the pk to the ModelForm. In the ModelForm i am not able to use self.pk in the queryset i define for the field: views.py [...] def get_form_kwargs(self): # Pass extra kwargs to DetailProductForm kwargs = super(DetailProduct, self).get_form_kwargs() kwargs.update({'pk': self.kwargs['pk']}) return kwargs forms.py class DetailProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): # get the pk from the FormView at set it as self.pk self.pk = kwargs.pop('pk', None) super(DetailProductForm, self).__init__(*args, **kwargs) # use self.pk in my queryset (there are more fields who use self.pk, this is just one as an example) field = forms.ModelChoiceField(queryset=Configuration.objects.filter(product__pk=self.pk), widget=forms.RadioSelect) class Meta: model = Configuration fields = ['field'] NameError: name 'self' is not defined How can i use self.pk for the fields? -
Replacing templates in [os.path.join(BASE_DIR, 'templates')]
Since I don't have a Template folder with all my HTML, I cant use 'template in 'DIRS': [os.path.join(BASE_DIR, 'templates')], I place all my HTML directly in the site folder. MySite ├── MySite │ └── settings.py <--`'DIRS': [os.path.join(BASE_DIR, 'templates')],` └── index.html How can I change the 'templates' in 'DIRS': [os.path.join(BASE_DIR, 'templates')], to take the HTML files directly from my site folder? -
Error: [dpkg: error: cannot access archive '/home/uzair38/Downloads/wineqq2012-2-longene.deb': No such file or directory]
I am getting the above error message while downloading Visual Studio on Ubuntu 14.04. Any help would be appreciated :) -
Django insert getlist data
I am selecting a mark for every student and every core value then sending all data back to the database, please help me guys.. I’m completely stuck with this problem, I tried to solve it for several days. my problem is i didnt get the right value of every mark is for student and which marks is for what core value here is my views.py for desc, i in zip(request.POST.getlist('marking'), request.POST.getlist('coredescription')): coredesc = corevalues[int(desc)] coredescription = CoreValuesDescription(id=coredesc) p = marking[int(i)] print(desc, p) s = StudentBehaviorMarking(id=p) for student in request.POST.getlist('student'): students = StudentPeriodSummary(id=student) V_insert_data = StudentsCoreValuesDescription( Teacher=teacher, Core_Values=coredescription, Marking=s, Students_Enrollment_Records=students, grading_Period=coreperiod, ) V_insert_data.save() i = +1 desc = +1 return render(request, "Homepage/updatebehavior.html") and here is my html <form method="post" id="DogForm" action="/studentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="hidden" value="{{teacher}}" name="teacher"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in corevalues %} <td colspan="8"><input type="hidden" value="{{core.id}}" name="core">{{core.Description}}</td> {% endfor %} </tr> <tr> {% for corevalues in corevaluesperiod %} <td colspan="4" style="font-size: 12px"><input type="hidden" value="{{corevalues.id}}" name="coredescription">{{corevalues.Description}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student's Name</td> {% for corevalues in period %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" … -
Django-rest-framework read url data
urls.py from rest_framework import routers router = routers.DefaultRouter() router.register('fan/<str:name>', FanView) urlpatterns = [ path(r'', include(router.urls)), ] view.py class FanView(viewsets.ModelViewSet): queryset = Fan.objects.all() serializer_class = FanSerializer def get_queryset(self): queryset = Fan.objects.all() print(self.request.query_params.get('name', None)) return queryset Hi i am trying to send name in djnago-rest-framework url. And reading the same in my viewSet. But, i am always getting None. I don't wants to send data like fan/?name=foo Please have a look Is there any way to achive that ? -
How do I make all the container sizes same and also how to set the images in a proper way?
enter image description here How do I set a standard container size and also how do I size the images in a proper way so that the clarity of the images dont disturb and also gives a good look. The images are of different sizes so dont know what to do exactly, should I set them to a standard size? or is there any better way? <div class="album py-5 bg-light"> <div class="container"> <div class="row "> {% for job in jobs.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img class = "card-img-top" src = "{{job.image.url}}"> <div class="card-body" > <p class="card-text" >{{job.summary}}</p> <div class="d-flex justify-content-between align-items-center"> </div> </div> </div> </div> {% endfor %} </div> </div> </div> -
Django - how to get Table that is connected to User?
I have a built-in table from Django, "Users". Every user is getting stored in there. Now, I have created another table called "Questions" - Questions contains personal questions (fields) that every User on their own should answer. They are connected OneToOne: class Question(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) So far it's working. I can create a Question object and then assign it to a user. But: How can I query the fields of Question that is assigned to a user? In the end I want to have a big HTML form that contains all these questions the user can answer. I have tried following: questions = request.user.question.objects.get(user=user) context = {'questions':questions} That does not work and results in AttributeError: Manager isn't accessible via Question instances. I am stuck here and don't know how to do this. If anyone can help me, thank you. -
Django Taggit error "too many SQL variables" how can i do limit query?
Hello i have a wallpaper website. Im using taggit. I have 200k tags and have 20k wallpaper. I want use related wallpapers in view like this def detail(request,slug): wallpaper = get_object_or_404(Wallpapers, slug = slug) category = Category.objects.all() similar_posts = wallpaper.tags.similar_objects()[:20] random.shuffle(similar_posts) return render(request, "detail.html", {"wallpaper": wallpaper, "category": category, "similar_posts": similar_posts, }) and i take "too many SQL variables" error. example wallpaper tags: anime, water, rain 15k+ wallpaper have anime tag How can i limit or filter query this related wallpaper items? -
How to solve content.Keywords.key_words: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples
So I wrote My first ChoiceFIeld Model I facing Some Isuues : from django.db import models from django.conf import settings from django.utils import timezone from django.utils.translation import gettext_lazy as _ class Keywords(models.Model): POLITICS = 'politics', SPORTS = 'sports', ENTERTAINMENT = 'entertainment', FOOD = 'food', LIFESTYLE = 'lifestyle', RANDOM = 'random', TOPIC = [ (POLITICS, _('News About Politics')), (SPORTS, _('News About Sports')), (ENTERTAINMENT, _('News About Entertainment')), (FOOD, _('News About Food')), (LIFESTYLE, _('News About Lifestyle')), (RANDOM, _('Random News')), ] key_words = models.CharField(max_length=2, choices=TOPIC, default=RANDOM,) This is the code i wrote. But when I am trying to makemigrations It gives me this error?message: content.Keywords.key_words: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. What I did wrong? Thanks Good People. -
How to migrate db in django using CI/CD with Google CloudSQL?
I have a django repository setup in gitlab and I am trying to automate build and deploy on google cloud using gitlab CI/CD. The app has to be deployed on App Engine and has to use CloudSQL for dynamic data storage. Issue that I am facing is while executing migration on the db, before deploying my application. I am supposed to run ./manage.py migrate which connects to cloudSQL. I have read that we can use cloud proxy to connect to cloudSQL and migrate db. But it kind of seems like a hack. Is there a way to migrate my db via CI/CD pipeline script? Any help is appreciated. Thanks. -
flutter's dio to access django's api 403
I use flutter's dio to access django's api, I have commented out 'django.middleware.csrf.CsrfViewMiddleware' , and added @csrf_exempt to the view function, but dio still reports a 403 error when accessing. The python version I use is 3.7.5, the django version is 3.0.3, the flutter version is 1.9.1 + hotfix6, and the dio version is 3.0.8 Here is the flutter code: enter image description here Here is the django code: enter image description here Here is the error: enter image description here -
How to deploy django Web application in windows IIS using AWS instance?
I'm currently working on the application which will call services to perform backend operations and I want to deploy those API'S in AWS instance using windows IIS. Can someone explain me the steps to deploy the same? -
How to silent Django's warning for 405 Method Not Allowed
I am working with Django Rest Framework, and each time there is a request resulting in 405 Method Not Allowed, an annoying warning will be printed in the console. I wonder if I can opt to silent this warning, since it is rather not helpful in my settings. -
How to call an API with images without store image in django Python
I built an API system using django which take ID card front and back image. It will output the OCR of the two images. If my system is not do OCR properly it will call another API to do the OCR. so, i have to send those image to that API. But the problem is i do not send those images to that API without store those images in my system but i do not want to store those image. How can i do that? Here is my code class OCR_API(APIView): parser_classes = (MultiPartParser,) def post(self, request, format=None): frontImg = cv2.imdecode(np.fromstring(request.FILES['nidFrontImage'].read(), np.uint8), cv2.IMREAD_UNCHANGED) backImg = cv2.imdecode(np.fromstring(request.FILES['nidBackImage'].read(), np.uint8), cv2.IMREAD_UNCHANGED) requestRefId = request.POST.get("requestReferenceId", "") data = do_my__ocr(frontImg,backImg,requestRefId) if data['status'] == 'FAILED': write_image_file("front_img_.jpg", mainfrontImg) write_image_file("back_img_.jpg", backImg) fr = "media/images/" + "front_img_.jpg" bc = "media/images/" + "back_img_.jpg" data = call_another_api_service(fr, bc, requestRefId) return Response(data,status=200, content_type="UTF-8") #another API function def call_another_api_service(frontImg,backImg,requestRefId): url = 'http:' files = {'Image': open(frontImg, 'rb')} response = requests.post(url, files=files) print(response.text) N.B: I do not want to store those image. I want to use variable like fronimg and backimg to call the API. please help