Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django -decorators - wrapper function missing 1 positional argument
I'm trying to add some custom made decorators to my class baseds views, but I get this strange error: TypeError at /equipment/ wrapper_func() missing 1 required positional argument: 'request' This is my decorator (just the general structures, with a print test): def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): print('working:', allowed_roles) return view_func(request, *args, **kwargs) return wrapper_func return decorator and this is the view: class EquipmentType_ListView(LoginRequiredMixin, ListView): model = EquipmentType template_name = 'equipment/equipmentType_list.html' context_object_name = 'obj_list' ordering = ['type'] @method_decorator(allowed_users(allowed_roles=['Direzione'])) I don't understand what is missing, the wrap_func as the request parameter, but still the error says it is missing. Any help? Thank you Carlo -
How to start django web application under apache 2.4 vhost
If my apache service gets stopped I have realised I need to run source /opt/django/webapp/bin/activate; apachectl start as the user that installed the app to get the web service working correctly. How can I fix this so that if a reboot happens or apache stops it would just work when I run apachectl start. I am working on amazon ec2 instance. I have put the below in but does not seem to work cat <<EOT >> /etc/init.d/mystartup.sh #!/bin/bash source /opt/django/webapp/bin/activate; apachectl start EOT chmod +x /etc/init.d/mystartup.sh echo /etc/init.d/mystartup.sh >> /etc/rc.local -
Django and SQL Server, gevent compliant
I would like to use a SQL Server database in a Django app that I can scale in the future. The app would be I/O bound, so I thought the best way to make it scalable is to use Gunicorn with the gevent worker class. The problem is that for using Gunicorn with --worker-class gevent the Django app should be gevent compliant and usually happens that some database clients aren't compatible (eg: mysqlclient lib). I found this SQL Server backend for Django: https://pypi.org/project/django-mssql-backend/ but I'm not able to understand if it is gevent compliant (aka "green"). I know that it would be so if it only uses standard socket/networking python libs that can be easily monkey-patched but I can't understand if this is the case. Is pyodbc SQL Server backend gevent compliant? On the official manual and on Google I can't find further information. -
Calling function from class - name 'self' is not defined
I have a file within my search folder called views. Here a route hits the search function and I attempt to call a function from a imported class. This is search/views.py from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render from django.http import JsonResponse from wagtail.core.models import Page from wagtail.search.models import Query from wagtail.search.backends import get_search_backend from search.backends import AzureSearchBackend from search.azuresearch import AzureSearch def search(request): AzureSearch.get_index(self, hotels) I'm trying to call a function thats defined in a class AzureSearch in the file azuresearch class AzureSearch(object): ACTION_UPLOAD = 'upload' ACTION_MERGE = 'merge' ACTION_UPLOAD_MERGE = 'mergeOrUpload' ACTION_DELETE = 'delete' CONTENT_TYPE_JSON_HEADER = {'Content-Type': 'application/json'} def __init__(self, service_name, api_key, api_version): self.base_url = f'https://{service_name}.search.windows.net' self.api_key = api_key self.headers = {'api-key': api_key} self.api_version = api_version self.uri_params = {'api-version': api_version} def get_index(self, index_name): response = requests.get(f'{self.base_url}/indexes/{index_name}', headers=self.headers, params=self.uri_params) if response.ok: return response.json() self._handle_error(response) I get the following error when I run the search name 'self' is not defined -
Django: Subprocess Continuous Output To HTML View
I need a HTML webpage in my Django app to load and show the continous output of a script in a scrollable box. Is this possible? I'm presently using a subprocess to run a Python script, but the HTML page won't load until after the script has finished (which can take about 5 minutes). I want the users to see something is happening, rather than just a spinning circle. What I have already also unloads the full output of the script with "\n" in the text; I'd like it to output each new line instead, if possible. My code is as follows: Views.py: def projectprogress(request): GenerateProjectConfig(request) home = os.getcwd() project_id = request.session['projectname'] staging_folder = home + "/staging/" + project_id + "/" output = "" os.chdir(staging_folder) script = home + '/webscripts/terraformdeploy.py' try: output = subprocess.check_output(['python', script], shell=True) except subprocess.CalledProcessError: exit_code, error_msg = output.returncode, output.output os.chdir(home) return render(request, 'projectprogress.html', locals()) projectprogress.html: <style> div.ex1 { background-color: black; width: 900px; height: 500px; overflow: scroll; margin: 50px; } </style> <body style="background-color: #565c60; font-family: Georgia, 'Times New Roman', Times, serif; color: white; margin:0"></body> <div class="ex1"> {% if output %}<h3>{{ output }}</h3>{% endif %} {% if exit_code %}<h3> The command returned an error: {{ error_msg }}</h3>{% endif … -
How to get approval for a particular task in django
I am working on creating tasks, in which I require have a url for approvals. In this, the person that created the task instance can ask for approval for some changes from another user (not necessarily admin). These approval requests will show up on the approver's dashboard in form of a table, where he can approve/reject them. Here is my code: models.py: class Approvals(models.Model): task = models.ForeignKey(Task_category, on_delete=models.CASCADE) requester = models.ForeignKey(User, related_name='Requester', on_delete=models.CASCADE) priority = models.CharField(max_length=50) approver = models.ForeignKey(User,related_name='Approver', on_delete=models.CASCADE) description = models.CharField(max_length=400) created_at = models.DateTimeField(auto_now_add=True) due_date = models.DateField(null=True,blank=True) approved = models.BooleanField(default=False) views.py: class PendingApprovals(viewsets.ModelViewSet): http_method_names = ["get","update"] queryset = Approvals.objects.all() serializer_class = ApprovalSerializer to_approved = Approvals.objects.filter(approver=request.user,approved='False') I am able to get a list of all the tasks that a given user has to approve, but I cant figure out how to approve them i.e how to change their boolean field tag. Any help will be appreciated. TIA. -
CORS vs JWT what is difference
I develop and deployed django rest api on heroku. then iam trying to fetch api in vue cli but it won't work. It says CORS error.this time my mind has some questions i should enable cors in backend using cors library or allor-origin in frontend?? can i use JWT instead of CORS what are issuse should face if enable cors in backend?? -
unable to POST mongo gridfs pdf to django api endpoint with python requests
I am new to mongodb and working first time with mongo gridfs I have inserted n numbers of PDF(eg: 100) in form of MongoDB gridfs using pymongo now i want to retrieve this 100 PDFs from gridfs and send a post request to Django endpoint one by one (100 post request for 100 PDFs) which saves this PDF in data base making 100 records. import pymongo import requests import gridfs import base64 myclient = pymongo.MongoClient() db = myclient['test_db'] collection = db["test_collection2"] API_URL = r'http://localhost:8000/upload/' fs = gridfs.GridFS(db) pdfs = fs.find() for pdf in pdfs: headers = { 'Authorization': 'Token {}'.format('12a9ed0e58802ea3d1e8e96bcb7b9arerd'), } data = fs.find_one(filter=dict(filename=pdf.filename)) with open(pdf.filename, "wb") as f: r = requests.post( API_URL, files={'file': f.write(base64.b64decode(date.read()))}, headers=headers, verify=False, ) problem is when it reaches Django API endpoint, sent PDF file is empty def perform_create(self, serializer): logger.info('Inside create') file_name = self.request.FILES['file'].name the Django endpoint works as expected with the postman, with PDF file but it is giving issue with the MongoDB gridfs. what i am doing wrong? Please help me resolve this. thanks in advance -
React Const Infinite Cycle
I faced a problem when I was coding in React. I have the following segment of code: <Popconfirm placement="topRight" title="Are you sure to delete this task?" onConfirm={confirm} okText="Yes" cancelText="No" // [1] > <a>delete</a> </Popconfirm> and I have the confirm function like this: const confirm = () => { // [2] message .loading("Deleting...", 1.8) .then(() => message.success("Todo item deleted!", 1.3)); postDeleteData('/todo/', { method: 'delete', keyid: 42}) // [3] .then(data => { if (data.success) {window.location = '/todo/';} }) console.log('confirmed'); }; Now, everything works fine so far. However, things won't work after I made the following changes: Changed confirm to confirm(42) (just as a test) Changed confirm = () => to confirm = (kid) => Changed {keyid: 42} to {keyid: kid} Which basically passes a parameter to the confirm call. I was expecting everything to work smoothly as this happened: And as you can see, the code started to execute infinitely on itself automatically without any key presses or action, which is the problem. Can anyone please tell me the cause? Thanks in advance. Resources async function postDeleteData(url = '', data = {}) { const formData = new FormData(); formData.append('method', data.method); formData.append('keyid', data.keyid); const response = await fetch(url, { method: 'POST', credentials: 'include', … -
Using a serializer to validate data in a custom django REST API view
I am trying to build a custom API view and I stumbled over 2 problems, one more general, the other one more specific: I have a custom view where I create a an object from the data sent in the api-request: @api_view(["POST"]) def graph_create_view(request): """ """ network = Network.objects.get(name=request.data["network"]) graph = Graph.objects.create( network_id=network.id, name=request.data["name"], description=request.data["description"], field2==request.data["field"], field3==request.data["field"], field4==request.data["field"], field5==request.data["field"], field6==request.data["field"], field7==request.data["field"], graph.save() return Response(HttpResponse.status_code) That works well, when I send all the data specified in the Graph.objects.create method. When I do not send all the data but leave out a field (Let's say I send for example data without the description field) I get a key-error. That makes sense, because that key is actually missing. I could circumvent this with many if-else-statements but that is cumbersome, not practical and hard to maintain. Now, I know I probably should write a generic view and not build this myself like this. The problem is that I need to create a Graph with two nested serializers attached to it and this is quite complicated to implement when overwriting the create method. Because the graph has two more models related to it for which I also create objects and then add it to the … -
sign up and sign in form in same view. django (python)
I want sign up and sign in form in same page. at home page default is sign up view but when click sign in button i want fadeout (js) sign up form and fade in sign in form. i have this error--->>> local variable 'form1' referenced before assignment def regform(request): if request.method == 'POST': form = SignUp(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('/') if request.method=='POST' and 'log' in request.POST: form1=AuthenticationForm(data=request.POST) if form1.is_valid(): return redirect('/') else: form1=AuthenticationForm() else: form = SignUp() return render(request, 'home/home.html', {'form': form,'form1':form1}) -
Unable to get page numbers when using django paginator
I'm using django paginator in my templates\blog\home.html. It's not working and give undesirable output. Here is my file. home.html: {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add: '3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} {% endblock content %} i'm getting this line {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add: '3' %} with Next and Last button in my … -
Django NoReverseMatch : Reverse for ‘entry’ not found. ‘login’ is not a valid view function or pattern
I have a wiki application and I am trying to list entries in homepage(index) with namespacing urls but I am getting the reverse for 'entry' not found error for my view function called 'entry'. urls.py from . import views app_name="wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entry, name="title") ] views.py from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request,title): return render(request, "encyclopedia/entry.html", {"entry_title":title , "entry_body": util.get_entry(title)}) index.html {% block body %} <h1>All Pages</h1> <ul> {% for i in entries %} <li> <a href="{% url 'wiki:entry' i %}"> {{ i }} </a</li> {% endfor %} </ul> {% endblock %} If I change wiki:entry to wiki:index I can successfully generate list items and link all of them to homepage. Somehow {% url 'wiki:entry' i %} doesn't retrieve entry view at views.py and use i for the title . Also, if I hardcode url in the template like href="{{i}}" it does also work. -
Automatically create Item in reverse foreign table if not exist in django rest frameworks
Suppose I've model as shown below. class Estimate(models.Model): company = models.ForeignKey( settings.CompanyInfo, on_delete=models.CASCADE, related_name='company' ) and the company model is class CompanyInfo(models.Model): name = models.CharField(_("Name"), max_length=255) email = models.EmailField(_("Email"), max_length=254) address = models.CharField(_("Address"), max_length=255) if i follow documentation as suggested here, https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers i can able to create foreign table data, But i want this in reverse order. Let me clarify more. Suppose user want to create new estimate object. each time user create new object user is also providing all the information which is required to create company info. I hope this sentence make some sense. Now my requirement is if the company already exist, I just want to use company id in estimate table, other wise create new company and assign its id for new estimate object. Also I'm not sure either this is possible or not so I'm really sorry for this stupid question. -
How to Display Data on view page in Django?
I have data of subcategory and filters, and both objects data displaying on same page but I want to combine all data according to filter, on the same page subcategory` product are displaying and those products also displaying which coming after the filter, please let me know how I can merge both data in the same page. here is my views.py file code... def SubCategorySlugListAPIView(request, subcat_slug): category = Category.objects.all() subcategories = SubCategory.objects.all() product = Product.objects.all() brands=Brand.objects.all() f = ProductFilter(request.GET, queryset=Product.objects.all()) supplement=Supplement.objects.all() featured=Product.objects.filter(featured=True).order_by('-created_at')[0:6] high = Product.objects.all().order_by('-saleprice') if subcat_slug: subcategory = get_object_or_404(SubCategory, subcat_slug=subcat_slug) productlist = product.filter(subcategory=subcategory) paginator = Paginator(productlist, 12) page_number = request.GET.get('page') product = paginator.get_page(page_number) template_name = 'mainpage/cat-products.html' context = {'product': product, 'subcategories': subcategories, 'subcategory': subcategory, 'category': category, 'featured':featured, 'high':high, 'brands':brands, 'supplement':supplement, 'filter':f} return render(request, template_name, context) Data are displaying on the page using project and filter, but I want to display all products which user do filter and this data will be display on category basis. -
keep the input on the textarea after submit in html and Django in python
I want to keep the input of the user on the textarea after submit here's the HTML code below, I'm using Django server to run the HTML code if want any more info please tell me. {% load static %} <html> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <head> <title> Sentiment Analysis </title> </head> <div id="wrapper" style="width:500px;" > <form id="paper" action="/external/" method="post"> <div id="margin">This Analyser will scale your feelings </div> {% csrf_token %} <textarea name="param" required placeholder="express your feelings in any language ..." id="text" rows="10" style="overflow: hidden; word-wrap: break-word; resize: none; "></textarea> <br> <input id="button" type="submit" value="start analysing"> </form> <br> <div id="margin">{{data_external}} {{data1}} {{ request.POST.title}} </div> </div> </html> <script> $(document).ready(function(){ $('#title').focus(); $('#text').autosize(); }); </script> -
on_delete gives a syntax error when it shouldn´t
When I try to do anything I always get this error, but when I went to the documentation its necessary to have the on_delete for ForeignKey, the message is this one : Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\utilizador\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\utilizador\Desktop\mysite\home\models.py", line 30 on_delete=models.SET_NULL, ^ SyntaxError: invalid syntax``` What am I missing? Or why does it … -
django.db.utils.IntegrityError: insert or update on table "authtoken_token" violates foreign key constraint
I have a little problem on django rest framework in saving data (with token), why i am receiving this error? insert or update on table "authtoken_token" violates foreign key constraint "authtoken_token_user_id_35299eff_fk_auth_user_id" this is my serializers.py class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = Account fields = ['email', 'username', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = Account( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account my views.py @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' data['email'] = account.email data['username'] = account.username token = Token.objects.get(user=account).key data['token'] = token else: data = serializer.errors return Response(data) my models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, … -
Django forms + jQuery
How to use jQuery mask plugin (javascript in general) in template to validate and style a field and update the data in the DB ? In the example below I use : https://igorescobar.github.io/jQuery-Mask-Plugin/ to validate a PhoneNumberField and Widget Tweaks to style the field. models.py from phonenumber_field.modelfields import PhoneNumberField phone_number = PhoneNumberField() forms.py class ProfileEditForm(forms.ModelForm): user_photo = forms.ImageField(label='Profile photo', required=False, error_messages={'invalid': 'Image files only'}, widget=forms.FileInput) company_logo = forms.ImageField(label='Company logo', required=False, error_messages={'invalid': 'Image files only'}, widget=forms.FileInput) class Meta: model = Profile fields = ('company_name', 'company_logo', 'user_photo', 'desc', 'dep', **'phone_number'**) views.py @login_required def dashboard_edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() print(profile_form) messages.success(request, 'Profile updated successfully') else: messages.error(request, 'Error updating your profile') else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request, 'back/index.html', {'user_form': user_form, 'profile_form': profile_form}) index.html <input type="text" class="js-masked-input form-control" name="phone" id="phoneLabel" placeholder="+x(xxx)xxx-xx-xx" aria-label="+x(xxx)xxx-xx-xx" value="+1(605)5618929" data-hs-mask-options='{ "template": "+0(000)000-00-00" }'> -
How to get user data from custom user model in django?
This is my User Model. class User(models.Model): user_id = models.AutoField(primary_key=True) user_email = models.CharField(max_length=100) user_password = models.CharField(max_length=15, default=None) def __str__(self): return self.user_email This is my User Model View. def userdetails(request): username = request.user.get_username() password = request.user.get_password() users = User.objects.get(user_email=username) user_list = { 'users': users } if request.user.check_password(password): print(password) return render(request, 'userdetails.html', user_list) else: return render('/', {'user': request.user.username}) # I dont know what this line is doing and This is my Template. <form class="form-signin" method="POST" action="{% url 'login' %}"> {% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Login</h1> <div class="mt-3"></div> {{ form.username.label_tag }} {{ form.username }} <div class="mt-3"></div> {{ form.password.label_tag }} {{ form.password }} <div class="mt-3"></div> {{ form.errors }} <button class="btn btn-sm btn-primary" type="submit">Sign in</button> </form> I am unable to get the user data from the Login Template. Is there any way to work with the current User Model? -
I want to create and update UserProfile object with OneToOne User object field and create a api in Django rest framework
I'm new in Django rest framework, I tried my whole day but can't do it,I want to do full crud operation in my UserProfile Model which have a OneToOne field user, User can only update their own profile and in UserProfile create or update user shouldn't update User[username], How can i achieve it Please Help me *** serializers.py *** from rest_framework import serializers from product.models import UserProfile from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' read_only_fields = ['username','password', ] class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) class Meta: model = UserProfile fields = "__all__" def create(self, validated_data): user_data = validated_data.pop('user') user_instance = User.objects.get( username=user_data['username']) user_instance.save() user_profile_instance = UserProfile.objects.create( **validated_data, user=user_instance) user_profile.save() return user_profile *** views.py *** from django.shortcuts import render from .serializers import UserProfileSerializer from rest_framework.views import APIView from rest_framework import generics, permissions from rest_framework.response import Response from rest_framework import status from django.contrib.auth.models import User from product.models import UserProfile # Create your views here. class CreateUserView(generics.ListCreateAPIView): serializer_class = UserProfileSerializer permission_classes = [permissions.IsAuthenticated,] def get_queryset(self): user = self.request.user return UserProfile.objects.filter(user = user) *** models.py *** from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE) country = … -
Django ImproperlyConfigured exception at app_name.url
This is a debug version of a running server, and the project's structure is in accordance with the online version, so this structure should be ok, yet when attempting to run the server I get an ImproperlyConfigured exception. django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patte rns and app_name instead. I looked at online solutions but this exception can occur in many scenarios, and I couldn't figure out how to apply these solution into my code. I tried modifying the code as instructed in these solutions and kept getting this exception message. Some relevant code: app_name\urls.py: from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), ] polls.urls includes many url patterns. An image of the project's structure. Thanks! -
Increase by one per user per submit
I got the models shown down below. I want that my invoice_id field gets the value 000001 when user A submits to it and as well 000001 when user B submits to it. It should auto increase from there, so if user A stays idle but user B makes other submits, B's next will get 000002, 000003 etc. If user C then joins and submit, he should get 000001 too. How would I approach this? my models: class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=45) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # Company Profile Fields co_logo = models.ImageField(upload_to="dashboard/logos", blank=True) co_name = models.CharField(max_length=45) co_address = models.CharField(max_length=45) co_zip = models.CharField(max_length=45) co_city = models.CharField(max_length=45) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True class Invoice(models.Model): client = models.ForeignKey(BusinessContact, default=None, on_delete=models.CASCADE) user = models.ForeignKey(Account, default=None, on_delete=models.CASCADE) invoice_id = models.CharField(unique=True, max_length=6, null=True, blank=True, editable=False) place = models.CharField(max_length=40) date_created = models.DateTimeField(verbose_name='date created', auto_now_add=True) date_sent = models.DateTimeField(verbose_name='date sent by mail', auto_now=True) date_deadline = models.DateTimeField(verbose_name='payment deadline', auto_now=False) bank_number … -
How to make a unite test for mocking a random return funciton?
I need to mock the output of this function: utils/generate_new_verification_token.py from random import randint def generate_new_verification_token(): return ''.join(["{}".format(randint(0, 9)) for num in range(0, 4)]) In my test file: x/test_api.py class TestPhoneVerify(APITestCase): def setUp(self): self.user = User.objects.create_user(email='mock@example.com', password='12345678') def generate_token(): foo = ['1111', '2222'] return Response(random.choice(foo)) @mock.patch('utils.generate_new_verification_token.generate_new_verification_token', side_effect=generate_token) def test_duplicate_code_for_same_user(self, req_token): self.client.force_login(self.user) res_request = self.client.post('/phone/request/', data={'phone': '4545345'}) print(res_request.token) It keeps generating random numbers other than '11111', '2222' which I am using in the mocking function. i.e it keeps using the original generate_new_verification_token function. How to solve this to use my generate_token mocking function? -
django nested model json import
I am quite new to Django and I may be missunderstanding some concepts, but I can not find a solution to what I am trying to do. I have a multi table model defined and I have defined the models, views, admin, serializers and urls. It is working perfectly to independtly read and write in all of them through the API. The code looks something like this: models.py class Level1(MySQLNoCountModel): name = models.CharField() ... class Level2(MySQLNoCountModel): level1 = models.ForeignKey( Level1, blank=False, null=True, on_delete=models.CASCADE ) name = models.CharField() ) ... serializers.py class CreateLevel1Serializer(OrderedModelSerializer): name = serializers.CharField() def create(self, validated_data): obj, created = models.Level1.objects.update_or_create( name = validated_data['name'], defaults={ } ) class CreateLevel2Serializer(OrderedModelSerializer): level1 = serializers.CharField() name = serializers.CharField() def validate_level1(self, value): try: return models.Level1.objects.get( name=value ) except Exception: raise serializers.ValidationError(_('Invalid leve1')) def create(self, validated_data): obj, created = models.Level2.objects.update_or_create( name = validated_data['name'], defaults={ 'level1': validated_data.get('level1', True), } ) With this I can create new elements by sending two consecutive posts to the specific ednpoints: { "name":"name1" } { "level1":"name1", "name":"name2" } I am trying to do it in a single operation by inserting something like this: { "name":"name1" "level2":[ { "name":"name2" }, { "name":"name3" } ] } I have tryied to redefine the …