Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a decorator that works on class-based views and function-based views?
I have some decorators that can be used on top of class-based views like below : @method_decorator(auth0_login_required, name='dispatch') class MyClass(DetailView): ... I'd like to also be able to use it on top of functions inside class-based views like so : class MyClass2(DetailView): ... def get(self, request, *args, **kwargs): ... @auth0_login_required def post(self, request, *args, **kwargs): ... The problem is that the decorator doesn't work the same for these two use case, I'd like to avoid creating two decorators that does the same work. Here's what the decorator looks like : def auth0_login_required(function): def wrap(request, *args, **kwargs): if request.user.is_authenticated or request.user.is_staff: ... ... return function(request, *args, **kwargs) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap For the second use case I have to add self as parameter right before request. I was wondering if there was a way to make it work both ways with one decorator? -
(Hydraulic) Circuit, Component and Branches
I have the following problem. I have a Circuit and a Component model, here a (hydraulic) circuit has one or more (hydraulic) components. However a component is also part of one or more (hydraulic) branches. Say there are two parallel branches than a component is a member of branch 1, branch 2 or a member of both branches. I would like the user to be able to select the branches to which the component is a member. This could be as simple as multiple checkboxes for each branch. Next the Circuit model should calculate the pressure drops for the various parallel branches. If there are two branches than two seperate pressure drops should be calculated. Pressure drop is calculated that if a component is a member of the respective branch than the component pressure drop is added otherwise it's neglected. The simplified Component and Circuit models are as follows class Circuit(models.Model): circuit_name = models.CharField(max_length=200) number_branches = models.IntegerField(default=1) n_pressure_drops = ??? # Stores a value for each of the branches class Component(models.Model): circuit = models.ForeignKey('circuit.Circuit', related_name='components', on_delete=models.CASCADE) component_name = models.CharField(max_length=200) pressure_loss = models.FloatField(default=0) is_a_member = ??? # stores number_branches boolean values I suspect I need another Branch model, since one circuit … -
How to change IntegerField to CharField in Django for populated database?
I need to change model field type from IntegerField to CharField. My database is already in production. When applying migration, the following error is being shown: django.db.utils.ProgrammingError: operator does not exist: character varying >= integer HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. I have a solution but it seems tedious to me: Suppose, 'number' is IntegerField. I want to change it to CharField. Create new CharField 'number_char', clone data from IntegeField 'number', delete 'number' and rename 'number_char' as 'number'. What is the most elegant way of doing this in Django? Thanks in advance. -
Dynamic display of fields in Django admin
I wont to create custom User model, but have some troubles. My model will have choices for staff and players and if I will create user as staff I wont to display only those fields that are defined for staff and same for players. Here is Example of my code. class User(AbstractUser): ROLE = ( ('staff', 'Staff'), ('player', 'Player')) POSITIONS = ( ('headcouch', 'Headcouch'), ('assistenz', 'Assistenz-Coach'), ('supervisor', 'Supervisor')) POSITIONS_PLAYER = ( ('th', 'TH'), ('st', 'ST'), ('vt', 'VT')) user_type = models.CharField(max_length=10, choices=ROLE, default='spieler') My idea is if I choose for example Staff then in my django admin it will display POSITIONS but if I choose Player it will display POSITIONS_PLAYER Can some one show me an example how to implement it? -
How to create a form field for every foreignkey in manytomany relationship in django
I don't understand how to build a specific form in Django. First of all here are my models : class Category(models.Model): name = models.CharField(max_length=200, unique=True) class Assessment(models.Model): name = models.CharField(max_length=200) pub_date = models.DateTimeField(verbose_name=_('date published'), default=timezone.now) classgroup = models.ForeignKey(ClassGroup, verbose_name=_('class'), on_delete=models.CASCADE, related_name='+') category = models.ManyToManyField(Category, through='AssessmentScale', through_fields=('assessment', 'category'),) total = models.IntegerField() class AssessmentScale(models.Model): assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) value = models.IntegerField() I would like to have a form like this html form. Actually, an assessment scale is sub-divided into different categories. So when I create an assessment, I'd like have a form field for each category allowing to add a value via my custom intermediary model AssessmentScale. But I really don't know the django way to build this form. I read this post, wich is similar I think, and someone advise the use of Inline model formsets. But I don't understand how to solve my problem with the latters. Could you help me ? -
Application server not serving simultaneously
I have deployed a Django (rest) application using, gunicorn, nginx and supervisord with most of the standard configuration. Please ask for any specific setting, as I want to be minimalist here. When the data was small in size, I did not notice the synchronous behavior. Now when one of my views is taking a long to return the response all APIs for all users are in pending state (chrome developer tool). Once the blocking view returns (sometimes times out), pending APIs also return after that. I have tried following combinations with no significant improvement as specified in this SO post. Gunicorn with gevent async worker gunicorn server:app -k gevent --worker-connections 1000 Gunicorn 1 worker 12 threads: gunicorn server:app -w 1 --threads 12 Gunicorn with 4 workers (multiprocessing): gunicorn server:app -w 4 I also read and try following similar questions on SO. Make a non-blocking request with requests when running Flask with Gunicorn and Gevent Requests not being distributed across gunicorn workers gunicorn doesn't process simultaneous requests concurrently -
Redirect to a folder in Django
Django currently has a complete system for routing urls. But i have a very specific situation where i am using django but actually need to use urls like in classic php. For example: The url - localhost/reader/theeffort should take me to a folder called theeffort where i have my files index.html, 1.html, 2.html, 3.html, ..... and so on! Now all these files should be accessible by localhost/reader/theeffort/*.html . and not by django's default url system. Is this possible? If yes, how? -
How display a calendar with Django Scheduler
I'm looking, I can't find how use django-scheduler... I wanna do something that seems simple. I'm trying to display a calendar with link events. -
pytest 3.5.0 broke celery tests
After pytest update from 3.4.2 to 3.5.0 my celery tests was crashed with error Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I have tried to add @pytest.mark.django_db to my test, but nothing cahnges. Code: conftest.py: @pytest.fixture(scope='session') def celery_session_app(request): """Session Fixture: Return app for session fixtures.""" yield django_celery_app @pytest.fixture(scope='session') def celery_session_worker(request, celery_session_app, # noqa: pylint=redefined-outer-name celery_worker_pool, celery_worker_parameters): """Session Fixture: Start worker that lives throughout test suite.""" with worker.start_worker(celery_session_app, pool=celery_worker_pool, **celery_worker_parameters) as worker_context: yield worker_context Test: def test_create_task(celery_session_worker): x = debug_task.delay() assert x.status in ['PENDING', 'SUCCESS'] assert x.get(timeout=20) == "Request: '_project_.celery.debug_task'" -
two of forms in one template DJANGO
it's views.py class StudentDetail(DetailView,FormView): model = Student template_name = 'student_detail.html' context_object_name = 'detail' form_class = AddComment def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pk'] = Student.objects.filter(pk=self.kwargs.get('pk')) return context def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): comment = Comment comment = form.save(commit=False) comment.created_by = request.user comment.save() student = get_object_or_404(Student,pk=kwargs['pk']) student.comments.add(comment) return redirect('/students/'+kwargs['pk']) else: print(form.errors) return FormView.post(self, request, *args, **kwargs) it's models.py class Comment(models.Model): created_by = models.ForeignKey(User,related_name='comments',null=True,on_delete=models.CASCADE) message = models.TextField(max_length=1000, unique=False) about = models.CharField(max_length=1,choices=ABOUT_CHOICES,default='L') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.created_by.first_name +' : '+ self.message + ' : ' + str(self.comments.all()) class Score(models.Model): created_by = models.ForeignKey(User,related_name='scores',null=True,on_delete=models.CASCADE) subject = models.CharField(max_length=1,choices=SCORE_SUBJECT_CHOICES,default='A') korean = models.IntegerField(choices=SCORE_CHOICES,default='0') math = models.IntegerField(choices=SCORE_CHOICES,default='0') english = models.IntegerField(choices=SCORE_CHOICES,default='0') other1 = models.CharField(max_length=1,choices=OTHER_CHOICES,default='X') other2 = models.CharField(max_length=1,choices=OTHER_CHOICES,default='X') other1_score = models.IntegerField(choices=SCORE_CHOICES,default='0') other2_score = models.IntegerField(choices=SCORE_CHOICES,default='0') def __str__(self): return self.created_by.first_name +' : '+ self.get_subject_display() +' : ' + str(self.scores.all()) class Student(models.Model): school_year = models.CharField(max_length=4,choices=SCHOOL_YEAR_CHOICES,default='2019') campus = models.CharField(max_length=1,choices=CAMPUS_CHOICES,default='M') type = models.CharField(max_length=1,choices=TYPE_CHOICES,default='N') affiliate = models.CharField(max_length=1,choices=AFFILIATE_CHOICES,default='N') name = models.CharField(max_length=30, unique=True) entry_month = models.IntegerField(choices=MONTH_CHOICES,default=0) entry_day = models.IntegerField(choices=DAY_CHOICES,default=0) comments = models.ManyToManyField(Comment,related_name='comments',blank=True) scores = models.ManyToManyField(Score,related_name='scores',blank=True) picture = ProcessedImageField( upload_to = 'students/%Y/', default = 'students/no-img.jpg', processors=[ResizeToFill(500,500)], options={'quality':80} ) def __str__(self): return self.name it's form.py class AddComment(ModelForm): class Meta: model = Comment fields = ['message','about'] class AddScore(ModelForm): … -
Django Beginner. Rest Framework. How do I get the field data(ManyToManyField) in serializer when I am validating
class Class(models.Model): ... class Student(models.Model): classes = models.ManyToManyField('Class', related_name='students') class ClassSerializer(serializers.ModelSerializer): ... def validate(self, data): students = data['students'] if students.count()+1 >= 40: raise ValidationError('Class is full') return data I want to have a validation that limits the number of students in a class. When I do the above, it seems that data['students'] is a list. Doing len(students) would actually work, but I was told count() is better for query sets. How do I get students queryset instead of a list of students? I may want to do .filter() with them too. -
Django is_valid() always returns false , why?
views.py def login(request): user = "not logged in" if request.method == "POST": # Get the posted form MyLoginForm = LoginForm() print(MyLoginForm.is_valid()) # returning false everytime if MyLoginForm.is_valid(): user = MyLoginForm.data["user"] return render(request, 'loggedin.html.txt', {"username": user}) else: MyLoginForm = LoginForm() return render(request, 'loggedin.html.txt', {"username": user}) Why is_valid() is returing flase everytime , kindly help me out with this here is the Html file .... {% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Identifiant" name = "user" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <input type = "password" style = "margin-left:20%;" placeholder = "password" name = "password" /> </center> </div> <br> <div style = "max-width:470px;"> <center> <button style = "border:0px; background-color:#4285F4; margin-top:8%; height:35px; width:80%;margin-left:19%;" type = "submit" value = "Login" > <strong>Login</strong> </button> ....... -
Django 1.11 circular import error, Also url pattern... current path doesn't match
I'm using django 1.11. I'm getting a circular import error when I include: url(r'irbSite/', include('irbSite.urls', namespace = 'irbSite')), url(r'irbSite/', include('django.contrib.auth.urls')) in urls.py in the project folder: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', auth_views.LoginView.as_view(template_name = 'irbSite/login.html'),name='login'), url(r'irbSite/', include('irbSite.urls', namespace = 'irbSite')), url(r'irbSite/', include('django.contrib.auth.urls')) ] However, if I do not include it my login page will appear, but when I click the register link I get this error: "url patterns" ... "^admin/ ^$ [name='login'] The current path, register.html, didn't match any of these." My directory (not code): irbsite pycache migrations static templates init.py admin.py apps.py forms.py models.py tests.py urls.py views.py project pycache init.py settings.py urls.py wsgi.py manage.py My views.py (in irbSite folder): from django.contrib.auth import login, logout from django.core.urlresolvers import reverse_lazy from django.views.generic import CreateView from . import forms class Registration(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'register.html' My urls.py (in irbSite folder): from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'irbSite' ulrpatterns = [ url(r'logout/$', auth_views.LogoutView.as_view(),name='logout'), url(r'register/$',views.Registration.as_view(template_name = 'irbSite/register.html'),name='registration'), ] I'm modifying a tutorial that I followed from a udemy course. I've hit a wall, any … -
django manage.py runserver error Unknown system variable 'innodb_strict_mode'"
I'm using python 2.7.14, django 1.11 and mysql 5.7 to my local server and it work fine until i tried to connect in our external mysql 5.1 database and got below error when checking my connection (python manage.py runserver). I suspected because external Mysql is version 5.1. Below is my database setting and error message: default': { 'ENGINE': 'django.db.backends.mysql', #'NAME': os.path.join(BASE_DIR, 'db.mysql'), #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'NAME': 'Mfg', 'USER': 'arastra', 'PASSWORD': '', #no password 'HOST': 'localhost', 'PORT': '3356', # Tunnel set-up. File "C:\Python27\Lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\Python27\Lib\site-packages\MySQLdb\cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "C:\Python27\Lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue django.db.utils.OperationalError: (1193, "Unknown system variable 'innodb_strict_mode'") -
Django HTML QuerySet
Is there a way to check if the student exsist in the database class table, since student is assigned as a forgeinkey in the table. I want to achive this without open another loop. index.html: <ul> {% for student in studentList %} {% if student in classList %} <li><a href="#">{{ student.name }}</a></li> {% endif %} {% endfor %} views.py def index(request): context = { 'studentList': Student.objects.all(), 'classList': ClassRoom.objects.all(), } return render(request, 'resurs/index.html', context) -
What could be the easiest way to Import a CSV file into a Django Model?
I am making an app in DJANGO that deals with a lot of 'questions'. That is, there are a question table specified in Model and there will be more or less thousand of questions. Now, I have an excel file in hand where all the questions are and I can make a csv file from there. I just need to get the CSV data in my question table. What could be the possible easiest way to do that? Can any one tell about any tool, process, code to do so? Thanks a lot! -
Get request through postman with JWT
I have installed pip install djangorestframework-jwt i have modified settings to REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } I have got a token by giving my credentials and then passing that token through bearer token in authorization in postman When I do a api call through postman it gives me error saying { "detail": "Authentication credentials were not provided." } The api call is for a BookViewSet. Why does it say details not provided after giving the token also. plz help me, Thanks. -
I want to maintain order. When I post something that recent post will come first like other platforms
I'm using Django 2.03, recently. I have three models to post three kinds of data into one template. I have used three "For tag" to render it into the template. when I post something, that post it does not comes first. Cause it renders that post from that "for" tag. Sample at below. I want to maintain order. When I post something that recent post will come first like other platforms. {% for obj in quickword %} <div class="ui large header" id="quick-word-description"> <p> {{ obj.Initial_keyword_choices }} {{ obj.description }} </p> </div> {% endfor %} <!-- cards type two #### add product post card --> {% for product in addproduct %} <div class="ui center aligned content"> <h3><a class="header" href= {% url 'add-product-view' %}> {{ product.product_name|capfirst }}</a></h3> <p> <span class="date"><span class="launched-in">Launched in</span> <strong> Sep 2014</strong></span> </p> </div> {% endfor %} <!-- cards type three ##### article post card --> {% for article in article_view %} <div class="content"> <a href= "{% url 'details' article.id %}" class="header">{{ article.Initial_keyword_choices }} {{ article.article_title|title }}</a> <div class="description"> <p style='color: black;'>{{ article.article_description|capfirst|truncatewords:25 }} </p> </div> </div> {% endfor %} -
Access Dictionary Value inside list in Django Template
I have a dictionary inside a list. I want to access dictionary value inside django template. How can I get that? views.py def payment_status(request): l1=[] cand = CandidateDetail.objects.all() for person in cand: for num in range(0,paid['count']): if paid['items'][num]['email']==person.email and paid['items'] [num]['status']=='authorized': cand_dict = {'first_name':person.first_name, 'last_name':person.last_name, 'email':person.email, 'paid':'Yes'} l1.append(cand_dict) return render(request, 'desk/payment_status.html',{'cand_list':l1, 'cand_len':len(l1)}) html file <div class="col-md-10"> <h3>Candidate Payment Status</h3> <table class="cand_list"> <tr> <th>Name</th> <th>Email</th> <th>Payment Status</th> </tr> {% for item in cand_len %} <tr> <td>{{ cand_list[item]['first_name'] }} {{ cand_list[item] ['last_name'] }}</td> <td>{{ cand_list[item]['email'] }}</td> <td>{{ cand_list[item]['paid'] }}</td> </tr> {% endfor %} </table> </div> The error I am getting is -- Could not parse the remainder: '[item]['first_name']' from 'cand_list[item]['first_name']' -
Django - how to generate oauth2 credentials after successful google login
i have successfully configured everything to work with google oauth2. i have used django-rest-framework-social-oauth2 the user gets registered if new in DB, the user get logged in if old everything working fine i want to generate a oauth2 credentials if the user successful logged in using google oauth like this { "access_token": "jCvkP4l7jt88D2O1H1WnNC5wx56knj", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "u51zWkv056BNMsug8Qw6KCgk5Qtyp" } -
Related field id in POST request in Django Rest Framework
I am creating the object with just only related field id. I have searched a lot but couldn't get the answer. Here is my code models.py: class Resturant(models.Model): name = models.CharField(_('name'), max_length=100) class Menu(models.Model): resturant_id = models.OneToOneField(Resturant, related_name='resturant', on_delete=models.CASCADE) serializers.py: class MenuSerializer(serializers.ModelSerializer): returant_id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Menu fields = ['id', 'created_at', 'resturant_id'] views.py: class CreateMenuAPIView(APIView): def post(self, request, *args, **kwargs): serializer = MenuSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) I am getting this error while sending { "resturant_id": 2 } in POST request. DETAIL: Failing row contains (14, 2018-04-02 09:36:43.261849+00, null). Any help would be appreciated ! -
Remove email field from Django Allauth signup
How do I remove the email field from Django allauth signup? No settings here show any option to remove it. Any idea? -
How do I get 1 day before timezone.now()
I have a button that should appear 1 day before the model object's start_date. In my view I have a functions that tells me if the object's start_date or end_date is now. def has_engagement(self): from rental.models import Inquiry inquiries = Inquiry.objects.filter(inquiryequipment__equipment=self).filter(start_date__lte= timezone.now()).\ filter(end_date__gte=timezone.now()).filter(status="CO") if not inquiries: return False # no current confirmed engagement else: return True # there is a current confirmed engagement instead of this, i need to check if today is a day before the start or end dates. Any ideas? Thanks -
Django mocks not working as expected
I'm struggling with django mock; I have even simplified an unit test but the test is still failing. I want to verify that a method is called (even with any parameter), but the "assert_called_once_with" always returns False. Currently I'm trying: @patch('utils.make_reset_password') def test_shouldHaveCalledMakeResetToken(self, mocked): user = User.get(...) make_reset_password(user) mocked.assert_called_once_with(user) Even this simple example is failing with: AssertionError: Expected 'make_reset_password' to be called once. Called 0 times How this is possible? What am I doing wrong? Thanks in advance -
print access_token of google oauth user
i have used django-rest-framework-social-oauth2 added this to templates 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', added backends 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOpenId', 'social_core.backends.google.GoogleOAuth2', google keys SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "***" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "***" setup everything on the https://console.developers.google.com when i access this link http://localhost:8000/auth/login/google-oauth2/ from browser everything working fine my logged user details are register in DB if new, else login if old. then the social auth auto redirects to this link http://localhost:8000/accounts/profile/# which is empty. i need the access token of the google user so that i can convert the token to oauth token in this link http://localhost:8000/auth/convert-token with my site client id & secret i created. after that i can use the converted token to grant access to my API request