Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-simple-captcha always showing invalid capcha in wizardview from django formtools
I am using django-formtools to split the registration form. I have added django-simple-captcha for captcha verification. The captcha is invalid always. I think it is becuase the form field name is '1-captcha_0' in django form wizard. Is there any way to fix this? -
OpenEDX how to complete invisible registration with OAuth?
I'm setting up OpenEDX with specific parameters. First of all, I don't want it to be full open to people, so I've disabled the registration form by setting ALLOW_PUBLIC_ACCOUNT_CREATION to false in lms.env.json. Then I wanted it to only be accessible through my OAuth2 service. I've set up a python module according to this documentation page The login part works fine, but then OpenEDX is stuck to the registration page, because my OAuth2 service doesn't give the user's Country field, which is a mandatory field for OpenEDX. I just want this part to work flawlessly, so here are my questions: Is there a way to remove the "Country" field from the list of the mandatory fields for registration? If there's no way to do so, can my python module give a default country information about the user so the registration completes in an invisible way ? If there's still no way, can I enable the registration form but disable the integrated login form to leave only the OAuth way ? Finally, if none of the solutions above work, what can I do? Thanks in advance for the precious help everyone here is giving! -
Numerical operation with absulute value in Django
I tried to add three different absolute value in my template but I got always 0. I try to explain it: My values: a=-7 b=8 c=10 I tried this method with Django mathfilter: {{a|abs|add:b|abs|add:c|abs}} I always got 0 because I think the mathfilter can't handle many abs value. Could anyone give me an advice which help me to do this operation? Thnak you in advance! -
Path Specific Cookie in Django
i want to create cookie based authentication depends on path , so simply for testing i have create two views and set cookies respectively View 1 Cookie With globalLy available View 2 Cookie With Specific But the problem in both view only global cookie is available View 1 View 2 You can see both cookie have same name but different path, but when we get cookies only global cookie is available if i display request.META.get('HTTP_COOKIE')) then all cookie are display but not in request.COOKIES.get('last_visit') please help, i have tested in php , it works fine but not in python django -
fatal error: portaudio.h: No such file or directory error: command 'gcc' failed with exit status 1
i am using windows 10 and when i am running the commang - git push heroku master getting this erro please solve my problem from 4 days i am searching the solution but didn't get Running setup.py install for PyAudio: started remote: Running setup.py install for PyAudio: finished with status 'error' remote: Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-qx34haso/PyAudio/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-mydedmjn-record/install-record.txt --single-version-externally-managed --compile: remote: running install remote: running build remote: running build_py remote: creating build remote: creating build/lib.linux-x86_64-3.6 remote: copying src/pyaudio.py -> build/lib.linux-x86_64-3.6 remote: running build_ext remote: building '_portaudio' extension remote: creating build/temp.linux-x86_64-3.6 remote: creating build/temp.linux-x86_64-3.6/src remote: gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/app/.heroku/python/include/python3.6m -c src/_portaudiomodule.c -o build/temp.linux-x86_64-3.6/src/_portaudiomodule.o remote: src/_portaudiomodule.c:29:23: fatal error: portaudio.h: No such file or directory remote: compilation terminated. remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-qx34haso/PyAudio/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-mydedmjn-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-qx34haso/PyAudio/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to shoppingwave. remote: To https://git.heroku.com/shoppingwave.git ! … -
How to replace placeholders in placeholders (variables)?
In a Django template, I'd like to add text from a model field. This text field can be understood as text-template itself. It may look like: Dear {{user}}, thank your for... Regards, {{sender}} This text field is available as emailtemplate inside a normal Django template. The fields from above (user=Joe, sender=Alice) are available as well. {% extends 'base.html' %} {% block content %} {{ emailtemplate }} {% endblock %} The output shall be as follows Dear Joe, thank your for... Regards, Alice I have no clue how to do this with built-in methods. My only idea is to parse emailtemplate manually before I hand it over to the template engine, thus inside the view. But I'm sure, I'm not the first one with that problem. -
How to define a relation N:N in python3+django2?
I am following this tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial02/ In this tutorial, I can create a class Question and a class Choice. One question contains multiple choices, but one choice belongs to only 1 question. So following the tutorial, there is a foreign_key in the class Choice that refers to the class Question, and the variable choice_set will be automatically created. Now I want to modify that a choice can belong to multiple questions as well. How should I do that? Thanks, -
Building post request with Django Test Client post data
when posting a form using my browser the post request from the views side looks like this GOOD: POST <QueryDict: {u'form_data': [u'{"kkz":"ALF" ....]}> When using test client like this data = { 'form_data': { "kkz": "ALF", .. } } .... c = Client() response = c.post('/wizzard/....', data=json.dumps(data), content_type="application/x-www-form-urlencoded") I'm getting this BAD: POST <QueryDict: {u'{"form_data": {"kkz": "ALF" ...}> Which the view can't handle. Where am i wrong ? -
Django Cannot upload images and get it to update the DB
So I'm trying to make it possible for users to update their Avatar/Profile image by allowing them to upload their image + I want to implement an image cropper so they can crop the image to a ratio of 1 to 1. All tho I think the first thing is making it possible to upload. I've searched around trying to make it possible but I think I've almost been everywhere. The thing is the image field I'm using is like an extension to the User table I basically called it extendeduser that has all the extra information included in it. View.py @login_required def useravatar(request, user_pk): if request.method == 'POST': form = UpdateProfileForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): user = form.save() user.refresh_from_db() user.extendeduser.avatar = form.cleaned_data('avatar') user.save() messages.success(request, 'Your avatar was successfully Uploaded!') return redirect('useravatar', user_pk=request.user.pk) logged_in_user = get_object_or_404(User, pk=request.user.pk) requested_user = get_object_or_404(User, pk=user_pk) driverslicence = DriversLicenceCategories.objects.all() feedback = FeedbackSupportForm() password = PasswordChangeForm(request.user) avatar = UpdateProfileForm(instance=request.user) context = { 'avatar' : avatar, 'logged_in_user': logged_in_user, 'requested_user': requested_user, 'feedback' : feedback, 'password' : password, } return render(request, 'user/avatar.html', context) Models.py class ExtendedUser(models.Model): avatar = models.ImageField(upload_to='users/avatars', default='static/img/userpreload.png') background = models.ImageField(upload_to='users/backgrounds', default='static/img/userpreload.png') Forms.py class UpdateProfileForm(forms.ModelForm): postal_code = forms.CharField(max_length=10, required=True) phone_number = forms.CharField(max_length=16, required=True) phone_number_show = forms.BooleanField(required=False) avatar … -
matching query does not exists - error in Django search
I have been struggling with this for a while now.I tried to implement Django search with pagination. Pagination works, but when I try to search something, I get this error: Course matching query does not exist. Here is the traceback: https://pastebin.com/jJp2hLUs And code: from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def pagination(request, data, num=10): paginator = Paginator(data, num) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) index = courses.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] return courses, page_range def search(request, slug): query = request.GET.get('q') if query: results = Course.objects.filter(Q(name__icontains=query), slug=slug) else: results = Course.objects.get() pages = pagination(request, results, num=1) context = { 'courses': pages[0], 'page_range': pages[1], 'query': query, } return render(request, 'courses/index.html', context) def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context) -
How to raise a custom form invalid error in wizardview from django formtools
I am using django-formtools to split the registration form. I have added Google ReCaptcha for captcha verification. I would wish to produce error in the form like the one in django UpdateView. Is there any method in django form wizard like messages.error(self.request, 'Invalid reCAPTCHA. Please try again.') return super(UpdateUserProfileView, self).form_invalid(form) -
how to use twilio video api python?
i would like to implement twilio video api in my django project but i didn't really understand the docs i managed to create a room i flowed this example from twilio.rest import Client api_key_sid = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" api_key_secret = "your_api_key_secret" client = Client(api_key_sid, api_key_secret) room = client.video.rooms.create(unique_name='DailyStandup') print(room.sid) after that what should i do ? how to access the room and start the chat -
Django : "stream" vs request.FILES["file"]
So I wanted to write a custom file upload parser as specified in docs. According to doc I implemented the parse method as class MailParser(BaseParser): """ parses email serialized data """ media_type = "multipart/form-data" def parse(self, stream, media_type = None, parser_context = None): """ Here I was trying to read stream """ but when I tried to read stream it additionally had following content ----------------------------488071469102781097692083 Content-Disposition: form-data; name="file"; filename="email_test.msg" Content-Type: application/vnd.ms-outlook < actual content here > ----------------------------488071469102781097692083-- But when I directly read the file from request using request.FILES['file'] .read() The same content wasn't there. I wanted to understand this behaviour. Thanks in advance. -
NoReverseMatch at /login/
NoReverseMatch at /login/ is the error I'm getting from the console, I have a feeling this is something to do with the linking that is going on between urls.py but I can't figure out which part of it is wrong. Any help would be greatly appreciated on this. The full error from the console is beneath Reverse for 'django.contrib.auth.views.login' not found. 'django.contrib.auth.views.login' is not a valid view function or pattern name. urls.py from django.contrib import admin from polls import views as polls_views from django.conf.urls import url, include from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^calendar/', include('calendarium.urls')), url(r'^polls/', include('polls.urls')), url(r'^$', polls_views.home, name='home'), url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'login'}, name='logout'), url(r'^signup/$', polls_views.signup, name='signup'), ] base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>{% block title %}OnNote{% endblock %}</title> </head> <body> <header> <h1>My Site</h1> {% if user.is_authenticated %} <a href="{% url 'logout' %}">logout</a> {% else %} <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a> {% endif %} <hr> </header> <main> {% block content %} {% endblock %} </main> </body> </html> login.html {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <div id="content-container" class="container p-none"> <div class="lgn-container col-lg-8"> <form … -
Multiple Reverse-Relations in Django-REST-FrameWork
Models: class Client(Model): title = CharField('Название клиента', max_length=100) class Phone(Model): client = ForeignKey(Client, on_delete=CASCADE) number = CharField(max_length=50) Serializers: class PhoneSerializer(ModelSerializer): number = CharField(required=True) class Meta: model = Phone fields = ('number') class ClientSerializer(ModelSerializer, GlobalObjectMixin): id = IntegerField(read_only=True) title = CharField(required=True) phone = PhoneSerializer(required=False) def create(self, validated_data): if 'phone' in validated_data: phones = validated_data.pop('phone') client = Client.objects.create(**validated_data) phone = Phone.objects.create( client_id=client.id, **phones ) return client class Meta: model = Client fields = ('id', 'title', 'phone', 'phone_set') Problem: I can't add multiple phones while creating the Client, if I provide only one Phone for Client, I can create and retrieve that Client with no problem, but if I add multiple Phones while creating the Client, I got an empty list instead of a list of dicts with Phones. PS: I'm making requests via postman, I provide Phone while creating Client like: phone.number : 1234567 -
Django annotate with conditional expression, how to apply distinct()
I have a little bit complex query and I use annotate with a conditional expression, the code is below: from django.db.models import Q, F, When, CharField, Value, Case from django.contrib.auth.models import User ATT_PREFIX = 'f' def get_it(mymodel, fields): q = Q(modelone__modeltwo__mymodel=mymodel) query_set = { 'aid': F('modelone__id'), 'name': F('modelfour__name'), } for f in fields: query_set[ATT_PREFIX + str(f.id)] = Case( When(Q(modelfive__modelsix=f) & Q(modelfive__user__email=F('email')), then='modelfive__entry'), default=Value(''), output_field=CharField(), ) return User.objects.filter(q).annotate(**query_set) Attributes aid and name collected with F() have expected values. Second part which use conditional expression have a problem: If feilds list contain 2 objects, then I have 2 User objects created by Case() when condition is meet. So instead of one object with atributes (aid, name, f17, f18) I got two objects: obj1 attributes (aid, name, f17) obj2 attributes (aid, name, f18) -
executing code only once when status change
I am a beginner django developer, and I have a question concerning executing code only once when a if statement is met. In my app I have a team where each member need to answer a survey. and I would like that, if each member has answer his survey a mail is sent to the Team manager that the team is ready. I know how to do it in myview.py.. the thing is now each time I load my app a new mail is sent ... I would like to have it send only once, when the status change from open to close. Any idea ? -
Gunicorn for Django project without virtual enviroment
I was trying to deploy my Django project with Gunicorn but the tutorial is very messy and even though the example worked, the real project is not working. Do I need to configure a gunicorn file or make some changes in project wsgi file? here is my wsgi file- import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ChemicalSimilarities.settings") application = get_wsgi_application() I am using this command to try to run gunicorn for debugging too - gunicorn ChemicalSimilarities.wsgi:application--debug --log-level debug The error that I am getting is this - proxy_protocol: False worker_connections: 1000 statsd_host: None max_requests_jitter: 0 post_fork: <function post_fork at 0x7fb86d5fd7d0> errorlog: - enable_stdio_inheritance: False worker_class: sync ssl_version: 2 suppress_ragged_eofs: True syslog: False syslog_facility: user when_ready: <function when_ready at 0x7fb86d5fd500> pre_fork: <function pre_fork at 0x7fb86d5fd668> cert_reqs: 0 preload_app: False keepalive: 2 accesslog: None group: 1000 graceful_timeout: 30 do_handshake_on_connect: False spew: False workers: 1 proc_name: None sendfile: None pidfile: None umask: 0 on_reload: <function on_reload at 0x7fb86d5fd398> pre_exec: <function pre_exec at 0x7fb86d5fdd70> worker_tmp_dir: None limit_request_fields: 100 pythonpath: None on_exit: <function on_exit at 0x7fb86d6055f0> config: None logconfig: None check_config: False statsd_prefix: secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} reload_engine: auto proxy_allow_ips: ['127.0.0.1'] pre_request: <function pre_request at 0x7fb86d5fded8> post_request: <function post_request at 0x7fb86d605050> forwarded_allow_ips: … -
django rest api error
in view.py def locker_data_response(request, locker_id): if request.method == 'GET': locker_information = get_object_or_404(Locker, locker_id = locker_id) print(locker_information) locker_information_serialize = LockerSerializer(locker_information, many=True) print(locker_information_serialize) return Response(locker_information_serialize.data) in serialize.py class LockerSerializer(serializers.ModelSerializer): class Meta: model = Locker fields = '__all__' .accepted_renderer not set on Response error -
Django - User uploaded S3 files in the view
I have a page where users can upload PDF / image files to their profile. The model for these files is relativly straightforward: class ResumeItemFile(models.Model): item = models.ForeignKey(ResumeItem, related_name='attachment_files') file = models.FileField( max_length=255, upload_to=RandomizedFilePath('resume_attachments'), verbose_name=_('Attachment')) name = models.CharField(max_length=255, verbose_name=_('Naam'), blank=True) I am creating a view where all files linked to a profile (item) are gathered in a .zip file. I've got this working locally, but in production I run in the following error NotImplementedError: This backend doesn't support absolute paths. The main difference is that on production the mediafiles are served through S3 MEDIA_URL = 'https://******.s3.amazonaws.com/' STATIC_URL = MEDIA_URL In my view I created a list of the ResumeItemFile in the attachments variable, which is a list of dicts that look like this: {'filename', ResumeItemFileObject} for file in attachments: storage = DefaultStorage() filename = file[1] file_extension = str(file[0].file).split('.')[-1] file_object = storage.open(file[0].file.path, mode='rb') filename, file_object.read()) file_object.close() Though this works fine locally, on staging it crashes on the file_object = storage.open(file[0].file.path, mode='rb') line. If the backend does not support absolute paths, how I am to select the correct file? Does anyone have an idea of what I am doing wrong? -
Django : render not passing context variable to template
I have this views function to fetch userid and accountnumber from AWS Dynamodb : def dsctbl2(request): dynamodb=boto3.client('dynamodb', region_name='us-west-2') response = dynamodb.scan( TableName='User-Account') filtered = response['Items'] length = len(filtered) for k in range(length): accnum = filtered[k]['AccountNum']['S'] uid = filtered[k]['UserId']['S'] f = dict(AccountNum=accnum,userID=uid) rows = list(f.items()) return render('useradd.html',{'rows': rows}) I have tried almost everything but the rows value is just not getting passed to my template. I even tried passing a simple string value and even that is not getting passed. This is my template table where I wish to display the userid and accountnum. <div class="mytable"> <table> <thead> <tr> <th>Account #</th> <th>User Id</th> </tr> </thead> <tbody> {% for row in rows %} <tr> <td>{{ row.AccountNum }}</td> <td>{{ row.UserId }}</td> </tr> {% endfor %} </table> </div> When I hit the template , nothing shows up. No values are getting displayed except the table headings. Why is render not passing the context variable (list value)from my views to template ? I have been stuck with for about 6 hours ! Can someone resolve this issue ? -
Django, CSS3, and font-face: how to load local font files?
So I have a Django app <my-app> and I would like to load some local font files into the base template <my-app>/templates/<my-app>/base.html. For example, under <my-app>/static/<my-app>/fonts/Lato/ I have several .ttf files: Lato-Black.ttf Lato-BlackItalic.ttf Lato-Bold.ttf etc and in <my-app>/static/<my-app>/css/fonts.css I have: @font-face { font-family: Lato; font-style: normal; font-weight: 300; src: local('Lato-Black') url('../fonts/Lato/Lato-Black.ttf') format('truetype'), local('Lato-BlackItalic') url('../fonts/Lato/Lato-BlackItalic.ttf') format('truetype'), local('Lato-Bold') url('../fonts/Lato/Lato-Bold.ttf') format('truetype'), local('Lato-BoldItalic') url('../fonts/Lato/Lato-BoldItalic.ttf') format('truetype'), local('Lato-Hairline') url('../fonts/Lato/Lato-Hairline.ttf') format('truetype'), local('Lato-HairlineItalic') url('../fonts/Lato/Lato-HairlineItalic.ttf') format('truetype'), local('Lato-Italic') url('../fonts/Lato/Lato-Italic.ttf') format('truetype'), local('Lato-Light') url('../fonts/Lato/Lato-Light.ttf') format('truetype'), local('Lato-LightItalic') url('../fonts/Lato/Lato-LightItalic.ttf') format('truetype'), local('Lato-Regular') url('../fonts/Lato/Lato-Regular.ttf') format('truetype') ; } Accordingly in base.html: <link rel="stylesheet" type="text/css" href="{% static '<my-app>/css/fonts.css' %}" /> This does not load the fonts so that I can use them as if I used Google's api: <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet"> So how do I fix my CSS? -
pass class variable name to class method
I have a Model defined as below: class ProblemVerificationModel(CreateUpdateDateModel): problem = models.ForeignKey(Problem, related_name="problem_survey") verifier = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="verified_problem") is_problem_properly_formated = ... # BooleanField is_this_done = ... # BooleanField is_that_done = ... # BooleanField # other BooleanFields The above model serves like a voting system in my application. I need to calculate percentage of votes for each property such as is_problem_properly_formated, is_this_done, is_that_done etc. I am using classmethod for the same as defined below: @classmethod def percentage_problem_properly_formated(cls, problem): votes = cls.objects.filter(problem=problem) total_votes = votes.count() yes_votes = votes.filter(is_problem_properly_formated=True).count() percentage_yes = (yes_votes / total_votes) * 100 return percentage_yes @classmethod def percentage_is_this_done(cls, problem): votes = cls.objects.filter(problem=problem) total_votes = votes.count() yes_votes = votes.filter(is_this_done=True).count() percentage_yes = (yes_votes / total_votes) * 100 return percentage_yes Now for each property I am using similar method with difference being parameter passed to filter method. This certainly is not a DRY way of doing things. I just want a single method where I can pass the parameter to pass to filter method. Can you help or provide hints to achieve the same results the DRY way? -
fatal error: portaudio.h: No such file or directory
Running setup.py install for pyaudio ... error Complete output from command /home/mertyildiran/Downloads/VirtualEnvironment/vir1/Cerebrum/ENV/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-GCltlv/pyaudio/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-icMIUV-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/mertyildiran/Downloads/VirtualEnvironment/vir1/Cerebrum/ENV/include/site/python2.7/pyaudio: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying src/pyaudio.py -> build/lib.linux-x86_64-2.7 running build_ext building '_portaudio' extension creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c src/_portaudiomodule.c -o build/temp.linux-x86_64-2.7/src/_portaudiomodule.o src/_portaudiomodule.c:29:23: fatal error: portaudio.h: No such file or directory #include "portaudio.h" ^ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 -
Excluding fields while using Values()
I have a model XYZ(name,age,sex), I am fetching all the fields using XYZ.objects.filter(name='ddd').values() this is returning all the fields in dict how to exclude the field age I have tried XYZ.objects.filter(name='').exclude('sex').values() but it not working