Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Can't access data on template through foreign_key
I want to access transaction_ambassador in my template. Therefore my approach is going through the order model as I already use it and it's foreign_key. What I did was {{ order.ambassador_transaction }}. But all I get is ambassadors.AmbassadorTransaction.None. I checked it several times, but it is connected through the foreign_key. Anyone knows what I am doing wrong here? views.py class OrderListView(ListView): allow_empty = False template_name = 'orders/order_list.html' def get_queryset(self): return Attendee.objects.filter( order__order_reference=self.kwargs['order_reference'], order__access_key=self.kwargs['access_key'], ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['order'] = Order.objects.get( order_reference=self.kwargs['order_reference'], ) return context models.py class AmbassadorTransaction(models.Model): order = models.ForeignKey( Order, on_delete=models.PROTECT, related_name='ambassador_transaction' ) ambassador = models.ForeignKey( AmbassadorProfile, on_delete=models.PROTECT, related_name='ambassador_profile' ) class Order(models.Model): event = models.ForeignKey( Event, on_delete=models.PROTECT, related_name='orders' ) order_reference = models.CharField( max_length=10, unique=True, ) total_gross = models.DecimalField( max_digits=25, decimal_places=2 ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) -
DoesNotExist at /home/ Friend matching query does not exist
from home.models import Post,Friend from django.contrib.auth.models import User class HomeView(TemplateView): template_name='home/home.html' def get(self,request): form=HomeForm() posts=Post.objects.all().order_by('-created') users=User.objects.exclude(id=request.user.id) friend=Friend.objects.get(current_user=request.user) friends=friend.users.all() -
Not able to install mysqlclient
I am new to django but I know MySQL. However I wanted to connect django with mysql but is stuck at this point where I have to install mysqlclient but getting the error. I have already installed mysql server, created a virtualenv but still not able to install mysqlclient. Here is the error I am getting: /usr/bin/ld: cannot find -lssl /usr/bin/ld: cannot find -lcrypto collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/home/devesh/django-apps/myproject/myprojectenv/bin/python3 -u -c "import setuptools, tokenize;file='/tmp/pip-install-vaq3j43s/mysqlclient/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-record-v5qqxse5/install-record.txt --single-version-externally-managed --compile --install-headers /home/devesh/django-apps/myproject/myprojectenv/include/site/python3.5/mysqlclient" failed with error code 1 in /tmp/pip-install-vaq3j43s/mysqlclient/ -
Use of single underscore before parentheses in Django
I've seen a lot of examples if Django of people doing things like class Person(models.Model): SEX_CHOICES = ( ('male', _('male')), ('female', _('female')), ('non-binary', ('non-binary')), ) first_name = models.CharField(_('first_name'), max_length=25) last_name = models.CharField(_('last_name', max_length=50) sex = models.CharField(_('sex'), choices=SEX_CHOICES, max_length=100) Meta: verbose_name = _('first_name') What does the the single leading underscore do? I assume that it's doing something about translating the names into database field names, but I'm having trouble finding anything in the official documentation that mentions it. Is this still a thing in Django 2.0? -
Get Django admin password
I'm using Django (version 2.0) as a newbie and have forgotten the admin superuser password. I know that I can create another superuser and change the password of the previous superuser as well. But is there any procedure to know the RAW password of the previous superuser which I've forgotten? -
Profiling python Gunicorn Django application only shows low level calls, not my code
I am profiling my django application which runs on a gunicorn WSGI webserver. I use werkzeug which takes care of profiling with cProfile. Basically the only thing I had to do to make it work was to add the Middleware from werkzeug.contrib.profiler import ProfilerMiddleware from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main_app.settings") application = ProfilerMiddleware(get_wsgi_application(), restrictions=(30,)) application = get_wsgi_application() Everything works fine but I only see stats from what seems to me system calls, but not my packages, I guess I have to add them somehow to the profiler so he knows about it, can someone tell me how? 263632 function calls (233580 primitive calls) in 8.682 seconds 3:19:46 PM web.1 | Ordered by: internal time, call count 3:19:46 PM web.1 | List reduced from 1091 to 30 due to restriction <30> 3:19:46 PM web.1 | ncalls tottime percall cumtime percall filename:lineno(function) 3:19:46 PM web.1 | 54 4.160 0.077 4.160 0.077 {method 'read' of '_ssl._SSLSocket' objects} 3:19:46 PM web.1 | 6 2.599 0.433 2.599 0.433 {method 'do_handshake' of '_ssl._SSLSocket' objects} 3:19:46 PM web.1 | 6 1.094 0.182 1.094 0.182 {method 'connect' of '_socket.socket' objects} 3:19:46 PM web.1 | 11 0.055 0.005 0.055 0.005 {method 'sendall' of '_socket.socket' objects} 3:19:46 PM web.1 | … -
iterator should return strings, not bytes (did you open the file in text mode?) - csv error
CSV file example is Name Emp_ID Zone_ID Jack 4145 10-34-2Z-71ABD Bob 4146 10-35-2Z-71ABD Rick 4147 10-34-2Z-73ABD Shane 4148 10-34-2Z-72ABD Here is the python code (Am running this in django environment) import . . def handle_uploaded_file(file1, file2): """ handle_uploaded_file is a function that takes 2 files uploaded by the users """ csv_old = csv.reader(file1, delimiter=',') header = next(csv_old) # here is line 25 in my pycharm old_data = {row[0] : row for row in csv_old} csv_new = csv.reader(file2, delimiter=',') header = next(csv_new) new_data = {row[0] : row for row in csv_new} set_new_data = set(new_data) set_old_data = set(old_data) added = [['Added'] + new_data[v] for v in set_new_data - set_old_data] deleted = [['Deleted'] + old_data[v] for v in set_old_data - set_new_data] in_both = set_old_data & set_new_data changed = [['Changed'] + new_data[v] for v in in_both if old_data[v] != new_data[v]] with open('difference.csv', 'w', newline='') as f_output: csv_output = csv.writer(f_output, delimiter=',') csv_output.writerow(['History'] + header) csv_output.writerows(sorted(added + deleted + changed, key=lambda x: x[1:])) def index(request): # index is a function for the upload button if request.method == 'POST': # POST method inserts something to the server print(request.FILES) form = UploadFileForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): print("cool") handle_uploaded_file(request.FILES.get('file1'),request.FILES.get('file2')) return HttpResponseRedirect('results/') else: form = UploadFileForm() return render(request, 'hello.html', {'form': … -
Django won't let me run migrate because the check function detects references to a new field I am adding
I am adding a new field to a model, but I can't get the migration to work sqlite3.OperationalError: no such column: main_language.iso639_1 I could only generate the migration file with makemigration by commenting out all references to the new field in my code, but now I can't run migrate without keeping the field commented out. This is not acceptable as referencing my new field obviously needs to eventually appear in my code and anyone else pulling the latest version of the codebase will have the uncommented code when they attempt to run the migration. I haven't had this problem before despite adding new fields to models many times, not sure why it is happening this time: # iso639_1 is the new field class Language(TranslatableMixin, models.Model): ENGLISH = 1 # id for English should always be 1 ISO_HELP_TEXT = _("Please find the correct code at: https://www.loc.gov/standards/iso639-2/php/code_list.php") title = models.ForeignKey('main.Sentence', on_delete=models.PROTECT, related_name='LanguageTitle') iso639_2 = models.CharField(max_length=8, help_text=ISO_HELP_TEXT) iso639_1 = models.CharField(max_length=8, blank=True, default='', help_text=ISO_HELP_TEXT) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) created = models.DateTimeField(auto_now_add=True) objects = LanguageManager() Error I receive when trying to run 'python manage.py migrate': Traceback (most recent call last): File "C:\Users\Win7\OneDrive\Programming\Git\lang\.venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Win7\OneDrive\Programming\Git\lang\.venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in … -
Django - Posting jQuery dictionary object via Ajax returns None
I have an Ajax function in my Django project resembling the following... $('#btn-submit').click(function(e){ e.preventDefault(); var btn = $(this); var dataUrl = btn.attr('data-href'); var title = $('#title').val(); var dict = {}; $('.choice-m2m-check').each(function(i){ k = $(this).val(); v = $(this).attr('data-value'); dict[k] = v; }); $.ajax({ url:dataUrl, method:'POST', data:{ 'title':title, 'dict':dict, }, success:function(data){ if (data.saved){ ... } }, error:function(error){ ... } }); }); So I have a {key: value, ...} dictionary which assigns a 'true' or 'false' boolean flag to each item. This is then posted to the URL represented by 'dataUrl' where Python does some checks on the data. So firstly, in the jQuery after the key value pairs have been assigned, I console log the value of dict using console.log(dict) which gives me something like the following {item-885564895: "true", item-0385245877: "false"} in the console. The problem is that in my Django view where I print the posted value of request.POST.get('dict') then it prints None. Note that when I print the 'title' field which is a regular string then printing it returns the value of the title. What am I doing wrong? -
Password field doesn't hide the password in the sign up form
I was trying to teach myself how to use django more efficiently and only to use class-based views. I am not sure if I am doing everything alright. I tried to make a form so that a user could sign up. But the password field won't hide my password. Here is my code: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Sign Up" /> </form> #views.py class HomeView(CreateView): template_name = 'home.html' model = Client fields = ['username', 'password', 'email', 'name', 'surname', 'phone', 'address'] #models.py class Client(User): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) phone = models.CharField(max_length=15, validators=[ RegexValidator( regex='^[0-9+]*+', message='Not a valid phone number.', ), ]) address = models.CharField(max_length=255) #forms.py class AccountForm(forms.Form): email = forms.CharField(widget=forms.EmailInput) password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Client -
Unable to enter the blank form textarea after $().html();
I am writing a footnote like SO's comment, the template: <div class="col-md-12 add-article-footnote"> <a href="{% url 'article:footnote_create'%}">add a footnote</a> </div> the script: when "add a footnote" is clicked, it prompts an footnote form, $(document).ready(function () { $('.add-article-footnote').on('click', function (e) { e.preventDefault(); var $addArticleFootnote = $(".add-article-footnote"); var footnoteForm = ` <br class="cbt"> <form action="" class="footnote-form"> <div class="form-group row"> <div class="col-md-9"> <textarea class="form-control" name="footnote" rows="3"></textarea> </div> <div class="col-md-2"> <button class="btn btn-primary" id="footnoteBtn">Add Annotation</button> </div> </div> </form>`; $addArticleFootnote.html(footnoteForm); });//click event }) However,when the form is emerged, I cannot click into the blank textarea,but could enter in with right click, If I click instantly, the vertical bar flashed in the beginning of the line. -
Django how to send form post data for approvel?
i am having a registration form for customers and want to approve the customers by our employee.if he fulfills the requirements then i want all his detail shown in my employe page who will examine his form detail and approve it . i dont know how to do ? i am newbie please help me. in my models i use customer and customer will book the car after that all of his detail which car he booked i want that to show to my employee site made that restriction on employe page login required only company employee can log in . so help me i want all the forms detail send to my employe page where he sees which customer is register and car he booked . if he click on approve button then email sended to that customer your booking you placed is confirmed . models.py class Booking(models.Model): class Meta(): db_table = "booking" verbose_name = "Booking" verbose_name_plural = "Bookings" ordering = ['-booking_date'] booking_car_car = models.ForeignKey( Car, on_delete=models.CASCADE, related_name='booking_car_car_key' ) booking_customer_customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='booking_customer_customer' ) booking_start_date = models.DateField( blank=False, null=False ) booking_end_date = models.DateField( blank=False, null=False ) booking_total_price = models.IntegerField( blank=False, null=False ) booking_approved = models.NullBooleanField( blank=True, null=True … -
Apply a filter in nested list
I have a course model and insde it I have a categories list … I want to be able to filter the categories Here's my serilaizers class CourseSerial(serializers.ModelSerializer): categories = serializers.SerializerMethodField(read_only=True) image = VersatileImageFieldSerializer( sizes=[ ('full_size', 'url'), ('thumbnail', 'thumbnail__100x100'), ('medium_square_crop', 'crop__400x400'), ('small_square_crop', 'crop__50x50') ] ) class Meta: model = Course fields = ('id','name_a','name_e','short_desc_a', 'short_desc_e','image','categories') def get_categories(self, obj): cats = CourseCategories.objects.filter(course=obj.id) return CourseCategoriesSerial(cats,many=True). class CourseCategoriesSerial(serializers.ModelSerializer): class Meta: model = CourseCategories fields = '__all__' and here's the results "active": 1, "creation_date": "2018-02-24", "creation_user": 1, "categories": [ { "id": 1, "active": 1, "creation_date": "2018-02-24", "course": 1, "category": 140, "subcategory": 159, "creation_user": 1 }, I want to be able to filter the nested list.. like api/course/?category=140 -
JWT Token fails to validate if multiple clients send tokens to Django Server
I have built a token based authentication/permission system in Django (not using REST Framework). When a user logs in, a JWT token is generated using this code - token = jwt.encode({'user': email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=48)}, settings.secret_key) The token is sent as part of response to the AngularJS Frontend and stored there in a cookie and user is navigated to the landing page. When the user tries to visit any other page on the site, the token is sent as part of the request Authorization Header and received in the django backend to be validated by a wrapper - def token_required(f): @wraps(f) def decorated(request, *args, **kwargs): token = None print >> sys.stderr, settings.secret_key try: if request.META['HTTP_AUTHORIZATION']: token = request.META['HTTP_AUTHORIZATION'] print("HTTP AUTH TOKEN: " + request.META['HTTP_AUTHORIZATION']) else: return Response().sendinvalidresponse('User is not Authorised. Please Login', 401) except: Response().senderrormail("Authentication.py", "token_required(f)") return Response().sendinvalidresponse('Internal Error', 500) if token: try: data = jwt.decode(token, settings.secret_key) current_user = list(Q.generic_database_connect(Q.check_user_query, {'var_email': data['user']}))[0] print >> sys.stderr, data print >> sys.stderr, current_user token = jwt.encode({'user': data['user'], 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=48)}, settings.secret_key) settings.token = token.decode('UTF-8') except: print "Token validity failed" return Response().sendinvalidresponse('Token is invalid!', 401) return f(current_user, request, *args, **kwargs) else: print "Token doesnt exist" return Response().sendinvalidresponse('User is not Authorised. Please Login', … -
Django 2.0 and decorator_include - problems with reverse urls
I use django 2.0.7 in my project with django-decorator-include app (version 2.0). My urls.py: from django.conf import settings from django.contrib import admin from django.urls import path, re_path, include from django.conf.urls.static import static from django.conf.urls.i18n import i18n_patterns from django.contrib.auth.decorators import login_required from decorator_include import decorator_include urlpatterns = i18n_patterns( path('', include('web.urls', namespace='web')), path('backoffice/', decorator_include([login_required,], 'backoffice.urls', namespace='backoffice')), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My backoffice.urls: from django.urls import path, re_path from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ from backoffice import views app_name = 'backoffice' urlpatterns = ( path('', views.DashboardView.as_view(), name='dashboard'), ) backoffice is added to INSTALLED_APPS. In my views (in app web for example) I am able to do reverse URL, for example in my login view I do return redirect('backoffice:dashboard') and it works just perfectly - its redirecting to /backoffice/. Problem is when I try to do reverse urls in my templates. In one of my templates, when I add code: <li class="featured"><a href="{% url 'backoffice:dashboard' %}">{% trans 'Open dashboard' %}</a></li> I get django error: NoReverseMatch at / 'backoffice' is not a registered namespace I suppose that problem is related to django-decorator-include, because if I change my include to standard django url include: path('backoffice/', include('backoffice.urls', namespace='backoffice')), it works just fine, and … -
DRF Pagination for regular APIView for json data
I want to implement Server to server pagination using DRF pagination regular APIView for JSON data coming from the database. I referred to the DRF tutorial, they specified for generic APIView. but how can I do pagination for regular APIView? -
Django, wsgi.py error in apache 2
I am trying to deploy my django app into an apache2 server, but i keep getting the same error in the logs and in the page says 'internal server error', i couldn't find any solution to this problem, if i run the app with the command 'python manage.py check' it says that there are 0 problems and the same, running it with python manage.py runserver it works perfect. error logs: [Wed Jul 18 12:47:33.789968 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] mod_wsgi (pid=20694): Target WSGI script '/srv/http/pos/posAPP/wsgi.py' cannot be loaded as Python module. [Wed Jul 18 12:47:33.790013 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] mod_wsgi (pid=20694): Exception occurred processing WSGI script '/srv/http/pos/posAPP/wsgi.py'. [Wed Jul 18 12:47:33.790035 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] Traceback (most recent call last): [Wed Jul 18 12:47:33.790055 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] File "/srv/http/pos/posAPP/wsgi.py", line 16, in <module> [Wed Jul 18 12:47:33.790105 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] application = get_wsgi_application() [Wed Jul 18 12:47:33.790120 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] File "/srv/http/pos/posenv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Wed Jul 18 12:47:33.790158 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] django.setup(set_prefix=False) [Wed Jul 18 12:47:33.790172 2018] [wsgi:error] [pid 20694] [remote 172.19.40.32:61460] File "/srv/http/pos/posenv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup [Wed Jul 18 … -
Passing value from previous page to django view
I have a job site where a user enters a zip code into a form and a list of jobs matching that zip code is displayed search.html : <h6>Results: {{ number_of_results }}</h6> {% for job in jobs_matching_query %} <h2><a class="job_link" href="#">{{ job.job_title}}</a></h2> <p class="job_address lead">{{ job.establishment_name }} - {{ job.address }}</p> {% endfor %} <form action = "{% url 'email_subscription' %}"> <p>Subscribe to recieve job alerts near {{ query }}:</p> <!-- query stores zip code--> <input type="text" name= "email" placeholder="Email"> <button class="btn" type="submit">Subscribe</button> </form> The search form is handled by the following view (not sure if I need to include this or not): def job_query(request): if request.method == "GET": query = request.GET.get('query') jobs_matching_query = Job.objects.filter(zip_code__iexact = query) | Job.objects.filter(city__iexact=query) | Job.objects.filter(state__iexact=query) number_of_results = 0 for job in jobs_matching_query: number_of_results = number_of_results + 1 return render(request, 'core/search.html', {'query': query ,'jobs_matching_query': jobs_matching_query, 'number_of_results': number_of_results}) On that search.html I have an email subscription box (subscribe to recieve alerts for that particular zip code), is there a way to pass the value of query from that page to an email_subscription view? I believe I've seen this done in the url so here is the url for said view url(r'^email_subscription$', views.email_subscription, name="email_subscription"), thanks in advance … -
Modifying multiple objects simultaneusly with Django
Ok, so here's the thing. I'm just starting out with Django, and I have a model which is pretty much: class Parent(models.Model): description = models.CharField(max_length=128,unique=True) def __str__(self): return self.description class Child(models.Model): description = models.CharField(max_length=128,unique=False) int0 = models.IntegerField(unique=False) int1 = models.IntegerField(unique=False) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) def __str__(self): return self.description What I want to end up with is something like this. Essentially, I want a list of the int0 and int1 values, modifiable, in fields. They should be sorted alphabetically, by parent and child. What is the best way to go about this? -
Django - Freight Key - how to use it correctly?
I have following DB model: class Table1( models.Model ): sctg = models.CharField(max_length=100, verbose_name="Sctg") emailAddress = models.CharField(max_length=100, verbose_name="Email Address", default='') def __unicode__(self): return str( self.sctg ) class Table2( models.Model ): sctg = models.ForeignKey( Table1 ) street = models.CharField(max_length=100, verbose_name="Street") zipCode = models.CharField(max_length=100, verbose_name="Zip Code") def __unicode__(self): return str( self.sctg ) and I would like to execute select query. This is what I did: sctg = Table1.objects.get( sctg = self.sctg ) data = Table2.objects.get( sctg = sctg ) and it works but now I am executing 2 queries. Is there a chance to do this in only one ? in raw SQL I'd do a JOIN query but no idea how to do this in django models Will be thankful for your support, Thanks in advance, -
Exception running celery
I am trying to integrate celery version 4.2 in a django project. As per the docs I have done the changes in init.py and celery.py but when I run celery with: python -m celery -A instaguide beat -l debug I get the exception below. I am not sure what it is missing. The only CELERY_ setting that I have defined in my project.settings is CELERY_BROKER_URL and it doesn't complain about not connecting to broker. So it is something else that I am missing either in my settings or somewhere else. Any clues? celery-worker | k (most recent call last): celery-worker | File "/usr/local/lib/python2.7/runpy.py", line 174, in _run_module_as_main celery-worker | "__main__", fname, loader, pkg_name) celery-worker | File "/usr/local/lib/python2.7/runpy.py", line 72, in _run_code celery-worker | exec code in run_globals celery-worker | File "/usr/local/lib/python2.7/site-packages/celery/__main__.py", line 20, in <module> celery-worker | main() celery-worker | File "/usr/local/lib/python2.7/site-packages/celery/__main__.py", line 16, in main celery-worker | _main() celery-worker | File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 322, in main celery-worker | cmd.execute_from_commandline(argv) celery-worker | File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline celery-worker | super(CeleryCommand, self).execute_from_commandline(argv))) celery-worker | File "/usr/local/lib/python2.7/site-packages/celery/bin/base.py", line 275, in execute_from_commandline celery-worker | return self.handle_argv(self.prog_name, argv[1:]) celery-worker | File "/usr/local/lib/python2.7/site-packages/celery/bin/celery.py", line 488, in handle_argv celery-worker | return self.execute(command, argv) celery-worker | … -
Django - What CBV should I use for my case?
First of all, I want to say that I'm really a novice with Django, and looking for some architectural advice for my project. I have a front-end template that looks like this: When a user clicked "save" button, data in the input fields needs to be saved into a database. The users will be constantly updating these input fields with new values, and there will be a case where none of these data is present in the database, because the user hasn't filled them out yet. The problem is, I am not sure what view method to use. views.py class BhaCreateView(CreateView): model = models.bha fields = '__all__' context_object_name = 'bha' template_name = 'base/bha.html' This just a really rough code that I made just ask a question here. I'm aware that there are many kind of class-based-views, such as DetailView, ListView, CreateView, UpdateView... and many more. Which one, or ones should I use for my purpose? I'm thinking that I need some combination of CreateView and UpdateView, since the users will be updating new information to BHA section, but there still are chances that information was not inserted in the first place at all. How should I do this? -
Django - what is the use of 'super' keyword in python?
I am beginner in Django and Currently I was developing the code in Django and was not able to figure out the difference between the two. class MyForm(forms.Form): myfield = forms.ChoiceField(choices=[(u.id, u.username) for u in User.objects.filter(type="TYPE1")]) and class MyForm(forms.Form): pass def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['myfield'] = forms.ChoiceField(choices=[(u.id, u.username) for u in User.objects.filter(type="TYPE1")]) even though purpose of both code is same but I am unable to spot the difference between the two as what is going on behind the scene. -
Can`t create a virtualenv using Python
I am trying to create a virtualenv but I just get stuck with this message python -m virtualenv env New python executable in /Users/r13/env/bin/python Installing setuptools, pip, wheel... What is going on? -
Add new provider to Django-AllAuth (SteadyHQ.com)
I want to add a new provider (SteadyHQ.com) to the Django-allauth app. SteadyHQ is similar to patreon but from Germany. I have made a fork of the project and add SteadyHQ as a provider. Unfortunately I stuck with the implementation :( You can finde the documentation of the SteadyHQ API here. I have create a new provider and create the social account with my client ID and Security Code. Additional I have add the following code to my settings.py: SOCIALACCOUNT_PROVIDERS = { 'steadyhq': { 'SCOPE': ['read'] } } For testing I have to use ngrok because it is not possible to use "localhost:XXXX" as redirect url at SteadyHQ. Now the redirect URL looks like http://personallink.ngrok.io/accounts/steadyhq/login/callback/ If I try to login with SteadyHQ.com I come to the access grant page from SteadyHQ.com. I give my App full access and get following callback: http://personallink.ngrok.io/accounts/steadyhq/login/callback/?code=SomeSpezialCode&state=SomeSpecialState BUT my site show an "Social Network Login Failure. An error occurred while attempting to login via your social network account.". I have no Idea how to deal with it and get the other parts to work... I hope someone can help my. Thank you very much! Best regards Tobit