Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Invalid Keyword Argument 'user'
Im creating a signup view with a profile model. but got stuck with a small TypeError. Can someone tell me where am I going wrong.. models.py class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=10) full_name = models.CharField(max_length=200) is_doctor = models.BooleanField(default=True) @receiver(post_save, sender=User) def update_user_docto(sender, instance, created, **kwargs): if created: Doctor.objects.create(user=instance) instance.doctor.save() forms.py class DocSignUpForm(UserCreationForm): full_name = forms.CharField(help_text='Required') mobile = forms.CharField() class Meta: model = User fields = ('username', 'full_name', 'mobile', 'password1', 'password2',) views.py def docsignup(request): if request.method == 'POST': form = DocSignUpForm(request.POST) if form.is_valid(): user = form.save() #error in this line user.refresh_from_db() user.doctor.full_name = form.cleaned_data.get('full_name') user.doctor.mobile = form.cleaned_data.get('mobile') user.save() #username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('base') else: form = DocSignUpForm() return render(request, 'signup.html', {'form': form}) -
Django error when trying to display the sign up form
So I have this form which extends the User and I just want to allow the student to create and account and be able to select the courses from the course list.But when I try, I get the error: __init__() takes 1 positional argument but 2 were given I can't find any solution to this yet. I need some advice. These are my files: {% block body %} <div class="row"> <div class="col-md-8 col-sm-10 col-12"> <h2>Sign up as a {{ user_type }}</h2> <form method="post" novalidate> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form }} <button type="submit" class="btn btn-success">Sign up</button> </form> </div> </div> {% endblock %} class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) path('signup/', views.StudentSignUpView, name='signup') class StudentSignUpForm(UserCreationForm): attended_courses = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple, required=True ) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.save() student = Student.objects.create(user=user) student.attended_courses.add(*self.cleaned_data.get('attended_courses')) return user class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index') -
Django REST: CRUD on Through Table, Many-to-Many relationship
I have workers and tasks that they can complete. I would like for workers to be able to apply for tasks, and retrieve the following .json for each task. GET http://127.0.0.1:8000/api/tasks/ returns: "results": [ { "url": "http://127.0.0.1:8000/api/tasks/1/", "workers": [], "user": "Username", "created": "2018-01-21T19:56:35.398320Z", "title": "Help me with Django Rest", "description": "Here is my problem", }, Currently, the workers field is empty, and I would like to write a view so that workers can apply for this specific task using a POST request to: http://127.0.0.1:8000/api/tasks/1/apply This Many-to-Many relationship looks as follows: models.py class Worker(models.Model): user = models.OneToOneField(User) class Task(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=False) description = models.TextField(max_length=500, blank=False) user = models.ForeignKey('auth.User', related_name='tasks', on_delete=models.CASCADE) workers = models.ManyToManyField(Worker, through='Task_worker') def save(self, *args, **kwargs): super(Task, self).save(*args, **kwargs) class Task_worker(models.Model): worker = models.ForeignKey(Worker) task = models.ForeignKey(Task) created = models.DateTimeField(auto_now_add=True, blank=True) serializers.py class TaskWorkerSerializer(serializers.HyperlinkedModelSerializer): task = serializers.ReadOnlyField(source='task.id') worker = serializers.ReadOnlyField(source='worker.id') class Meta: model = Task_worker fields = ('task', 'worker', 'created', ) class TaskSerializer(serializers.HyperlinkedModelSerializer): workers = TaskWorkerSerializer(source='task_worker_set', many=True, read_only=True) user = serializers.ReadOnlyField(source='user.username') class Meta: model = Task fields = '__all__' class WorkerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Worker fields = '__all__' My urls.py contains task_list = views.TaskWorkerViewSet.as_view({ 'get': 'list', 'post': 'create' }) urlpatterns += [url(r'^tasks/(?P<task_id>[0-9]+)/apply$', task_list),] … -
Django cant see my toolbar
Hello I have a common problem in Django like Django can't see .. OK this time Django can't see my beautiful toolbar Terminal doesnt show any error. This is my cms_toolbar.py placed in my "aktualnosci" folder from django.utils.translation import ugettext_lazy as _ from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar from cms.utils.urlutils import admin_reverse from .models import * @toolbar_pool.register class PollToolbar(CMSToolbar): supported_apps = ( 'aktualnosci', ) watch_models = [Aktualnosci] def populate(self): if not self.is_current_app: return menu = self.toolbar.get_or_create_menu('poll-app', _('Aktualnosci')) menu.add_sideframe_item( name=_('Lista aktualnosci'), url=admin_reverse('aktualnosci_aktualnosci_changelist'), ) menu.add_modal_item( name=_('Dodaj aktualnosc'), url=admin_reverse('aktualnosci_aktualnosci_add'), ) Of course Django can't see it and ignore it. My question is - how to force Djnago to see it Screaming doesnt help! -
Django save_model file not yet uploaded
def save_model(self, request, obj, form, change): in this handler I can get the name of the uploaded file, but the file itself is not uploaded yet, so I can't make any operations on it, can be there a way to force django to upload that file in this save_model handler? in order to do some operations on it -
Django signals working yet one is giving unexpected results
I dislike having people go through the trouble of reviewing my code but even after trying for hours, I have no idea what the problem is. I didn't have a clear way of describing my question's title but I tried. I am building a College Management System. I have two apps at the moment. One is for accounts and the other is called klass. I have extended the default user and have added a boolean field of 'in_class' which I will be using as a check to do stuff later. Below is an overview of my accounts.models.py: accounts.models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) in_class= models.BooleanField(default=False) bio = models.TextField(blank=True, help_text='write something about yourself...') # goes on... I am not utilizing the permissions, i am using a role-based approach. The only difference is i've added the boolean fields to my user model instead of creating another model for the roles. Below is an overview of my klass.models.py: klass.models.py from django.db import models from accounts.models import User from django.db.models.signals import post_save, … -
Window not closing in django after save
I have two many to many fields when I click on one many to many feild and the save the window closes but there is one more m2m field inside 1st one when i clicked that and save the data my new window does not close -
Django view to call api
So i'm using django view to call api post method but its giving me 400 error As i encounter csrf forbidden error b4, im using the @csrf_exempt for now. I tried doing post method on both the API itself and also using the view to call the api. However when using the view to call, i got 400 error when both are using the same post value to post. Posting using api: QueryDict: {'book': ['Second '], 'author': ['Ban'], 'date': ['2018-01-10 08:00AM']} [22/Jan/2018 18:56:09] "POST /api/test/ HTTP/1.1" 200 61 Posting using view: QueryDict: {} [22/Jan/2018 18:56:12] "POST /api/test/?book=Second+&author=Ban&date=2018-01-10+08%3A00AM HTTP/1.1" 400 36 [22/Jan/2018 18:56:12] "POST /test/ HTTP/1.1" 200 19 Here is my code models.py class TestPost(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) serializer.py class TestPostSerializer(serializers.ModelSerializer): date = serializers.DateTimeField(format="%Y-%m-%d %I:%M %p") class Meta: model = TestPost fields = ('id', 'book', 'author', 'date') views.py from django.http import HttpResponse import requests def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', params=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', params=request.GET) if r.status_code == 200: return HttpResponse('Yay, it worked') return HttpResponse('Could not save data') class TestPostViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = TestPost.objects.all() serializer_class = TestPostSerializer -
Chatfuel bot - user validation
I have been reading a LOT seriuosly a lot of how can I implement this flow to my bot, for example: The user types his/her username I get the data written by the user I search in my Django Rest API if the user actually exists and then return to he/she the tasks he/she need to complete for the end of the week. I know that I have to use JSON plugin, and User Input, but what I don't know how to do, is obtain what the user type. Until now I got this URL setup in my JSON plugin: https://helloworld.herokuapp.com/post?username={{username}} so this mean that I have a running server. But then what? I read this: API integration and also this setup server side logic But step 3 is what I don't know how to develop, I achieve this: class GetView(TemplateView): template_name = 'profiles/get.html' def geturl(self, request): # url = 'https://helloworld.herokuapp.com/post?username={{username}}' # parsed = urlparse.urlparse(url) # return HttpResponse(urlparse.parse_qs(parsed.query)['username']) username = self.request.query_params print(username) url = 'https://helloworld.herokuapp.com/post/' + 'username' + username But I think i'm not even close to find the solution. -
Django rest Swagger 2.0 how to display DictFiled in swagger UI?
I'am trying to display below serializer dict field but its not showing in swagger UI Please take a look. class TargetSerializers(serializers.ModelSerializer): name = serializers.CharField(required=True) target_type = serializers.PrimaryKeyRelatedField(queryset=ScanType.objects.all()) configuration_details = serializers.DictField() class Meta: model = Target fields = ('id', 'name', 'target_type', 'lock_threshold', 'user_id', 'configuration_details') -
CBV or Functional View for JsonResponse
I am new to creating API endpoints using Django. Which is a better way to handle API requests and process JsonResponse? Should I do it in a Class-Based View? Or a Functional View? I would assumed CBV would be an overkill since people tend to use CBV for the generic-view inheritance. Since I am merely sending back a Json object, i would consider it unnecessary and thus a Functional view would suffice. However, I am not too sure what exactly are the other components of CBV and FV that would matter and make the difference. If there is one view better over another view, can you please tell me with reasons why one is preferred over another. Cheers. -
How can I change email sender's name in django
I'm creating email system in my django project and faced to next question: Send email from custom email sender name, f.e. sending email from gmail(btw it works in my project) requires sending messages only from gmail account, same thing with smtp-pulse, sendgrid and etc. . My question is: May I use any of already configured smtp servers in my case, or I only need to create my own using smtplib(f.e) and configure it? Tried: DEFAULT_FROM_EMAIL = 'support@site.com' SERVER_EMAIL = 'support@site.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 2525 EMAIL_USE_TLS = False EMAIL_HOST_USER = 'user@gmail.com' EMAIL_HOST_PASSWORD = 'password' This one doesn't work. Same with mail.ru/smtp-pulse.com -
Django convert raw SQL ordering to QuerySet API
I'm trying to perform natural ordering on CharField for model (here simplified version): class House(models.Model): number = models.CharField(max_length=32) def __str__(self): return str(self.number) >>> House.objects.all() <QuerySet [<House: 2>, <House: 1>, <House: 4>, <House: 3>, <House: 1b>, <House: 2b>, <House: 1c>, <House: 13c>, <House: 10>, <House: 2e>, <House: 3ab>]> I have managed to order it by raw SQL query: House.objects.raw("SELECT * FROM entry_house ORDER BY(substring(number, '^[0-9]+'))::int, substring(number, '[0-9].*$')") But I need to get QuerySet object not RawQuerySet (for our current pagination implementation). Iterating over all raw queryset is not an option because of huge amount of data. How can I convert result of RawQuerySet to QuerySet or even better, how to convert this raw SQL query to Django QuerySet API? -
Pass attributes from a Cutom Field to a Custom Widget template
I want to create a custom Field and a custom Widget. I'm trying to do this using ModelForms. How can I pass arguments from the Field to the Widget but not as widget attributes, similar to how {{ widget.name }} is passed. field_name = CustomField(obj_original=ALPHA, obj_type=100) I want to use this values in the widget template as conditional and/or as values for template tags(do some manipulation), so this is why I don't want them in attributes(the attribute will appear in the html elements), this don't. I know I can pass multiple attributes in widget, but I need then to remove them from attributes and attached as direct properties/attributes of the widget. I want to be passed in the Field, not in Widget. I check in django source ChoiceField and SelectField but it is not very clear for me. -
updated file name in django
This is an admin form handler, for example I upload a test.txt file in the django admin panel: def save_model(self, request, obj, form, change): if 'torrent_file' in form.changed_data: print("file has changed: ") print(obj.file) else: print("file has not changed") super(FileAdmin, self).save_model(request, obj, form, change) here I get the original file name from the upload form, but by fact the file is saved with another name if there is already a file with this name, but in the above code i get only the original name in all cases, how to can I get the changed/updated file name that was saved?.. -
Django boolean choice field
How can I make a django form of Yes and No. for example I want my django website to have a question like: "Do you use Django?" -Yes -No the - sign is the radio buttons. How can i do this in django -
Modifying a Django Rest Framework Request
I have a Django rest framework api set up, and I'm trying to insert the current time into incoming PUT requests. I currently have: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.filter(done = False).order_by('-time') serializer_class = ItemSerializer paginate_by = None def list(self, request, *args, **kwargs): self.object_list = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(self.object_list, many=True) return Response({'results': serializer.data}) This handles partial updates, but I would like to be able to send a request setting an Item to done = True and have the api also insert a unix timestamp into the data sent to the serializer. Could I alter the request object like this, or is there a better way? def put(self, request, *args, **kwargs): request.data['time'] = time.time() return self.partial_update(request, *args, **kwargs) -
Why does my django cache return nothing? Not even 'None'
I have the following three functions. The bottom function calls on the top two functions. I will get an error when multiplying the variables c=m*b 'unsupported operand type(s) for *: 'NoneType' and 'float'' and as you can see m returns nothing. So my two problems are that btc_to_hourl3 does not show 'None' or a value (and therefore skips the if statement). And secondly when printing totalUserL3hours(user1) in last function it prints nothing even though the function called shows a cached variable? def btcToHourL3(): btc_to_hourl3 = cache.get('btc_to_hourl3') print("btc to hourl3 cached is : ".format(btc_to_hourl3)) #shows as nothing when is something? if btc_to_hourl3 is None: main_api = 'https://api.nicehash.com/api?method=balance&id=keyhere' json_data = requests.get(main_api).json() balance1 = json_data['result']['balance_confirmed'] print("Nice hash L3 balance is: {}".format(balance1)) btc_to_hourl3 = float(balance1)/totalMachineHoursWorkedMonthL3() m = float(btc_to_hourl3) print("Total btc to every hour is: {}".format(btc_to_hourl3)) cache.set('btc_to_hourl3', m, 900) #cache for 15 mins return float(btc_to_hourl3) def totalUserL3hours(user1): user_L3_hrs = cache.get('user_L3_hrs'+user1.username) print("User l3 cache hours are {}".format(user_L3_hrs)) ####Prints 'None' when it is none ie after 1800secs. Prints 511 when works if user_L3_hrs is None: a=0.0 l3_total = user1.L3s.all() for l3 in l3_total: x = l3.indivMachineHoursWorked() a=a+x cache.set('user_L3_hrs'+user1.username, float(a), 1800) print("User l3 hours are {}".format(a)) return user_L3_hrs def TotUserL3Mined(user1): # a = 0.0 # l3_total = request.user.L3s.all() … -
How can I add the `order_status_count` to as the same level as the `results` list?
I want to add the order_status_count to as the same level as the results list: I tried bellow code: serializer: class OrderFilterSerializer(ModelSerializer): order_type = serializers.CharField(write_only=True, allow_null=True) order_user_name = serializers.SerializerMethodField() order_status_count = serializers.SerializerMethodField(read_only=True) def get_order_status_count(self, order): ..... return order_status_count view: class OrderSerializerListAPIView(ListAPIView): serializer_class = OrderFilterSerializer # pagination_class = OrderPageNumberPagination ..... But the bellow is like this: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 140, "next": "http://localhost:8000/api/abc/order/list/?page=2", "previous": null, "results": [ { "id": 1, "order_user_name": "test01", "order_status_count": { "paid_finished_count": 5, "paid_unfinish_count": 68, "unpay_count": 49 }, "order_num": "15108988238922", ..... }, ...... You see the order_status_count in every item now: "order_status_count": { "paid_finished_count": 5, "paid_unfinish_count": 68, "unpay_count": 49 }, This is not fit my envision. How can I add the order_status_count to as the same level as the results list? -
Does migrations directory in django project should be pushed to git repo?
In django project, when models changed the migrations file will be changed, if add migrations directory to git will raise conflict to others, if not add sometimes will raise server error when migrated. How do you solve this? -
Calling api from django view error. forbidden (csrf token is missing or incorrect)
I seen alot of other solution, tried it but problem still persist. When i do a requests.get, it works fine but when i'm doing requests.post. I got this forbidden (csrf token is missing or incorrect) error. Here is my code models.py class TestPost(models.Model): # reminderId = models.AutoField() book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) serializer.py class TestPostSerializer(serializers.ModelSerializer): # valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] # time = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True) date = serializers.DateTimeField(format="%Y-%m-%d %I:%M %p") class Meta: model = TestPost fields = ('id', 'book', 'author', 'date') views.py from django.http import HttpResponse import requests def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', params=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', params=request.GET) if r.status_code == 200: return HttpResponse('Yay, it worked') return HttpResponse('Could not save data') class TestPostViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = TestPost.objects.all() serializer_class = TestPostSerializer I did a POST method on the url of the function but error Forbidden (CSRF token missing or incorrect.): /test/ [22/Jan/2018 16:59:09] "POST /test/ HTTP/1.1" 403 2502 -
"http method not bound to view" when documenting class-based view in drf_yasg
Previously, I documented my function-based views like this: @swagger_auto_schema( operation_id='ChangePassword', methods=['POST'], request_body=ChangePasswordSerializer, responses={ '200': 'empty response body', }) def change_password(request): # code here We then switched our views to class-based, so I simply copy-pasted the documentation decorator over to the post method: class UserChangePasswordView(APIView): @swagger_auto_schema( operation_id='ChangePassword', methods=['POST'], request_body=ChangePasswordSerializer, responses={ '200': 'empty response body', }) def post(self, request): # code here However, on running this decorator, drf_yasg threw the exception File "/usr/local/lib/python3.6/site-packages/drf_yasg/utils.py", line 126, in decorator assert all(mth in available_methods for mth in _methods), "http method not bound to view" What is going on? What does this error message mean? -
Django generic date based views How to get the date lookup?
There is a function in a generic class based view called _make_single_date_lookup(self, date) def _make_single_date_lookup(self, date): """ Get the lookup kwargs for filtering on a single date. If the date field is a DateTimeField, we can't just filter on date_field=date because that doesn't take the time into account. """ date_field = self.get_date_field() if self.uses_datetime_field: since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(date + datetime.timedelta(days=1)) return { '%s__gte' % date_field: since, '%s__lt' % date_field: until, } else: # Skip self._make_date_lookup_arg, it's a no-op in this branch. return {date_field: date} I am interested in the lookup part: return { '%s__gte' % date_field: since, '%s__lt' % date_field: until, } How do you get access to the lookup for the month in a MonthArchiveView? -
Setting up Django on a clean VM: issue linking runserver to VM's ip
I'm setting up my Django site on a clean Ubuntu VM. Gone through the process of installing the necessary tools, I follow this tutorial and apart from the additional python packages I've added for my site it's the same process. According to this instructional guide to check whether everything is running smoothly you run python manage.py runserver 0.0.0.0:8000 and it should then run on the IP:8000 of the site. above is the instance of this running and this above shows the external ip of the google cloud instance running this. However when i try to visit http://35.227.49.155:8000/ I get This site can't be reached and it's double confirmed with no activity on the shell on a request picked up. -
How to create dynamic webscraper in Django using BeautifulSoup
I am trying to a dynamic webscraper using Django. I have a html button in which it has buttons so it is like when i will press the button it will start webscraper and will save the data into database and later on from another button i can download that data into CSV format. Now I have prepared the html page for buttons. I have written webscraper script and in my views.py i have imported that scraper file and called that function but when i type python manage.py runserver scrapers starts but my web page is not reachable. First how can i solve this problem. Second how can i connect my scraper with the html button Third how i can save the data into database Fourth how can i download them into csv when i press the button Below is my Views.py from django.shortcuts import render from django.conf.urls import url from django.conf.urls import include from django.http import HttpResponse from bs4 import BeautifulSoup import requests import Up# this is the web scraping file # Create your views here. #def index(request): # first = {"here":"will enter more details"} # return render(request, "files/first-page.html", context=first) #return HttpResponse("<em>Rera details will be patched here</em>") #uncomment this …