Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Query largest date in an ArrayField
I'm making use of Django's postgres ArrayField. Say I have a model like this: from django.db import models from django.contrib.postgres.fields import ArrayField class Event(models.Model): name = models.CharField(max_length=200) dates = ArrayField(models.DateField()) And I want to find the Event with the latest date. Is there a way to build a queryset that can do that? -
How to accomplish rendering templates with AngularJS without refreshing whole page?
I mostly lack the knowledge and vocabulary to being looking into the subject, as I would have already if I could put my Google search in proper terms that would yield helpful results. This is probably pretty basic, so looking to get a basic knowledge so I can dig into it myself. My current intranet web application has, and really only needs, two URLS: https://app/ https://app/dashboard The first is where the user enters their credentials and then it passes them on to the latter. The web application has a navbar and sidebar that should always be there once they are in the dashboard and authenticated. The navbar has really basic stuff like logout, profile, etc., but the sidebar has several dozen tools I am developing. What I would like is for the user to be able to click on any of those tools and have the main content area populate with content that is relevant to that tool. You see this all over the place, but the most recent one I saw that reminded me to ask about this, is here if you scroll down to the Overview and Spec buttons: https://www.bhphotovideo.com/c/product/667336-REG/CAD_E100S_Equitek_E100S_Supercardioid_Large.html Right now, I have my login page (https://app/) … -
MySQL has operational error where SQLite3 does not
I was building my Django website with SQLite3 and now that I am moving it to production I would like to dump the database and switch to MySQL. As I ran python manage.py migrate on the production server however, the following error occured: Traceback (most recent call last): File "manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 215, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 514, in alter_field old_db_params, new_db_params, strict) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 683, in _alter_field params, File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/my-project/.virtualenvs/my-project/lib/python3.5/site-packages/django/db/backends/utils.py", … -
Howler JavaScript library iterating audio objects in Django template
Building an app that displays a list of audio objects, the HTML5 audio element is not compatible across all browsers, so I'm using the Howler JS library. So, my Django template is iterating over an included ul element like this: {% for obj in instance.sounds_set.all %} {% include 'sound_detail.html' with sound=obj %} {% endfor %} the sound_detail.html looks like this: <ul><div> <a onclick="play()">Play</a> <a href="/{{sound.id}}/delete/">Delete</a> </div> </ul> and the script which creates the Howler object: function play(){ var sound = new Howl({ src:['{{obj.sound.url}}'], volume: 0.5, }); sound.play();} So, the template iterates over the ul correctly and the delete url deletes the correct object, but the play() function always calls the first audio object in the list, regardless of which ul object the function is called from. How can I get the play button on each ul object to correspond to the correct sound? -
Getting TemplateDoesNotExist at / error in Django on running the server
I'm trying to follow Django tutorials and learn Django. Below is my project structure: But when I run python manage.py runserver I get TemplateDoesNotExist at / error showing: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: Using loader django.template.loaders.app_directories.Loader: /usr/local/lib/python2.7/site-packages/django/contrib/admin/templates/template.tmpl (File does not exist) /usr/local/lib/python2.7/site-packages/django/contrib/auth/templates/template.tmpl (File does not exist) /usr/local/lib/python2.7/site-packages/markdown_deux/templates/template.tmpl (File does not exist) Why does it go to the above path to find the template.tmpl file and not got to /Django_Project/template/template.tmpl Let me know if any more piece of code is needed from me. Thanks. -
How to send a body in Swagger Django documentation?
I try to use Swagger documentation in my Django project however I am not able to send body. Furthemore, List Operations doesn't work. Anyone have an idea how to fix it? I have only default settings: urls.py: from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^swagger', schema_view), ] I can only list all my URLs and log in as admin. Logout doesn't work. At this moment when I choose Expand Operations I see something like this: -
Django/Celery/Droplet: starting celery fails with supervisor, but works manually with same script (AppRegistryNotReady: Apps aren't loaded yet.)
I can call a worker with my celery_init.sh. It receives tasks and processes them in the way I would expect, as confirmed with flower. I can't get supervisor to start celery automatically with the same script. terminal$ ./celery_init.sh works perfectly. terminal$ sudo supervisorctl restart celery fails like this: Traceback [2017-07-18 21:07:28,475: CRITICAL/MainProcess] Unrecoverable error: AppRegistryNotReady("Apps aren't loaded yet.",) Traceback (most recent call last): File "/home/realestateleads/local/lib/python2.7/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/home/realestateleads/local/lib/python2.7/site-packages/celery/bootsteps.py", line 115, in start self.on_start() File "/home/realestateleads/local/lib/python2.7/site-packages/celery/apps/worker.py", line 143, in on_start self.emit_banner() File "/home/realestateleads/local/lib/python2.7/site-packages/celery/apps/worker.py", line 158, in emit_banner ' \n', self.startup_info(artlines=not use_image))), File "/home/realestateleads/local/lib/python2.7/site-packages/celery/apps/worker.py", line 221, in startup_info results=self.app.backend.as_uri(), File "/home/realestateleads/local/lib/python2.7/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/home/realestateleads/local/lib/python2.7/site-packages/celery/app/base.py", line 1182, in backend return self._get_backend() File "/home/realestateleads/local/lib/python2.7/site-packages/celery/app/base.py", line 900, in _get_backend self.loader) File "/home/realestateleads/local/lib/python2.7/site-packages/celery/app/backends.py", line 65, in by_url return by_name(backend, loader), url File "/home/realestateleads/local/lib/python2.7/site-packages/celery/app/backends.py", line 45, in by_name cls = symbol_by_name(backend, aliases) File "/home/realestateleads/local/lib/python2.7/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/realestateleads/local/lib/python2.7/site-packages/django_celery_results/backends/__init__.py", line 4, in <module> from .database import DatabaseBackend File "/home/realestateleads/local/lib/python2.7/site-packages/django_celery_results/backends/database.py", line 7, in <module> from ..models import TaskResult File "/home/realestateleads/local/lib/python2.7/site-packages/django_celery_results/models.py", line 17, in <module> class TaskResult(models.Model): File "/home/realestateleads/local/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__ app_config … -
Django Admin collapse inline
I have a Django Model being displayed in the admin as: class DesInline(admin.StackedInline): model = Des_Product extra = 1 fieldsets = [ (None, {'fields': ['id', 'name']}), (None, {'fields': ['description']}), ('Validation', {'fields': ['testing','results'], 'classes': ['collapse']}), ] class DesAdmin(admin.ModelAdmin): list_display = ('name','version') inlines = [DesInline] admin.site.register(Des,DesAdmin) And I have a large number of inline items. Currently the display show all the editable fields of the inline items DesProduct that were previously entered. Is there a way to use css to collapse existing fields of DesProduct that were previously entered so that only the def __str__(self) from the model shows and it is less clutter? I tried adding classes=['collapse']: class DesInline(admin.StackedInline): classes = ['collapse'] model = Des_Product extra = 1 fieldsets = [ (None, {'fields': ['id', 'name']}), (None, {'fields': ['description']}), ('Validation', {'fields': ['testing','results'], 'classes': ['collapse']}), ] But it collapse the whole List instead of just the editable fields. I am using Django 1.10.6 -
Django: Redirect Change Password URL
I have the following two URLs: url(r'^change-password/$',django.contrib.auth.views.password_change,{'template_name': 'meta/changepassword.html', 'post_change_redirect': '/password-changed/'},name='change_password'), url(r'^change-passwordiOS/$',django.contrib.auth.views.password_change,{'template_name': 'meta/changepassword.html', 'post_change_redirect': '/password-changed/'},name='change_passwordiOS'), I thought if I used the following within the change password form it would override what URL would be loaded: {% if 'iOS' in request.path %} <input type="hidden" name="next" value="/profileiOS/" /> {% endif %} But when I reach the change password from the url(r'^change-passwordiOS/$' and click the "Change Button" it does not goto the /profileiOS/ as expected but the standard /profile/ URL. Any help would be appreciated. Full Change Password Form: <form class="form-horizontal" role="form" method="post" action=""> {% csrf_token %} <fieldset> <div class="form-group"> <label class="col-md-6 control-label">{{ form.old_password.label }}:</label> <div class="col-md-6"> <input name="old_password" type="password" class="form-control"/> <div class="text-danger"> {% for error in form.old_password.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> <div class="form-group"> <label class="col-md-6 control-label">{{ form.new_password1.label }}:</label> <div class="col-md-6"> <input name="new_password1" type="password" class="form-control"/> <div class="text-danger"> {% for error in form.new_password1.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> <div class="form-group"> <label class="col-md-6 control-label">{{ form.new_password2.label }}:</label> <div class="col-md-6"> <input name="new_password2" type="password" class="form-control"/> <div class="text-danger"> {% for error in form.new_password2.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> <div class="form-group"> <div class="text-right col-sm-12"> <button type="submit" class="btn btn-primary">Change Password^</button> </div> </div> </fieldset> {% if 'iOS' in request.path %} <input type="hidden" name="next" … -
Gmail is not receiving emails from SendGrid
I have a Django app set up to send emails from my contact form via SendGrid. The contact form should send emails to contact@clientdomain.com, which is an account using G Suite, so the client opens the email on Gmail. However, the emails from the contact form are getting stuck on SendGrid with status deferred or block. I tried changing the destination email from contact@clientdomain.com to personal_email@gmail.com and it worked just fine. I don't know what else to do. Here is my Activity Feed from SendGrid dashboard: I read when the status is deferred, SendGrid keep trying to send the email again for the next 72h, but I have emails sent 3 days ago that never arrived on the inbox. Anyone knows what could I do to fix that? -
Django jquery ajax cors error
I get this error in the console when I try to post data with ajax. This data is supposed to be confirmed at this url and then I should get a response from it containing more data. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://secure.paygate.co.za/payweb3/process.trans. (Reason: CORS header 'Access-Control-Allow-Origin' missing). I am using django-cors-headers as middleware to add the headers. I followed all the config instructions. My settings.py: INSTALLED_APPS = [ # ... 'corsheaders', # ... ] MIDDLEWARE = [ # ... 'corsheaders.middleware.CorsMiddleware', # ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'GET', 'POST', ) The ajax call: $.ajax({ type: "POST", url: url, dataType: "json", data: data, success: function(data){ alert('success'); }, error: function(data){ alert('error'); } }); The data and url is declared above this and that part is fine. I only get the error alert everytime I submit it. My packages: Django==1.11.3 django-cors-headers==2.1.0 pytz==2017.2 I am on Windows 10. -
Django keep register information
I have a form to create new user. Currently, if the user enters bad informations like weak password or a known email address, the user is redirected to the begining to the view_register. So the user has to enter his informations once again. I just want to make sure that the register form in view_register is able to remember any previously entered informations. The user should have to possibility to edit his information to fix his email address or his password. views : def view_register(request): form = MinimumRegisterForm() return render(request, 'register.html', locals()) def view_games(request): media = settings.MEDIA if request.method == 'POST': form = MinimumRegisterForm(request.POST) if form.is_valid(): identifiant = form.cleaned_data['identifiant'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] confirm_password = form.cleaned_data['confirm_password'] sex = form.cleaned_data['sex'] if User.objects.filter(email=email).exists(): messages.add_message(request, messages.INFO, 'Cette adresse email est déjà utilisé.') return redirect(view_register) if password == confirm_password: strengh = password[0].isalpha() if all(c.isalpha() == strengh for c in password): request.session['ident'] = '123456' messages.add_message(request, messages.INFO, 'Le mot de passe doit contenir au moins 8 charactères lettres et chiffres.') return redirect(view_register) else: form = GamesRegisterForm() request.session['identifiant'] = identifiant request.session['email'] = email request.session['password'] = password request.session['sex'] = sex return render(request, 'games.html', locals()) else: messages.add_message(request, messages.INFO, 'Confirmation du mot de passe invalide.') return redirect(view_register) else: … -
Dont reload static files with runserver, django
I load big json files as static files for my page. This takes a few seconds. As ive read and experienced, Django (started with runserver) loads those files again, when my website is refreshed, which is not what I want, because of the loading time. How can i most easily permit this behavior, so that the files are only loaded once when the server is started? Thanks in advance! -
Gunicorn,Docker: No module named myproject
I am trying to deploy my Django website to a Ubuntu 16.04 server that has nginx and Gunicorn running in a docker container. I already have verified that Nginx is working properly. When I try to start the Gunicorn server I get the error "ImportError: no module named 'myproject.wsgi' Command I use trying to start gunicorn: sudo docker exec web1host /bin/sh -c 'cd /usr/share/nginx/html/myproject && gunicorn --bind 0.0.0.0:8000 myproject.wsgi:application' Error returned: [2017-07-18 20:11:57 +0000] [6043] [INFO] Starting gunicorn 19.6.0 [2017-07-18 20:11:57 +0000] [6043] [INFO] Listening at: http://0.0.0.0:8000 (6043) [2017-07-18 20:11:57 +0000] [6043] [INFO] Using worker: sync [2017-07-18 20:11:57 +0000] [6046] [INFO] Booting worker with pid: 6046 [2017-07-18 20:11:57 +0000] [6046] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 357, in import_app __import__(module) ImportError: No module named 'myproject.wsgi' [2017-07-18 20:11:58 +0000] [6046] [INFO] Worker exiting (pid: 6046) [2017-07-18 20:11:58 +0000] [6043] [INFO] Shutting down: Master [2017-07-18 20:11:58 +0000] … -
ViewSet and Router in rest framework
Had a problem with rest framework: building api with a viewset and router. I want api to serialize the user's posts by url like that: /api/users/user id/posts/page, but router can`t stand it. It suggest me that regexp in patterns: ^api/ ^ ^users/posts.(?P[a-z0-9]+)/?$ [name='user-posts'] class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @list_route() def posts(self, page): user = self.get_object() post_set = Post.objects.filter(owner=user) paginator = Paginator(post_set, 16) serializer = PostSerializer(paginator.page(page), many=True) return Response(serializer.data) Have any ideas how to compel this work correctly? Thanks in advance! -
NoReverseMatch error when making update form containing category slug
I'm trying to make a form that updates an existing Category and then redirects back to the Category page. Here is my code: forms.py class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Please enter the category name.") description = forms.CharField(max_length=256, required=False, help_text="Please enter the description of the category.") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) slug = forms.CharField(widget=forms.HiddenInput(), required=False) status = forms.BooleanField(label='Status', required=False, help_text="Is this category still active?") # An inline class to provide additional information on the form. class Meta: # Provide an association between the ModelForm and a model model = Category fields = ('name', 'description', ) views.py def update_category(request, category_name_slug): obj = get_object_or_404(Category, slug=category_name_slug) form = CategoryForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect( reverse('obj', kwargs={'category_name_slug':category_name_slug}) ) return render(request, "courses/update_category.html", {'form': form}) update_category.html {% block main_content %} <h1>Add a Category</h1> <form id="update_category_form" method="post" action=""> {% csrf_token %} {{ form.as_p }} <br/> <input type="submit" name="submit" value="Update Category" /> </form> {% endblock %} When I try to update using this form, I get a NoReverseMatch error. I have a feeling it has something to do with the views.py. How exactly do I write the first return? I managed to get another update form without a slug to work fine, so is it the slug … -
Django suppresses exception in production mode
I have a code that causes an exception (function called from template). When DEBUG=True it correctly raises Exception. But when DEBUG=False just blank page is displayed. What should I do to disable such behavior? -
AJAX Form with CBV Django yileds Form_Invalid Response but still posts to DB
Basically, I have a simple form that only has one field, which requires a string of < 200 chars. The form is submitted via an AJAX request and the response should be to stay on the same page("drug_new") and return a success or a fail with details about what was committed to the DB. What actually happens is: POST http://localhost:8000/drug/new/ 400 (Bad Request) And the server log shows the following: [18/Jul/2017 12:53:35] "GET /drug/new/ HTTP/1.1" 200 3909 invalid loop [18/Jul/2017 12:53:37] "POST /drug/new/ HTTP/1.1" 400 37 [18/Jul/2017 12:53:37] "POST /drug/new/ HTTP/1.1" 302 0 [18/Jul/2017 12:53:38] "GET /drug/new/ HTTP/1.1" 200 3909 Somehow the data also gets posted at the DB level, so what gives?? I am thinking it might have something to do with including the csrftokenmiddleware in the data section of the ajax request, however when I try to exclude it, it results in an error 500. I know that I could just use a function based view to validate the form data, however I don't want to have a CBV and a function for the same view. There has to be a way to get the CBV to work with an ajax request. Thanks in advance! :D Here are … -
Unable to Fix Django NoReverseMatch Error
I'm getting a NoReverseMatch error when I try to pass two arguments from one view to another. Here is the view that is passing the arguments: # promotion/views.py def enter_promo_code(request, template): if request.method == "POST": form = PromotionCodeForm(request.POST) if form.is_valid(): message_text, expiry_date = process_valid_promo_code(request.user, form.cleaned_data['promo_code']) return HttpResponseRedirect(reverse('welcome-page-promo', \ kwargs={'message_text': message_text, 'expiry_date': expiry_date})) else: form = PromotionCodeForm(label_suffix="") context = {'form': form} return render(request, template, context) Here is the receiving view. Note that the two input arguments are optional. The urlpatterns show that this view can be called with or without arguments. # home/views.py def welcome_page(request, template, message_text=None, expiry_date=None): account = Account.objects.get(pk=request.user.id) context = {'uid': request.user.id, 'account_type': account.type.account_type_cd, 'message_text': message_text, 'expiry_date': expiry_date} return render(request, template, context) Here are the urlpatterns for the receiving view: # home/urls.py url(r'^welcome/$', 'home.views.welcome_page', {'template': 'welcome_page.html'}, name='welcome-page'), url(r'^welcome/(?P<message_text>\w{1,})/(?P<expiry_date>\w{1,})/$', 'home.views.welcome_page', {'template': 'welcome_page.html'}, name='welcome-page-promo'), When I execute the promotion view, I get this error when the return HttpResponseRedirect command executes: NoReverseMatch at /promotion/code/ Reverse for 'welcome-page-promo' with arguments '()' and keyword arguments '{'message_text': u'Your promotion code was approved! You will receive a one-year free trial membership which expires on ', 'expiry_date': 'Jul. 18, 2018'}' not found. 1 pattern(s) tried: ['welcome/(?P<message_text>\\w{1,})/(?P<expiry_date>\\w{1,})/$'] I'm running this same code pattern in a different application … -
Django dynamic models disappear after restarting server
In my Django app I create a bunch of models at runtime dynamically. The models are created fine and they are registered properly. However, when I restart the server that my app is running on, the models disappear. The data stays in the database but there is no sign of the models I created. I tried recreating the models with inspectdb but since they are not static models like inspectdb creates, it does not work out properly. I have also tried registering them at database connection, but the issue is that they are not even known as models to begin with. Does anyone know how I can keep my models after restarting? -
How to send a body in Swagger Django documentation?
I try to use Swagger documentation in my Django project however I am not able to send body. Furthemore, List Operations doesn't work. Anyone have an idea how to fix it? I have only default settings: urls.py: from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='PRI API') urlpatterns = [ url(r'^swagger', schema_view), ] I can only list all my URLs and log in as admin. Logout doesn't work. At this moment when I choose Expand Operations I see something like this: -
Django install permissions automaticaly
I Have a django project with multiple apps, for commercial reasons I need to activate each app with just adding it in settings.INSTALLED_APP no I want to do the best thing about permission, my objectif is to install permissions automaticly whene starting server, so I will check the settings and install permissions of each installed app. I dont use migrations What is the best way to represent permissions ? and how can I install theme ? -
How does one redirect on an error in allauth?
I'm currently am writing a site where the users fill out a form with some information to signup, and the server verifies the correctness of that information on its end before allowing a successful signup. If the information is invalid, I want the user to be redirected to a page that tells them what went wrong. I currently have the form/user adapter working and am now adding in the verification for social signup (manual signup is currently working fine, although the code is ugly). Is there a way to add in a redirection in the form/adapter for social signup? If not, how do I handle this? -
Is there a way to do a follower system using CBV in Django?
I'm trying to make the Followers / Followers system on my page, but I do not know how to do something like that. I have only been able to log in the model and do it by admin, but with templates its different. models.py class Connection(models.Model): following = models.ForeignKey(User, related_name='following') follower = models.ForeignKey(User, related_name='follower') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return "{} > {}".format(self.following.username, self.follower.username) Source: https://github.com/cotizcesar/plaxedpy/blob/master/userprofile/models.py -
Django ModelForm with foreign key - allow user to create a new value
Lets say I have a basic model Recipe class Recipe(models.Model): name = models.CharField(max_length=100, null=True, blank=True, default=default_name) category = models.ForeignKey('Category') instructions = models.CharField(max_length=500, null=True, blank=True) Where Category is a related model. Then I have a basic recipe form: class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name','category','instructions'] This works fine, and shows correctly a select box with all of the categories to pick from. However I would like to give the user an option to enter in a brand new 'category' if they don't find one that fits in the related Category model. I found a solution using the select2 javascript library that allows the user to type in a custom value, however that causes the form to throw an error: Select a valid choice. That choice is not one of the available choices. What I'd like to do when processing the form, is take the custom inputs, create the new 'Category' object, then bind it back to the form.