Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium test URL not found in Django
I'm new to Selenium and I'm getting "URL not found" error during a test. It's kinda strange since everything is working in my production evnviroment. I tried to replicate my production DB in my test enviroment but I still get the same error. I was just improving the Tutorial project of Django documentation v. 1.11. Here is my models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.PositiveIntegerField(validators=[MinValueValidator(0)], default=0) def __str__(self): return self.choice_text Here is the urls.py : app_name = 'polls' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^specifics/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] And finally we have the tests.py part: ### SELENIUM ### class VoteTest(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(VoteTest, cls).setUpClass() cls.selenium = webdriver.Firefox() cls.selenium.implicitly_wait(10) Question.objects.create(question_text="Sample_question", days=1) Choice.objects.create(choice_text="Sample_choice", question=q, votes=1) def test_vote(self): self.selenium.get('%s%s' % (self.live_server_url, '/polls/')) self.selenium.find_element_by_xpath('//a[@id="1"]').click() # Here I get the "URL not found error", the URL is '.../polls/specifics/1/ As I said the URL is reachable from the webserver. I also print the values of the test DB during the tests and everything seems fine with IDs. … -
reset_sequence in pytest-django
I have posted my question to the pytest-django. But it seems non-active at least 2 weeks. I decided to ask my question here. In my test I want to use reset_sequence=True. How to do that in pytest-django? -
How to make login and signup in one url
Im new in Django. Got a problem. I have my urls.py: path('login/', auth_views.login, name='login'), path('reset/', auth_views.password_reset, name='reset'), path('logout/', auth_views.logout_then_login, name='logout'), path('signup/', views.signup, name='signup'), path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate'), So i can login using one HTML file and signup using other. But i have a HTML including and login and signup. The problem is that if i use /login/ url i can only log in and if i try the same forms to sign up - it does not work. The same with signup (only signup). How can i make both that functions work using one url and one HTML file. Thanks! Here is HTML: <body> <div class="login-page"> <div class="form"> <form class="register-form" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="имя пользователя" required autofocus id="id_username" maxlength="150"/> <input type="text" name="email" placeholder="email" required id="id_email" maxlength="200" /> <input type="password" name="password1" placeholder="пароль" required id="id_password1"/> <input type="password" name="password2" placeholder="повторите пароль" required id="id_password2"/> <button type="submit">создать</button> <p class="message">Уже зарегистрированны? <a href="#">Войти.</a></p> </form> <form class="login-form" method="POST" action="{% url 'login' %}"> {% csrf_token %} <input type="text" name="username" placeholder="имя пользователя" for=<input type="text" name="username" maxlength="254" autofocus required id="id_username" /> <input type="password" name="password" placeholder="пароль" for=<input type="password" name="password" id="id_password" required /> <p style="color: red">{{ error }}</p> <button type="submit">войти</button> <p class="message">Не зарегистрированны? <a href="#">Создать аккаунт.</a></p> </form> </div> </div> … -
Django admin JavaScript on forms frontend
Is there a good/easy way of implementing the JavaScript from django.contrib.admin.static.js to your own forms on the frontend, like inlines.js, prepoplulate.js etc. so you can get the same behavior dealing with forms. Or is this even advisable. -
How do I negate/invert a django-filter (exclude *unless* filter is active)?
Given a filter set like this: class MyFilter(django_filters.rest_framework.FilterSet): include_unusual_entries = django_filters.BooleanFilter(method='noop') I would like the 'default' queryset to be MyModel.objects.exclude(unusual_state=True) and only if the include_unusual_entries filter is set, I would like it the queryset to be MyModel.objects.all() Am I missing an obvious way to solve this? I don't see a way to set invert=True on a filter, or a way to set always_filter so that I could put an if into the method. For now, I solved it by overriding the qs property on my filter set, but it feels pretty wrong: @property def qs(self): queryset = super(MyFilter, self).qs if 'include_unusual_entries' in self.data: # if inclusion is explcitly enabled return queryset else: # if inclusion is *not* explicitly enabled (the default) return queryset.exclude(unusual_state=True) -
How to put many fields of django-tables2 into one?
I have a django table declared as follow : class BookTable(tables.Table): user= tables.TemplateColumn("""{% include 'books/user.html' with user=record.created_by %}""") books= tables.TemplateColumn( """ {% if record.g_books.count %} <div class="panel-body"> {% include 'books/details/detail.html' with book=record %} </div> {% else %} No New Books {% endif %} <div> </div> """) actions = tables.TemplateColumn("""{% include 'books/action.html' with book=record %}""") I want to make changes on the order and some styles of fields and I want to render only one field that groups user, books and actions fields . Is that possible with django-tables2 or it's a bad way to do so ? New with django-tables2 , any advice is welcome Thanks. -
email from vk django-rest-framework-social-oauth2
I installed django-rest-framework-social-oauth2 in my project on that tutorial https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 in my settings file i adding this SOCIAL_AUTH_VK_OAUTH2_SCOPE = [ 'email', ] SOCIAL_AUTH_VK_EXTRA_DATA = [ ('email', 'email'), ] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) when i send request on url /convert-token, created user, but without email field -
how do i use Django cluster or loading balance. Django +Nginx+uWSGI
i deployed the environment of Django +Nginx+uWSGI successfully. i wish i can run multi-django server with one nginx. the configuration below is nginx's conf: upstream django { server unix:///path/to/your/mysite/mysite.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } does it work just use ip:port? e.g.: upstream django { #server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 192.168.0.1:8001; # for a web port socket (we'll use this first) server 192.168.0.2:8002; server 192.168.0.1:8004; server 192.168.0.2:8004; } i want to use Unix sockets instead of ports. because the mysite.sock files maybe in many different remote hosts.how do i configure nginx's conf? thanks a lot and happy christmas! -
django-el(endless)-pagination not wokring with AJAX
I'm using django-el-pagination(Digg-style pagination) in my project, but the results don't appear to be using AJAX. I need to move the page without refreshing, but it seems that ajax is not working properly. view.py @page_template('dmmactress/actress_dev_page.html') def actress_dev(request, id, extra_context=None): instance = get_object_or_404(ActressInfo_two, pk=id) moviesinfo = ActressinfoMovielist_co.objects.filter(actressinfo_id=id).prefetch_related('movielist').order_by('movielist') context = { 'actresses': instance, 'moviesinfo':moviesinfo, } if extra_context is not None: context.update(extra_context) return render(request, 'dmmactress/actress_dev.html', context) actress_dev.html ........ <thead> </thead> <tbody id="entries" class="endless_page_template"> {% include page_template %} </tbody> ........ actress_dev_page.html {% load el_pagination_tags %} {% paginate moviesinfos %} {% for movieinfo in moviesinfo %} {{ movieinfo.movielist.movie_number|upper }} {% endfor %} {% get_pages %} {% if pages.paginated %} {{ pages }} {% endif %} The result is the same as the default paging without using ajax. Also, when I click the "page" link, I'm taken to "/? page = 2", which includes refreshing the entire page and is not what I want to do. And on the Chrome Console, no logs appear when the page reloads. (The js file has been successfully loaded.) What am I doing wrong? -
Restart server using any other key than Break
I am running a Django server in Windows on Google Compute Instance. I am connecting to it using Microsoft Remote Desktop app on macOS. The problem is whenever I want to quit the server I have to supply a Ctrl+Break command to the command prompt and my MacBook keyboard doesn't have a Break key. Even On-Screen keyboard doesn't have the Break Key. So instead of finding ways to find the break key, I want to find the ways to override the requirement of it. So my question is, is there any way I can change the shortcut for killing the server to ctrl+c or ctrl+z or any other available key instead of break in Django? -
ValueError: The view accounts.views.register didn't return an HttpResponse object. It returned None instead
I am getting this error and I have not been able to fix this. Here are the files:views.py from django.shortcuts import render,HttpResponse from django.contrib.auth.forms import UserCreationForm # Create your views here. def home(request): numbers=[1,2,3,4,5] name='satya' args={'MYname':name,'numbers':numbers} return render(request,'accounts/home.html',args) def register(request): if request.method=='POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/accounts') else: form=UserCreationForm() args={'form':form} return render(request,'accounts/reg_form.html',args) Here is reg_form.html {% extends 'base.html' %} {% block body %} <div class="container"> <h1> Register </h1> <form method="post"> {% csrf_token %} {{form.as_p}} <<button type=" submit " class="submit" >Submit</button> </form> </div> {% endblock %} I have imported the things correctly but not getting as what is wrong. -
Setting up two throttle rates in one view in django
I am using Django 1.11 and Python 2.7 and now tried to include throttling into my webservice. This seemed quite easy at the beginning as Django does all the work for you. But now I wanted to only throttle one of my views and differentiate between authenticated users and logged in users aswell as setting up a 'burst' rate (e.g. 5 requests per min) and a 'sustained' rate (e.g. 100 requests per day). Achieving this, I built 4 throttle-classes: class SustainedAnon(AnonRateThrottle): rate = '100/day' class BurstAnon(AnonRateThrottle): rate = '6/minute' class SustainedUser(UserRateThrottle): rate = '1000/day' class BurstUser(UserRateThrottle): rate = '20/min' I did not change the settings.py at all as it is not needed according to the docs (Django Throtte Docs). The only file I edited was my views.py in which I added this line to my Statistics class class Statistics(APIView): throttle_classes = (SustainedAnon, BurstAnon, SustainedUser, BurstUser) It almost does what it is supposed to do. It does only throttle the Statistics class and throttles logged in and anonymous users seperately, but it does not throttle the rates correctly. When not logged in, the App starts throttling after 3 requests instead of 6 and when logged in after 10 requests instead of … -
Building docker image with Django 2.0 fails
I am currently building a docker image with the latest version of Django but during the build I get this: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-9LueOB/Django/ You are using pip version 8.1.2, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. The command '/bin/sh -c INSTALL_PKGS="python-pip oracle-instantclient-tnsnames.ora afs_tools_standalone nss_wrapper openssh-clients cx_Oracle libmemcached-devel python-ldap mod_wsgi httpd MySQL-python wassh-ssm-cern wassh" && INSTALL_PKGS_BUILD="gcc python-devel zlib-devel" && yum install -y centos-release-scl && yum update -y && yum install -y --setopt=tsflags=nodocs --enablerepo=centosplus $INSTALL_PKGS && yum install -y $INSTALL_PKGS_BUILD && rpm -e --nodeps centos-logos && pip install --upgrade && pip install -r requirements.txt && rm requirements.txt && yum remove -y $INSTALL_PKGS_BUILD && yum clean all -y && rm -rf /var/cache/yum && mkdir /var/django/ && mkdir -p /var/django/home/ && mkdir -p /usr/local/bin/ && mkdir -p /run/httpd/ && chown -R root:root /run/httpd && chmod a+rw /run/httpd' returned a non-zero code: 1 On my requirements.txt I am using this: Django==2.0 djangorestframework==3.2.1 pyapi-gitlab==7.8.4 pylibmc==1.5.0 django-logtail python-gitlab Any idea of why this is happening? -
Django + Pug(Jade) - how to pass object to mixin?
I installed pypugjs, added it to settings.py, it works fine, but when I'm trying to pass object to Pug mixin - I got a TemplateSyntaxError - "Could not parse the remainder: '{age:20' from '{age:20'" mixin card(data) div #{data} +card({age:20, name:'Alex'}) How to pass more than one named filed to Pug mixin in Django? -
Create ViewSet which Auto Generate when access - Django Rest Framework
I am creating a Notification apps by Django Rest Framework which users can MARK AS READ ALL notification by using PATCH API in frontend. How can I create a viewset and serializer can do this task. This serializer and viewset below just for PATCH only one notification object, but I want to do it all with Notifications which have field is_read = False My Serializers: class NotificationEditSerializer(ModelSerializer): class Meta: model = Notification fields = ( 'id', 'is_read' ) My Viewset: class NotificationEditAPIView(RetrieveUpdateAPIView): queryset = Notification.objects.all() permission_classes = [AllowAny] serializer_class = NotificationEditSerializer lookup_field = 'id' My URL: urlpatterns = [ url(r'^$', NotificationListAPIView.as_view(), name='list'), url(r'^(?P<id>[0-9]+)/mark_as_read/$', NotificationEditAPIView.as_view(), name='update'), ] Hope your helps! -
In the django rest swagger how I write the description of A @api_view,so I can get a field to post the request params?
What content I show write here? Or somewhere else? -
Django Datepicker form nicely above table view - bootstrap css issue
I have a Django app, which Im trying to have a datepicker search form on top of the table nicely. I am trying to accomplish an arrangement something like this https://imgur.com/a/d6h1q But I am getting like this https://imgur.com/a/TOlqB .... <div class="panel-body"> <div class="row"> <form action="{% url 'employee-attendance_search_date' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ attendance_search_date_form }} <button type="submit" class="btn btn-primary">Search</button> </form> </div> <table class="table table-bordered table-hover table-striped"> <thead> .... Im using Datepicker for the search field. https://github.com/nkunihiko/django-bootstrap3-datetimepicker Can someone help fix that html/bootstrap code to make that sort of arrangements ? -
Delete table row django rest framework
I have a two buttons in my datatable that I'm trying to utilize to delete and edit an row. In my ModelViewSet I'm trying to do something like this: from django.shortcuts import get_object_or_404 from rest_framework import viewsets, filters, status from rest_framework.decorators import detail_route from rest_framework.response import Response from beaconpro.company.models.organization_model import OrganizationModel from beaconpro.company.restapi.serializers.organization_model_serializer import OrganizationModelSerializer from beaconpro.company.restapi.pagination import StandardResultsOffsetPagination class OrganizationViewSet(viewsets.ModelViewSet): queryset = OrganizationModel.objects.all() serializer_class = OrganizationModelSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_fields = ('id', 'organization_name') ordering_fields = ('id', 'organization_name', 'delete_organization_name') search_fields = ('id', 'organization_name', 'delete_organization_name') pagination_class = StandardResultsOffsetPagination def update(self, request, *args, **kwargs): return self.create(request, args, kwargs) def destroy(self, request, *args, **kwargs): organization = get_object_or_404(OrganizationModel, pk=kwargs.get('pk')) organization.delete() return super(OrganizationViewSet, self).destroy(request, *args, **kwargs) @detail_route(methods=['update']) def edit_organization_name(self, request, pk=None): pass @detail_route(methods=['delete']) def delete_organization_name(self, request, pk): organization = get_object_or_404(OrganizationModel, pk=pk) organization.delete() return Response(status=status.HTTP_200_OK) so I'm passing delete_organization_name into datatable using data to a button like this: $('#searchCompanyList').DataTable( { processing: true, serverSide: true, searchDelay: 1000, order: [[ 1, "desc" ]], orderMulti: false, pageLength: 10, ajax: { url: '/api/organization/', data: function(data) { data.limit = data.length; data.offset = data.start; data.search = data.search['value']; if (data.order[0]['dir'] == 'asc') { data.ordering = data.columns[data.order[0]['column']].name; } else { data.ordering = '-' + data.columns[data.order[0]['column']].name; } }, dataFilter: function(data) { var json … -
Exception Value: 'ExcelInMemoryUploadedFile' object has no attribute 'save'
I'm getting this error when try to save request file(i.e: excel) in django . And one more thing is it possible to read the request excel sheet without downloading, if yes please suggest that way. Code : filename = request.data.get("excel_file").name file = request.data.get("excel_file").save(filename) -
Notifications/Activity Stream using Multiple foreign Keys
I need to create a simple Notification app, that send messages to admin or users, depending on the action. I don't want to use Generic Foreign Keys because of database possible integrity issues and low speed, number of queries I know their are packages like activity-stream, django-notifications but both are using GFK, and are not exactly what I want I have the following model: class Action(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='activity') account = models.ForeignKey(Account, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) and create the following utility function to call from the view/model of the Foreign Key. def create_action(user, verb, target=None): action = Action(user=user, verb=verb, target=target) action.save() The issues: I don't know how to "tell" to the view/model using target argument one Foreign Key to pass, save I need to ensure that one and only one of the Foreign Keys is set when saving (usually by an editor in admin) -
Bulk index django model to elastic search
I am trying to bulk index my django model to elastic search 6, my plan is to run this as a cron once a day to update the index. import requests data = serialize('json', CapitalSheet.objects.all()) data += "\n" r = requests.post("http://127.0.0.1:9200/capitalsheet/_bulk", json = data) print(r.content) I am getting this error: b'{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"The bulk request must be terminated by a newline [\\n]"}],"type":"illegal_argument_exception","reason":"The bulk request must be terminated by a newline [\\n]"},"status":400}' If you can suggest something better, I would be glad. -
Cannot order by time using model manager
I made the following model manager class TaskManager(models.Manager): def get_queryset(self): return super(TaskManager,self).get_queryset().order_by('time__hour') But there is an error which says Cannot resolve keyword u'hour' into field. Join on 'time' not permitted. My models.py looks something like this - class Task(models.Model): content = models.TextField() slug = AutoSlugField(populate_from='content') time = models.DateTimeField() objects = TaskManager() I don't know what I am doing wrong. Please help how should I go about doing this. -
Messaging App in Django
I'm trying to create a messaging app. Here's what I tried, Here's the model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Here's what I tried in view to filter the User if conversation between any user & request.user occurred, def profiles(request): user1 = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('receiver__id') user2 = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('sender__id') users = User.objects.filter(id__in=user1).filter(id__in=user2) return render(request, 'chat/users.html', {'users': users}) Here I can filter out the users but problem is I couldn't re-order them based upon when sent a message most recently as we see on social networks. How can I do that? -
Django Form ChoiceField with Queryset
I need to get the other users of the firm within the ModelForm to set the main user, I do not know how to get variables inside the form for this? In the view the variable needed would be: request.user.profile.firm This is the form that needs to be created. class FirmForm ( forms.ModelForm ): primary = forms.ModelChoiceField ( queryset = User.objects.filter ( name = request.user.profile.firm )) class Meta: model = Firm Thank you and Happy Holidays! -
Report lab size in paython
My report Column is too many. can some one guide me how to make pdf size big in Reportlab and all column show on page. response = HttpResponse(content_type='"application/pdf"') response['Content-Disposition'] = 'attachment; filename=users.pdf' doc = SimpleDocTemplate(response, pagesize=landscape(A4)) record_for_frontEnd = BillManagement.objects.filter(**kwargs) pdf_data = [['Creation Date', 'Bill Number', 'Name', 'Quantity', 'Product/Service Name', "Ref No", "Cost", "discounted Price", "Net Amount", "Costomer Name", "Commission Staff", "Commission Amount", "Patyment Type"]]