Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get User object upon successful activation of their account via activation link
I am using django 1.11 & django-allauth to authenticate users. Recently the need to improve the flow when the user registers came up, while the confirmation link in email needs to automatically login the user who is being activated. Based on the documentation there is a setting which only works for same session users. ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION (=False) The default behaviour is not log users in and to redirect them to ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL. By changing this setting to True, users will automatically be logged in once they confirm their email address. Note however that this only works when confirming the email address immediately after signing up, assuming users didn’t close their browser or used some sort of private browsing mode. But - I want to be able to auto-login users upon activation: who have signed up from another form on a different web application (different session) - this will always return that the user is an AnonymousUser. More specifically, on my complete_account_verified_view() definition I want to be able to retrieve the user object of the user associated with the successful activation of their account using that activation link. How can this be implemented or is it not possible - are there any security … -
create embedded forms in django view
I have a rule class, a rule is a combination of a question and an answer: class Rule(models.Model): name = models.CharField(max_length=32) class Question(models.Model): name = models.CharField(max_length=32) rule_id = models.ForeignKey(Rule, on_delete=models.CASCADE, null=True, blank=True) class Answer(models.Model): name = models.CharField(max_length=32) rule_id = models.ForeignKey(Rule, on_delete=models.CASCADE, null=True, blank=True) I want to create a form for the rule, where I have two inputs: one for the question and the other for answer. When I click submit I should save a rule in rule table, a question in question table and an answer in answer table. This is the farest I get: I created a form for each model, and I called those forms in one view method: def create_rule_view(request,id, sc_id): rule = RuleForm(request.POST or None) question= QuestionForm(request.POST or None) answer = AnswerForm(request.POST or None) if rule.is_valid() and question.is_valid() and answer.is_valid(): rule.save() question.save() answer.save() return redirect('../') context = { 'rule': rule, 'question': question, 'answer': answer } return render(request, "rule/create_rule.html", context) But it's not the view I want and each model is saved independantly. Can anyone find a solution for me? thanks. -
Override page_size & ordering of CursorPagination in Django Rest Framework
I using CursorPagination of Django Rest Framework, I want to override default page_size(10) and ordering('timestamp') in a single viewset. How can I do this? I tried with my viewset but it's not success: from rest_framework.pagination import CursorPagination class ListAPIView(ListAPIView): queryset = Cake.objects.all() permission_classes = [AllowAny] serializer_class = ListSerializer pagination_class = CursorPagination filter_backends = (OrderingFilter, DjangoFilterBackend) filter_class = CakeListFilter filterset_fields = ('cake_type', 'user__username') ordering = '-date' page_size = 5 Please help me. Thanks in advance! -
Django templates: xxx-jqgrid-yyy notation in url tags
I had asked similar question before in a wider context, now I reduce it to bare bones. My setup (in a conda env): Mac OS X el Capitan 10.13.6 Python 3.6 (also tried with 3.4) Django 1.8.3 jquery-1.11.0.min.js I have an django application that does not work now (legacy inherited from someone else) that used to work. The app employs this data access approach using jqgrid (url tags with xxx-jqgrid-yyy pattern): var searchable_columns = { alteration_type: { searchoptions: { dataUrl: '{% url 'item-jqgrid-Entity1' pk=original.id %}' } }, disease: { searchoptions: { dataUrl: '{% url 'item-jqgrid-Entity2' pk=original.id %}' } }, } where Entity1 and Entity2 are model names, and the urls used to get rendered as dropdowns with values from the models. There is no python code in the app that is referring to this pattern in any way (including url patterns) Question: does this xxx-jqgrid-yyy pattern in template's url tag has a special meaning to django? Something like "Hey python/django, if you see 'xxx-jqgrid-Entity1' in the template then don't search for the pattern in urls.py and get the list of Entity1 values from the model's table directly" ? If so, is here any documentation on how is it hooked on … -
Please help me to solve the stylesheets problem with react
I'm doing my project with React.js I have three scss files in my react code login.scss,dashboard.css and one main scss file named as index.scss.I have one common style in my index.scss file and I imported both scss files in index.scss. But my styles are over riding in my pages so my design is not coming properly.How can I overcome this problem? -
How can we automate the super admin creation process in django
Can we automate the admin user creation process in django. ? Suppose user try to install the application on his system , i want that when user run migrate command then one super user created automatically -
Python Django Architecture Design
I am writing a project to migrate the C# webAPI to Django Framework and want to separation of business layer logic and data access in it. Please help to find out any boiler plate available to design this architecture structure. -
Why does {{ user.groups }} always show auth.Group.None
When I use {{ user.groups }} in my template, I always get auth.Group.None, even though the user is logged in and is part of a group. I can access the groups from the code with request.user.groups.all(), but I need an "always works" version in my templates. -
Retrieve post variable sent via Ajax in Django
I'm processing a table of banking/statement entries that have been exported from another system via a CSV file. They are imported into a view and checked for duplicates before being presented to the user in a HTML table for final review. Once checked they are sent via AJAX to the server so they can be added into a Django model. Everything is working OK including CSRF but I cannot access the POSTed variable although I can see it! Unfortunately making a hidden form isn't viable as there are 80+ rows to process. My Javascript looks like: $.ajax({ type: 'POST', url: '......./ajax/handleImports/', data: entriesObj, success: function (data) { if (data.response && data.response) { console.log("Update was successful"); console.log(data.entries) } else { ... } }, error: function() { ... } where entriesObj is var entriesObj = JSON.stringify({ "newentries": newEntries }); console.log(entriesObj) and when dumped to console.log looks like: {"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... } Now in view.py when I return the whole request.POST object as data.entries using context['entries'] = request.POST return JsonResponse(context) I get {"{"newentries":[{"Include":"","Upload ID":"0","Date":"2019-01-09", ... } but if I try and retrieve newentries with: entries = request.POST.get('newentries', None) context['entries'] = entries return JsonResponse(context) the console.log(data.entries) will output null? How am I supposed to … -
Django: name 'request' is not defined when try to filter event that has been accepted by User
I trying to filter event that only accepted by the current login-user, however this "name 'request' is not defined" continue to pop-up. # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: # filter event that only accepted by user if event.acceptor == request.user: d += event.get_absolute_url() if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' -
passing an id in django homepage url
I'm trying to create a blog using django.I have truncated the post such that you have to click on the post to read the entire post.essentially, you should be redirected to article.html where you get to read the entire blog post. If I try to go to my article.html/1 ,I can read the post, but if I try to do the sane using blog.id in my homepage, I get an error. This is my welcome.html code for the same <a href="{%url 'article' blog.id %}"><p>{pic.post | truncatewords:10 }}</p></button></a> my urls are as follows urlpatterns=[ url(r'^$',views.welcome,name = 'welcome'), url(r'^post/', views.post, name='post'), url(r'^article/(\d+)', views.article, name='article'), url(r'^search/', views.search_results, name='search_results'), ] if settings.DEBUG: urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) my views def welcome(request): pics=Blog.objects.all() return render(request, 'welcome.html', {"pics":pics}) def post(request): form= PostForm(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('welcome') else: form = PostForm() return render(request, 'post.html', {"form":form}) def search_results(request): if 'article' in request.GET and request.GET["article"]: search_term = request.GET.get("article") print(search_term) blogs = Blog.search_results(search_term) message = f"{search_term}" return render(request 'search.html'{"message":message,"blogs": blogs}) else: message = "You haven't searched for any term" return render(request, 'search.html',{"message":message}) def article(request, blog_id): pics =Blog.objects.filter(id = blog_id) return render(request, 'article.html', {"pics":pics, id:blog_id}) however, ever time i try to click … -
django-dataTables impossible to search with foreign/manyToMany references
I'm using dataTables rest framework for django, and when I try to search from scratch a data using a route and this route using manyToMany or foreign key references, this cause a icontains problem http://127.0.0.1:8000/test/api/tout-les-ig/?format=datatables&draw=4&columns[0][data]=number&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=test&columns[0][search][regex]=false&order[0][column]=0&order[0][dir]=asc&start=0&length=90&search[value]=&search[regex]=false&_=1547546595865 lets say [data]=number is a foreign key and [search][value]=test so if I dont put [search][value]= a value in this i wont take me an error but if I do I does and say: "Related Field got invalid lookup: icontains" I've allready tryed to do all things like this in the serializer: number = serializers.SerializerMethodField() def get_style(self,IG): return ', '.join([str(,b.get_number()) for nb in SOME.number.all()]) JS FILE: var table = $('#liste').DataTable( { "language": { "emptyTable": "Aucune donnée trouvée dans la base", "sSearch": "recherche: ", "searchPlaceholder": "recherche dans IGIPOP", "lengthMenu": "Affichage de _MENU_ éléments par page", "infoEmpty": "Aucun éléments ne correponds à la recherche", "info": "résultats de _START_ à _END_ pour un total de _TOTAL_", "infoFiltered": "(filtré avec _MAX_ éléments trouvés)", "zeroRecords": "Aucun résultat", "processing": "Recherche en cours...", "paginate": { "previous": "Page précédente", "next": "Page suivante" } }, 'serverSide': true, // permet les requêtes ajax 'ajax': '{{api_route}}', // route du json attendu dataFilter: function(data){ var json = jQuery.parseJSON(data); json.recordsTotal = json.count; json.recordsFiltered = json.count; json.data = json.results; delete … -
Running celery with django, mod_wsgi and apache
I have been trying to integrate Celery 4.2.1 with Django 2.1.3. I'm able to execute my tasks when running from django default server. The worker receives the task and executes it perfectly. But when running the django application using mod_wsgi and apache, I get an error saying, [Tue Jan 15 14:34:29.250884 2019] [wsgi:error] [pid 7620:tid 1176] [client 53.88.72.53:55100] ('[WinError 10035] A non-blocking socket operation could not be completed immediately',)\r wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'abcd.settings') application = get_wsgi_application() celery.py: from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'abcd.settings') from django.conf import settings os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('abcd', broker=settings.CELERY_BROKER_URL, backend=settings.CELERY_RESULT_BACKEND) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) tasks.py: from django.core.mail import send_mail from .celery import app from celery.utils.log import get_task_logger logger=get_task_logger(__name__) # This is the decorator which a celery worker uses. @app.task def send_email_task(subject, message, email_id): logger.info("Mail for " + subject + " has been sent to " + email_id) print("Mail for " + subject + " has been sent to " + email_id) send_mail(subject, message, 'abcd@abcd.com', [email_id]) Thanks! -
Do not redirect but show error on confirm_delete template if error occurs during DeleteView delete call
I am currently trying to override the DeleteView's inherited delete method to implement my desired behavior. However, I'm relatively new to the Django framework and Python in general and don't know what to do. The goal is to delete an object and if a ProtectedError occurs, the confirm_delete template should display an error message describing the issue and the user should not be redirected to success_url. My first approach, similar to other forms, was to pack the error into form.non_field_error, but I don't know how to access it. def delete(self, request, *args, **kwargs): self.object = self.get_object() success_url = self.get_success_url() try: self.object.delete() # Redirect to success_url except ProtectedError: pass # Add error to confirm_delete template / delete Form and stay on the delete confirmation page (don't delete) return HttpResponseRedirect(success_url) So how is it possible that the user is only redirected to success_url after a successful delete, but an error message appears on the confirm_delete template in case of a ProtectedError and no redirection takes place? -
Import error when using netmiko with django : No module named '_cffi_backend'
Netmiko works fine when I execute below script file (test.py) from the linux cli #!/var/www/html/devopsenv/bin/python from netmiko import ConnectHandler import getpass cisco_asr = { 'device_type': 'cisco_xr', 'ip': 'my ip', 'username': 'user', 'password': 'pass', 'verbose': True } net_connect = ConnectHandler(**cisco_asr) config_commands = [ 'int BE222.2481', 'vrf devops_test', 'ip add 10.1.1.1/30'] output = net_connect.send_config_set(config_commands) #net_connect.commit() print(output) However when I try to use the same script from a django view by importing as below, I get the import error. from netmiko import ConnectHandler import error picture ImportError at / No module named '_cffi_backend' Request Method: GET Request URL: http://W.X.Y.Z/ Django Version: 2.1.4 Exception Type: ImportError Exception Value: No module named '_cffi_backend' Exception Location: /var/www/html/devopsenv/lib/python3.6/site-packages/bcrypt/__init__.py in <module>, line 25 Python Executable: Python Version: 3.5.6 Python Path: ['/var/www/html/devops', '/var/www/html/devopsenv/lib/python3.6/site-packages', '/lib64/python35.zip', '/lib64/python3.5', '/lib64/python3.5/plat-linux', '/lib64/python3.5/lib-dynload', '/lib64/python3.5/site-packages', '/lib/python3.5/site-packages'] -
I want to test the function of django application created on docker with selenium
I'm trying to do: I want to test the function of django application with selenium, behave and behave-django. Also, I want to check the flow of execution of selenium by accessing the vnc server (vnc://localhost:5900). The problem: The vnc server refuses the access to the localhost. But, I can access the other websites, for exmaple, https://www.google.com/. error screen Also, nothing is displayed in the reverse-proxy log. So I thought that reverse-proxy was not working well, but I do not know the solution. Can anyone tell me the solution or clues? My environment: macOS 10.14.1 python 3.7.2 django 2.1.5 Docker 18.06.1-ce behave 1.2.6 behave-django 1.1.0 selenium 3.141.0 reverse-proxy by nginx Source code: features/environment.py class SeleniumTestCase(StaticLiveServerTestCase): fixtures = ["test.yaml"] @classmethod def setUpClass(cls): cls.host = "myapp.dev" cls.port = 50000 cls.browser = webdriver.Remote( command_executor="http://selenium_hub:4444/wd/hub", desired_capabilities=DesiredCapabilities.CHROME, ) cls.browser.implicitly_wait(3) super(SeleniumTestCase, cls).setUpClass() def tearDown(self): self.browser.quit() docker-compose.yml myapp: build: ~ command: python3 manage.py runserver 0.0.0.0:8000 volumes: - ~ ports: - 8000:8000 depends_on: - db environment: - ~ env_file: - ~ user: ~ reverse-proxy: build: ./reverse-proxy ports: - 50000:50000 - 443:443 depends_on: - selenium-node-chrome - selenium_hub - myapp links: - selenium_hub:hub volumes: - ~ selenium_hub: image: selenium/hub ports: - "4444:4444" selenium-node-chrome: image: selenium/node-chrome-debug volumes: - /dev/shm:/dev/shm depends_on: - selenium_hub … -
how to avoid error in accessing all the objects inside views
the page with the integer provided is showing not found 404 from django.http import HttpResponse from .models import Album def index(request): all_albums=Album.objects.all() html='' for album in all_albums: url="/music/"+str(album_id)+"/" html=html+"<a href="+url+">" return HttpResponse(html) expected - some links actual-404 not found -
how to implement echallan website using django
I need to develop a website as my theme based project,and i opted it to do with django.I am planning to do an online traffic fine website where one could pay their pending fines on their vehicles.So is it possible or not and what is needed to learn to impement this.Please kindly help me. -
Why don't working ListView in base template? Django 2.15
I want display list of all comments in db on sidebar (template "base_generic.html"). I do this with ListView, but this didn't working. views.py class CommentListView(generic.ListView): template_name = "base_generic.html" model = Comment paginate_by = 5 base_generic.html {% block sidebar %} <h1>Comments list</h1> {% if comment_list %} <ul> {% for comment in comment_list %} <p>{{ comment.author }} ({{ comment.comment_date }}) {{ comment.description|safe }}</p> {% endfor %} </ul> {% else %} <p>There are no comments.</p> {% endif %} {% endblock %} DB has a comments, but on the page shown "There are no comments". -
Python Django - Read data from multiple databases
I have a Django app that works with multiple databases and I'm having an issue trying to read data specifically from (testdb2) database. I do know that you can choose which database that you want to read data using keyword (Using) but that didn't work. The result is it's always tries to read data from (testdb). Here is the code for database in (Settings.py): DATABASES = { 'default': { 'NAME': 'testdb', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': 'port', }, 'users': { 'NAME': 'testdb2', 'ENGINE': 'sql_server.pyodbc', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': 'port', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, } Here is the code for (Views.py): from rest_framework import viewsets from .models import MyModel from .serializers import MyModelSerializer # Create your views here. class MyModelView(viewsets.ModelViewSet): queryset = MyModel.objects.using('users').all() serializer_class = MyModelSerializer Here is the code for (Models.py): from django.db import models from django.db import connection # Create your models here. class MyModel(models.Model): columnName = models.IntegerField(db_column='columnName', primary_key=True) columnEmail= models.IntegerField(db_column='columnEmail') columnAddress= models.IntegerField(db_column='columnAddress') columnPhone= models.IntegerField(db_column='columnPhone') class Meta: managed = False # Created from a view. Don't remove. db_table = 'UserTable' MyModel is based on a view that is created inside the database. My question: How … -
djagno send html email with static file such as css and js and images
I'm setting up a website for my self that send email with attachment. I used this link How to send html email with django with dynamic content in it? but when I send email according to this link, static files like my images and my css and js files didn't send with my email. here my code : `subject, from_email, to = "WebSite Newsletter Subscribe", settings.EMAIL_HOST_USER, [instance.email] html_content = render_to_string('newsletter/Email.html') text_content = strip_tags(html_content) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send()` now I want to know how I can attach this files? because now my emails are send just with empty html codes. -
Form validation not working for adding images in django 1.11
I have an app where i am uploading multiple images and uploading it. It works fine but without uploading anything if i click on upload it gives me an error because the validations are working. This is the error: django.utils.datastructures.MultiValueDictKeyError: "'gallery'" This is my code here: models.py class GalleryImage(models.Model): image = models.ImageField(upload_to='uploads/obituaries', db_index=True) obituary = models.ForeignKey(Obituary, related_name="gallery") def __str__(self): return self.obituary.name Views.py class GalleryAddView(View): def post(self, request, slug): try: data = request.FILES['gallery'] if len(request.FILES.getlist('gallery')) > 10: messages.error(request, "Max gallery images limit exceeded! Only 10 images are allowed.") return HttpResponseRedirect( reverse('obituary:public', kwargs={'slug': slug})) if request.FILES['gallery']: for f in self.request.FILES.getlist('gallery'): print(f) instance1 = Obituary.objects.get(slug=slug) if instance1.is_valid(): print(instance1) instance1.save() if self.request.FILES: for f in self.request.FILES.getlist('gallery'): GalleryImage.objects.create(obituary=instance1, image=f) messages.success(request, "Gallery images uploaded successfully!") else: messages.error(request, constants.OPERATION_UNSUCCESSFUL) return HttpResponseRedirect( reverse('obituary:public', kwargs={'slug': slug})) except Obituary.DoesNotExist: messages.error(request, constants.OPERATION_UNSUCCESSFUL) return HttpResponseRedirect(reverse('obituary:public', kwargs={'slug': slug})) forms.py class GalleryForm(models.ModelForm): class Meta: model = GalleryImage fields = ['image'] I dont know where i am going wrong. I have not used my form i guess. -
Django cms clear plugin level cache
I have a custom plugin which is basically rendering a form, I had it published over a page from where i removed it later. Problem I am facing is when I see published page the plugin part is till there being rendered, and when i go to modify it there is no existence of plugin. I assume it is a django cms's plugin level cache's problem which i am unable to flush. I've used cache = False , CMS_PLUGIN_CACHE , CMS_PLACEHOLDER_CACHE but no help so far. -
Django: Passing variable from post to get_context_data()
I want to pass a values comming from post form to get_context_data function. But problem is that when i am priting that value in post function then it prints correct value eg:self.start_date but same i print in get_context_data it prints None. And when i remove this line start_date = None then it gives error 'JobListView' object has no attribute 'start_date' class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' # if i remove this then i get error 'JobListView' object has no attribute 'start_date' start_date = None def get_context_data(self, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) company_name = self.request.user.userprofile.user_company context['jobs'] = Jobs.objects.exclude(job_is_deleted = True) context['form'] = JobSearchForm() print(self.start_date) # this print as None return context def post(self, request, *args, **kwargs): self.start_date = self.request.POST.get('start_date',None) print(self.start_date) # this print correct value from form return HttpResponseRedirect('/useradmin/job/') -
Facebook login popup flickering with django-allauth and docker
I am using using django-allauth with docker. While login with facebook getting error in console: Refused to execute script from 'https://www.localhost/static/facebook/js/fbconnect.js' because its MIME type ('image/png') is not executable. And I have forcefully attached fbconnect.js file in layout and all functionality working fine but when I open popup for login with facebook then opened popup is flickering. Why this is happening? Please help.