Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django-rest-framework, is it possible to use oauth and session authentication simultaneously?
Here's what I'm trying to do: I'm building a finance app. There's a web component, which is using Django templates and jQuery for AJAX requests, and a mobile client. My goal is to use session-based authentication for the AJAX requests coming from the web app, using django-allauth for authentication, and OAUTH2 for the mobile app with django-oauth-toolkit. I'm using django-rest-framework for the endpoints. The AJAX behaviour was working fine before I added the OAUTH middleware/authentication backend. This code from my view.py now prompts a 401 unauthorized when accessed via AJAX call, even when the user is authenticated using django-allauth. It worked previously (and still works when accessed via curl with an access token): @api_view(['GET']) def portfolio(request): """ Get account balances, total portfolio value in CAD, and balances converted to CAD at current market rates. """ try: account = request.user.account except ObjectDoesNotExist: return Response(status=Status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = AccountSerializer(account) return Response(serializer.data) Here are the relevant bits of mysettings.py: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = ( 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', 'oauth2_provider.backends.OAuth2Backend', ) An older method I wrote that doesn't use django-rest still works fine: @verified_account_required def get_rates(request): if request.method == 'POST': … -
Django @login_required decorator does not redirect to specific page
I'm trying to make a limited user edit page if the login is not executed. After logging in, the edit page opens with any user_id in the url. Although edit page should be open only with user_id already logged in user. For example, I logged in with user_id=7, so only one next url (http://127.0.0.1:8000/user/7/edit) have to have access to edit page. And this edit page is available by any next urls also (http://127.0.0.1:8000/user//edit) Are there any errors or mistakes in my code? I already have cleared cache in Opera and Chrome, but issue still exist. Django ver. 1.11.9. LOGIN_URL is not defined in settings.py urls.py urlpatterns = [ url(r'^login/$', user_login, name='user-login',), url(r'^(?P<user_id>\d+)/edit$', user_edit, name='user-edit',), ] views.py def user_login(request): login_form = AuthenticationForm(request.POST or None) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: # login(request, user) print("next is {}".format(request.GET.get('next'))) return redirect(user_edit, user.id) else: return redirect(user_login) return render(request, 'user_login.html', {'form': login_form}) @login_required(login_url='/user/login/') def user_edit(request, user_id): print(request, request.user) print("next is {}".format(request.GET.get('next'))) return render(request, 'user_edit.html', {'userid': user_id, 'user': request.user}) -
Celery very strange error, when calling another method
I call the Celery tasks with two arguments: @app.task my_task.delay(path, company_id) In task I call another method, an utility: @app.task def my_add_task(path, company_id): crop_image(path) the utility: def crop_image(path): image = Image.open(path) image_clone = image.copy(image) image_clone.thumbnail(100, 100) I get the following error: File "...tasks.py", line 15, in my_add_task crop_image(path) File "...utils.py", line 29, in crop_image image_clone = image.copy(image) TypeError: copy() takes 1 positional argument but 2 were given If I remove the company_id from the task everything works, so no 2 arguments now passed to crop_image my_task.delay(path) If I remove crop_image, and return the arguments no issue with them are ok I used celery purge do be sure no message are left -
How can I set a nginx index page for the domain name using Django?
I am using Django and nginx to make a web site.(Plus, uWSGI, and AWS EC2...) I already set nginx for IPv4 domain(http://123.45.67.89), so I can get to the correct index page. But I am not sure why I cannot do it for domain name(http://example.com)! I can just access "defalut page"(Welcome to nginx!) for nginx. Could you help me to do for a domain name? My Django project file(root) is /home/ubuntu/proj/mysite My index page is in /home/ubuntu/proj/mysite/taxi/templates/taxi/index.html I've set all in AWS Route 53. Following is my /etc/nginx/sites-enabled/mysite server { listen 80; server_name 123.45.67.89; #example #access_log /var/log/nginx/log/mysite.access.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/proj/mysite; } location / { root /home/ubuntu/proj/mysite; index /taxi/templates/taxi/index.html; #location of index page include /home/ubuntu/proj/mysite/uwsgi_params; uwsgi_pass unix:/run/uwsgi/mysite.sock; } } I don't know what I show you more to help me... Actually I am not sure whether it is a problem in nginx or not. -
Django IntegrityError while updating a record
I have a model with double columns as primary key. I do a filter on it and get the records I want, change a field and save it. As I know save will update the record and does not create a new instance of the model in db. so It should be all okay but I'm stuck with an integrityError Duplicate entry '10-2' for key 'PRIMARY' when I try to save the record Here is the code snippet: for anal in analysis: anal.analysisresult_path = some_string anal.save() #this line is where the error occurs And here is my model: class AnalysisResult(models.Model): analysisresult_path = models.CharField(db_column='analysisResult_path', max_length=255, blank=True, null=True) # Field name made lowercase. detectionresult_path = models.CharField(db_column='detectionResult_path', max_length=255, blank=True, null=True) # Field name made lowercase. targetcode = models.ForeignKey('TagetCode', models.DO_NOTHING, db_column='targetCode_id') # Field name made lowercase. request = models.ForeignKey('Request', models.DO_NOTHING, primary_key=True) class Meta: managed = False db_table = 'analysis_result' unique_together = (('request', 'targetcode'),) -
Django: extract time from datetime keeping the tzinfo?
In Django, how do extract the time of a datetime.datetime object keeping the tzinfo? In my code, I want a user to be able to edit the start time and end time of an object which contains start/end datetimes. That why I'm trying to create a form to edit the time part only: Forms class UpdateServiceForm(forms.ModelForm): class Meta: model = Service fields = tuple() start_time = forms.TimeField() end_time = forms.TimeField() Views class ServicesUpdateView(UpdateView): model = Service form_class = UpdateServiceForm def get_form(self, form_class=None): """ overrided to get start/end times from start/end datetimes """ form = super().get_form(form_class) form.fields['start_time'].initial = form.instance.start.time() form.fields['end_time'].initial = form.instance.end.time() return form It does not work because: form.instance.start returns an aware datetime (expected) form.instance.start.time() returns a naïve time. (I expected an aware time here. Of course, the bad hour is displayed in the form.) I browsed the django.utils.timezone section without finding the right tool. Any idea how to do this in a clean way? Thanks. -
How to run a custom aggregation on a queryset?
I have a model called LeaveEntry: class LeaveEntry(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, limit_choices_to={'is_active': True}, unique_for_date='date' ) half_day = models.BooleanField(default=False) I get a set of LeaveEntries with the filter: LeaveEntry.objects.filter( leave_request=self.unapproved_leave ).count() I would like to get an aggregation called total days, so where a LeaveEntry has half_day=True then it is half a day so 0.5. What I was thinking based on the django aggregations docs was annotating the days like this: days = LeaveEntry.objects.annotate(days=<If this half_day is True: 0.5 else 1>) -
AttributeError: module 'json' has no attribute 'dumbs' [on hold]
I am tryin to create this flask app, but I receive this error AttributeError: module 'json' has no attribute 'dumbs' I checked most of the solutions which says there is a possible duplicate. I double checked but can't find any. my file name is recommender.py and other files in my directory nothing close to json I moved all my files to a new directory which only contains 3 files i'm using but still the same error. I created a virtual environment with my dependencies only, but still the same. Tried Python 2.7 and 3.5 I even removed the Json file from my python installation and downloaded it from the python directory on github, but still the same I even uploaded my code to a clean server, created a virtual env to test it again, but still I get the same error I tried running json.dumbs on another file and it works fine my_list = [ 'a', 'b', 'c'] my_json_string = json.dumps(my_list) those are my dependencies I am importing import pandas as pd import gensim.models.word2vec as w2v import codecs import itertools import regex import os import re import urllib from flask import Flask, url_for, Response, jsonify import json those are the … -
'AnonymousUser' object has no attribute '_meta' when trying to update user
In my app I am getting an error when trying to update a user info. my code is the following: def CandidateSignIn(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = MyUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) registered = False if request.method == "POST": form = TeamMembersFormUpdate(data=request.POST, instance=request.user) if form.is_valid(): user = form.save() user.set_password(user.password) user.save() #registered = True return HttpResponseRedirect(reverse('registration:HRlogin')) else: print("Error!") else: form = TeamMembersFormUpdate() return render(request,'candidateSignIn.html', {'form':form, 'registered':registered}) and apparently I am getting the error from the line form = TeamMembersFormUpdate(data=request.POST, instance=request.user) do you have any idea on how to solve this ? -
Django - Select related or join on two different base models
I have two base models SiteData and Showoroom Service that have model structure as per the below. I need the SiteData info but I also would like to get link_type from the showroomservice model if there is a matching ID. ive tried a few things thus far, none are getting what I need, what is the best way to achieve this? Thanks select related >>> nd = ShowroomService.objects.select_related('site').all() >>> nd Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 229, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 590, in __repr__ u = six.text_type(self) TypeError: __str__ returned non-string (type SiteData) Combining : >>> complete_data = site_data | monitoring_data Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 310, in __or__ combined.query.combine(other.query, sql.OR) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 529, in combine "Cannot combine queries on two different base models." AssertionError: Cannot combine queries on two different base models. chaining >>> final_data = chain(monitoring_data, site_data) >>> for i in final_data: ... '{} {}'.format(i.location,i.link_Type) ... Traceback (most recent call last): File "<console>", line 2, in <module> AttributeError: 'ShowroomService' object has no attribute 'location' sites.models.py class SiteData(models.Model): location = models.CharField(max_length=50) site_type = models.ForeignKey(SiteTypes, … -
Using Django Summernote without migration
Is there a way of using django-summernote without applying the migration? I am not using the attachment upload feature, so it's kinda useless for me to have a new table in my DB. I think that it should be parametrized along with the disable_upload option as it looks like uploading is the only reason for having a migration. -
Can I create virtual environment after installing Django?
I've already started using Django, but I didn't create a virtual environment before installing Django. -
Decoding Characters as printed in terminal
i am having a function that returns a json response in this format when printed in terminal [{"value": 17, "label": "PENDING_ENROUTE"}, {"value": 1, "label": "REJECTED_PREFIX_MISSING"}] but if i access the context variable holding the data in template it returns [{u&#39;value&#39;: 17, u&#39;label&#39;: u&#39;PENDING_ENROUTE&#39;}, {u&#39;value&#39;: 1, u&#39;label&#39;: u&#39;REJECTED_PREFIX_MISSING&#39;}] Anyone having an idea on how to resolve it, i have tried alot of ways but i couldn't find any solution. Somebody help. -
how can i show data one after another in django models
I am Using Django Framework in my project. I want the results that start with query first then results that contain query next but when I am using the following code it is giving mixed results instead of one after other. How can I achieve My requirement collections = TokenCollection.objects.filter(Q(title__istartswith=query) | Q(title__icontains=query)) -
getting TypeError: invalid file: <InMemoryUploadedFile: abc.json (application/octet-stream)> while uploading json file in django
class jsonUpload(CreateAPIView): serializer_class = UploadSerializer def post(self, request, *args, **kwargs): import json with open(request.FILES['file']) as data: d = json.loads(data) -
how to get url link on the response of get() method
I am trying to upload and get a response to an image using DRF api. the images are uploaded on the specified location but what i want is to get the link of the image so that i can click on it and could see the image when i get the response. if anyone could help me rectify this problem I would really be very thankful models.py file class employees(models.Model): name_of_employee = models.CharField(max_length=20, unique=True) name_of_department = models.CharField(max_length=20, unique=True) emp_id = models.IntegerField() image = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg') def __str__(self): return '{} {}' .format(self.name_of_employee, self.name_of_department) views.py file class employeeList(APIView): def get(self, request): employees1 = employees.objects.all() serializer = employeesSerializer(employees1, many=True) return Response(serializer.data) def post(self, request): serializer = employeesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): employees1 = self.get_object(pk) employees1.delete() return Response(status=status.HTTP_204_NO_CONTENT) class employeeDetail(APIView): def get_object(self,pk): try: return employees.objects.get(pk=pk) except employees.DoesNotExist: raise Http404 def get(self, request,pk): employees1 = self.get_object(pk) employees1 = employeesSerializer(employees1) return Response(employees1.data) def put(self, request, pk): employees1 = self.get_object(pk) serializer = employeesSerializer(employees1, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_404_BAD_REQUEST) def delete(self, request, pk): employees1 = self.get_object(pk) employees1.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py file class employeesSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = employees fields = '__all__' … -
Docker - Django settings - Gunicorn ok but not manage.py
I read quite a few posts about this but still no solution... I have a docker-compose project with, among other, a django service that I build. On my prod environment, it is using gunicorn + nginx. All fine, working as expected. However on my dev environment, I am using only manage.py runserver. And here the troubles begin. Somehow, manage.py uses an old version of my settings.py that has been since then deleted. In my specific case, runserver is looking for a local mysql db, which doesnt exist because it is in another container. So, it is the same settings.py between gunicorn and manage.py, why does it work in one and not the other one??? My project structure: mysite |_ django_mysite/ | |_ __init__.py | |_ settings.py | |_ urls.py | |_ wsgi.py |_ myapp/ | |... |_ static/ | |... |_ manage.py |_ uwsgi_params My manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_mysite.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: … -
comparison with a key from django session
i setup a session key in django and tried to retrieve and compare with a string of the same elements, i have checked the type and they are all str but it cant return true otp = str(request.session["otp"]) print(otp,type(otp)) user_otp = str(request.POST.get("otp")) print(user_otp,"user_otp",type(user_otp)) if user_otp == request.session["otp"]: return HttpResponse("u enter") this is the log from the server after doing the print B3me <class 'str'> B3me user_otp <class 'str'> this shows they match but it doesnt return the HttpResponse -
How to test Graphql api which require user authentication
I am writing test for my application(Django+React.js+GraphQL) i have several api's which require a logged in user to access data. I am using django.contrib.auth for login/logout How can i write a simple test which can allow me to test some graphql api which require a logged in user. -
list index out of range issue, variables not existing yet
I am quite a beginner in python django and I am running through an issue that I guess I know how to solve but Iam not sure it is the right way to do it and I would like to have your point of view. My app is the following: A user create a project >> then create a team >> then invite member to the team >> is redirect to the project detail view The reverse is following the team member invitation. It is a questionnaire app so each invited members need to answer it and the answers is saved in "Response" and then I render the results in a dashboard. All my methods for the dashboard are in my views.py. My problem is that after inviting members all my methods are ran in the background but most of the variables do not exist yet since the invited user has not answered the questionnaire yet and I get an error like list index out of range is there a way to fix that without using an if/else/pass ? Method example : def get_current_team(self, format=None, *args, **kwargs): #import pdb; pdb.set_trace() current_team_member = Project.objects.get(id = self.kwargs['pk1']).team_id.members.all() members_response_list = [] for member … -
How to set the DestroyAPIView method not real delete my instance?
I have a model, like bellow: class BModel(models.Model): name = models.CharField(max_length=11) status = models.CharField(default="is_active") # if delete: deleted a = models.ForeignKey(AModel) def delete(self, using=None, keep_parents=False): pass # there I want to set the BModel's status to `deleted` Serializer: class BModelSerializer(ModelSerializer): class Meta: model = BModel fields = "__all__" Its Views is bellow: class BModelListAPIView(ListAPIView): serializer_class = BModelSerializer permission_classes = [] queryset = BModel.objects.all() class BModelDestroyAPIView(DestroyAPIView): serializer_class = BModelSerializer permission_classes = [] queryset = BModel.objects.all() My requirement is when use Django-Rest-Framework delete my BModel, I want to set the BModel's status field to deleted, not real delete the instance. How to access it? when I tried to write a delete method to my Model, there comes the default delete method: def delete(self, using=None, keep_parents=False): I have some questions about this: Is this is for the BModel's instance? Whether should through the delete method to access my requirement? -
how to access Item's database in the above code, so that I can create, update, or delete the items
class Hotel(models.Model): name = models.CharField(max_length=50) def get_absolute_url(self): return reverse('Hotel:detail', kwargs={'pk': self.pk}) def __str__(self): return self.name class Menu_time(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE,) period=models.CharField(max_length=50) def __str__(self): return self.period class Item(models.Model): period = models.ForeignKey(Menu_time, on_delete=models.CASCADE,) item=models.CharField(max_length=50) how to access Item's database in the above code, so that I can create, update, or delete the items -
django datefield is not store in MYSQL database correctly
I am using django and MYSQL. Below is my models.py: enter code here from django.db import models from django.utils import timezone import datetime from django.utils.translation import gettext as _ from bootstrap4_datetime.widgets import DateTimePicker from django import forms class Post(models.Model): WEEKDAYS=( ('Mon','Monday'), ('Tue','Tuesday'), ('Wed','Wednesday'), ('Thu','Thursday'), ('Fri','Friday'), ) TIMES=( ('morning','上午'), ('afternoon','下午'), ('night','晚上'), ) CUSTOMERS=( ('中兴','ZTE'), ('比特大陆','BITMAIN'), ('松果','PINECONE'), ('飞思卡尔','FREESCALE'), ('大唐','DATANG'), ) weekday = models.CharField(max_length=50,default='Mon',choices=WEEKDAYS) time = models.CharField(max_length=50,default='morning',choices=TIMES) customer = models.CharField(max_length=50,default='ZTE',choices=CUSTOMERS) pub_date = models.DateField(_("Date"), default=datetime.datetime.now().date) class Meta: ordering = ('-pub_date',) def __unicode__(self): return self.pub_date Here is database record: 13 2018-01-02 00:00:00.000000 中兴 morning Mon 14 2018-01-08 00:00:00.000000 中兴 morning Mon The database table shows the full time ,but I think datefield will only return format:YY-MM-DD。How to do to store date in YY-MM-DD format. Thanks! -
are routers in django Restframework necessary to use?
i have a stupid question about routers in DRF. so when i set url patters correctly and url endpoints are directing me to specific object.is this necessary to use routers?I am confused about this topic.better question: what is routers and why we should use it? -
django listbox add or remove dynamically into another listbox
i would like to create similar output as attached in question I have 3 models ModelA Stores all my master data ModelB Stores all my child data ModelC Should store master and child data based on my selection of pk(ModelA) and adding child data (ModelB) from listbox to another listbox. I have attached a image for your review. something similar i need Attached Reference