Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Any way to update model fields on request?
I'm using a select field to delete members of a certain model, but let's say I delete a member, and refresh the page, the member will be gone in the model but not in the page, it'll still show in the select. I know why this happens, but I want to know how to circumvent it. Here's my form: class StudentDeleteForm(forms.ModelForm): class Meta: model = Student fields = ['name'] widgets = { 'name': Select(choices=[("%s" % stud['id'], "%s" % stud['name']) for stud in Student.objects.all().values('id', 'name')]) } All I want is to be able to get these values from page request, and not have to restart the webserver every time. Is there any way how? -
Ajax call with withCredentials: true is not sending cookie in request
My scenario: example.com is a django page which is being visited by user. session is set by server. Now, I have frontend app on another domain called xyz.com, Now, I need to call APIs on example.com, so I am trying to make ajax call with withCredentials: true. but it does not seems to sending cookie 'sessionId' in request. I have already seen some stack overflow answers, but suggested answers are not working. link1 link2 link3 What I have been trying : My backend is written in Django, so I tried setting CORS_ALLOW_CREDENTIALS = True # Cross Origin Request Settings (CROS) CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken', 'cache' ) CORS_ORIGIN_WHITELIST = [ '*' ] SESSION_COOKIE_HTTPONLY = False SESSION_COOKIE_DOMAIN = 'example.com' -
Authenticate JWT/DRF when using Google Auth
My I do JWT authentication through username/password, it works like this: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer '''post looks like: <QueryDict: { 'csrfmiddlewaretoken': ['Pd1mjNUXEdeiObEGOg8oNeqU18nwMVkSu8C29e0POGKwa2kY3yHiXk6hOEzuatMg'], 'email': ['tom@gmail.com'], 'password': ['xyxyzuzu'], 'evaluateUsername': ['Login'] }>''' tokens = MyTokenObtainPairSerializer().validate(request.POST) request.session["accessToken"] = tokens["access"] request.session["refreshToken"] = tokens["refresh"] Easy enough. However, if I'm using Google Login, I don't have access to the user's email or password. I can grab the email easily in the following way: if not request.POST.get('email'): request.POST._mutable = True request.POST['email'] = user.email # request.POST['password'] = '********' # placeholder request.POST._mutable = False But it will still fail on the django authenticate(user, password), so I get the following error: rest_framework.exceptions.ValidationError: [ErrorDetail(string='No active account found with the given credentials', code='invalid')] How would I get around this, as I truly don't know the user's password if they're logging in with Google Auth, and any way to provide a falsey value results in an error? -
django_filter ModelMultipleChoiceFilter - Bad Request on miss
I have a ViewSet that has a filter_class that is like this: class OrderFilter(django_filters.FilterSet): ...... product = django_filters.ModelMultipleChoiceFilter( field_name='product', queryset=Product.objects.all(), ) With this, I can specify a product id, and make a get request like this /orders/?product=<product_id>. I'm seeing the following behavior in three situations: If there are order(s) with the given product_id, it will return those orders ... good! If there are NO orders with that given product_id, it will return a successful 200, with an empty results (e.g. {count: 0, next: null, previous: null, results: [ ]} ... good! If that product_id doesn't exist, it returns a 400 Bad Request with a ValidationError and this response: { product: [ "Select a valid choice. %(value)s is not one of the available choices." ]} ... wtf! This last situation seems odd to me. Shouldn't the response be the same if (a) the given object relationship isn't there and (b) the object itself doesn't exist? This dual behavior would seemingly indicate to the FE if that product exists or not, and perhaps they shouldn't know that information. How can I change my filters such that it always returns a 200 with a result set that is empty in those two cases? … -
Handling multiple input values for single html form in django
i have a html form with 3 inputs and steps buttons. 1st step user must put first name and press button 1 2st step user must put last name and press button 2 3st step user must put email and press final button 3 any time where the user press any button then go to next html step. i want to Handle inputs in my views.py step by step any time where the user press any button and not all together in the final submit . i try t use this code in views.py to take inputs in django backend and now work i don't take anything in views.py.(if i change button type from button to submit then i take results nut refresh page and i cant go to step 2) views.py if request.method == 'POST' and 'first_step' in request.POST: print '1' firstname= request.POST.get('firstname') if request.method == 'POST' and 'second_step' in request.POST: print '2' lastname= request.POST.get('lastname') if request.method == 'POST' and 'final_step' in request.POST: print '3' email= request.POST.get('email') here the html code : <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Form wizard with circular tabs</title> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <section> <div class="wizard"> <div class="wizard-inner"> … -
What is this regex error when trying to display Django User profile?
I'm trying to use regex to capture a user's username, and use a CBV to return a JSON response showing the correct User's info, but I am getting an error I don't understand. First off, here is the error I am getting: url(r'^userprofile/(?P[\w.@+-]+)', UserProfile.as_view()), NameError: name 'UserProfile' is not defined I have other URL captures that are working just fine, and they are all CBV just like this one, with the same format. Here is the URL capture code: url(r'^userprofile/(?P<username>[\w.@+-]+)', UserProfile.as_view()) Here is the CBV: class UserProfile(APIView): def get(self, request, username): obj = User.objects.get(username=username) serializer = UserSerializer(obj, many=True) return JsonResponse(serializer.data, safe=False) Here is the UserSerializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('__all__') And here is the User Model: class User(AbstractUser): birthdate = models.DateField(null=True) gender = models.CharField( max_length=1, choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ('U', 'Unspecified')), default='Unspecified' ) renewal = models.DateField(null=True) def __str__(self): return '%s %s' % (self.first_name, self.last_name) This is probably simple, but I don't know why this error is being thrown. Please advise. Thanks you. -
Running two django sites from one docker container?
I have a website that uses the sites framework to basically have two different domains serving the same Django project. In production, this is served through a Docker container (including an nginx server). What I would ideally do is have both sites be served from one single Docker container. Is this possible? The websites share the same database so that would be no problem, but what I am not able to figure out is how I can add another "web" instance to the same docker container using the same port (likely impossible). Are there other ways? Spinning up two docker containers on the same server would also be fine, but again I'd have to use the same ports which causes conflicts. FYI here is the docker-compose file: version: '3' services: nginx: image: nginx:latest ports: - 80:80 volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . depends_on: - db volumes: - ./src:/src expose: - 80 db: image: postgres:latest -
Django Daphne large file uploads
I have a Django web application that uses Channels and Daphne for websocket communication. All of my websocket stuff is working properly without any issues. My trouble comes from the fact that my server also allows me to upload files to the server. Small files (even up to 282mb) are being uploaded and working fine with no issues. However large files are resulting in a 500 Internal error - Daphne and showing this stack trace: 2018-10-29 12:40:14,009 - ERROR - http_protocol - Traceback (most recent call last): File "..\venv\lib\site-packages\daphne\http_protocol.py", line 176, in process "body": self.content.read(), MemoryError I'm guessing this is telling me that Daphne is running out of memory. I found reference here: Daphne Django file upload size limitations which also helps to confirm this finding. What I need an answer for is how to solve it. I am not running my project inside of Docker, I am on a Linux VM instance. If I increase the total RAM in use on the entire VM will daphne be able to grab some more? Is there some way I can specify to daphne that it is allowed to use more memory than it is current? This server instance has 4gb of … -
Not able to import models in views.py #python #django
This happens when I try to rn server Django - Python views.py Just when I try to import "Post" model, I have this error and I can't reach any page. If I don't import any model in views.py everything looks good.. Could you help me to fix this issue? from .models import Post def home_view(request): latest_posts = Post.objects.order_by('pub_date')[:3] return render(request, 'home.html', {'Latest': latest_posts}) models.py from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=120) brief_life = models.TextField(blank=True, null=True) Date_of_birth = models.DateField() def __str__(self): return self.name class Type(models.Model): name = models.CharField(max_length=120, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=120, unique=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=10000) pub_date = models.DateField() copy_num = models.IntegerField(default=1) for_buy = models.BooleanField(default=True) author = models.ForeignKey(Author, on_delete=True) p_type = models.ForeignKey(Type, on_delete=True) def __str__(self): return self.title apps.py from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' -
How to see if a view function exists based on a url
I am trying to give django a url and resolve it to a view. For example: >>> reverse('login') '/login/' >>> reverse('/login/') Traceback (most recent call last): File "", line 1, in File "/Users/david/Desktop/V/lib/python3.6/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/Users/david/Desktop/V/lib/python3.6/site-packages/django/urls/resolvers.py", line 622, in _reverse_with_prefix raise NoReverseMatch(msg) Is there another way to do this? Or a django method that I can pass it a url (these will be 'dirty' urls, such as "https://example.com/login/?next=/myaccount/"), and it will resolve it to the correct view? -
Testing with manual calculation or programmed calculation?
I'm using Django and I need to write a test that requires calculation. Is it best practice to calculate the expected value manually or is it ok to do this by using the sum function (see below) This example is easier for me because I don't have to calculate something manually: def test_balance(self): amounts = [120.82, 90.23, 89.32, 193.92] self.mockedTransaction(amount=amounts[0]) self.mockedTransaction(amount=amounts[1]) self.mockedTransaction(amount=amounts[2]) self.mockedTransaction(amount=amounts[3]) total = Balance.total() self.assertEqual(total, sum(amounts)) Or in this example I have to calculate the expected value manually: def test_balance(self): self.mockedTransaction(amount=120.82) self.mockedTransaction(amount=90.23) self.mockedTransaction(amount=89.32) self.mockedTransaction(amount=193.92) total = Balance.total() self.assertEqual(total, 494.29) -
Django Signals for task plannification
I try to found the best way to manage this issue with Django Signals: I created a datamodel with a table ExecutionPlan In this table I simply store task to execute at a "startDate" value. I would like to be "signaled" when a "execution line" have a "startDate < Now" I read Django documentation on signals but I didn't found any case where a signal is send for "a data value check", in my case when a startdate is outpassed. So my question is more methodic than technical: Do you think that Django Signals is designed for that case ? Should I design my own event loop ? Thanks in advance. Cyril -
Converting string into dictionary in Python [duplicate]
This question already has an answer here: What's the best way to parse a JSON response from the requests library? 4 answers I received a POST request response as a string by using Python Requests library (r.text). Is there a simple way to convert this string into a dictionary? The string looks like this: "{"token":"abcdefghijklmnopqrstuvwxyz","redirect_url":"https://google.com/someurl/"}" I want to grab the "redirect_url". Any help would be much appreciated. Thank you! -
Node JS and Pyhton Integration
Is using python and node js together efficient and scalable? I want to make a highly scalable web application. Would Node JS help me achieve speed ? And if I wanted to do really intensive calculations I want to use python, so if I called a python function/script from a node js web application by passing the parameters would that make my application able to utilize the speed of node js and power of python together ? -
Django reverse url not matching pattern
from tests.py url = reverse('password_change_done', args =[self.mylog.token, self.john.password]) from urls.py url(r'^password_change_done/$', password_change_done, name='password_change_done'), I have this error: django.urls.exceptions.NoReverseMatch: Reverse for 'password_change_done' with arguments '('cc6f98fe-93ea-4cc2-97c5-a8b16b6308cc', 'pbkdf2_sha256$30000$zdbekeYMwQfC$WyW7FsZZg6hgWhmw6USs6etLVJlOnol6RmISFSlg1+4=')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['password_change_done/$'] I thought that the pattern reverse has used matches correctly so why am I getting this error? -
How do I type-hint that a Python function returns instance of any class derived from a superclass?
I've got a bunch of Django template inclusion tags, which take as an argument either a specific instance of a database object or a string/int, which is interpreted as the primary key of that database object. For example... {% render_product product=obj %} {% render_product product=42 %} {% render_product product="42" %} ...all work fine and do the obvious: they render a template fragment with a particular Product instance, fetching it by primary key from the database, if needed. This is how Product and similar classes are defined: class Product(models.Model): # standard django model definition goes here Here's what usually happens in such an inclusion tag: @register.inclusion_tag("render_product.html") def render_product(product: Union[Product, str, int] = None) -> dict: _product = None if isinstance(product, Product): _product = product elif isinstance(product, str) or isinstance(product, int): try: _product = Product.objects.get(pk=product) except (Product.DoesNotExist, ValueError): pass return {"product": _product} Since I've got the same pattern happening in dozens of inclusion tags, I'm trying to refactor it out, so that I've got something like: @register.inclusion_tag("render_product.html") def render_product(product: Union[Product, str, int] = None) -> dict: _product = fetch_object(Product, product) return {"product": _product} Here's the fetch_object code: def fetch_object(cls: Type[Model] = None, obj: Union[Model, str, int] = None): if isinstance(obj, cls): return … -
Django - get all related objects
I'm trying to make a deep copy of a model object. Means I want to copy the object itself, and all of the related model objects. So if I have a Customer model, and an Order model with a foreign key to customer, I want to copy the customer with all the Order objects. So I assuming a Cursomer model object, I can write customer.order_set.all() But do I get all the related sets? -
What are the advantages of using Elastic Beanstalk to deploy my Django App as compared to EC2?
I've built a simple blogging Django app for myself, and want to deploy it using AWS. After some research, it looks like my options for deployment are Elastic Beanstalk and EC2. What are the advantages of using Elastic Beanstalk over EC2? -
DJANGO creating categories with sub categories
I have come unstuck with a categories table I am trying to implement. I am building a project with multiple category levels but what I want to do is build a multi tier category structure. For example I have created the class with categories as below but I would like to achieve multi level categories as per example below Action > (+) Thriller or Boxing or Gang Related Any thoughts ? class Category(models.Model): CATEGORIES = ( ('ACT', 'Action'), ('THRILLER', 'Thriller'), ('COM', 'Comedy'), ('WEST', 'Western'), ('MILITARY', 'Military'), ) image = models.ImageField() description = models.CharField(max_length=500) quantity = models.IntegerField() category = models.CharField( max_length=10, choices=CATEGORIES ) date_posted = models.DateTimeField(auto_now_add=True, blank=True) -
How to make request.POST work through all view in django?
Why before filing the form parent_id work but than it doesn't work? my view: @login_required def get_one_post(request, post_id=None): form = CommentForm(request.POST or None) parent_id = request.POST.get('parent_id') here it work! if post_id is not None: posts = models.Post.objects.filter(id=post_id) comments = models.Comment.objects.filter(post__id=post_id) if request.POST and form.is_valid(): comment = form.save() comment.post = models.Post.objects.get(id=post_id) comment.author = models.Profile.objects.get(user=request.user) but here it doesn't work i don`t know why print(request.POST) if parent_id is not None: comment.parent = models.Comment.objects.get(id=parent_id) comment.save() return render(request, 'mainapp/one-post.html', {'posts': posts, 'nodes': comments, 'form': form}) else: redirect('mainapp/post_category.html') -
Test method in CBV in Django
I have the following CBV class Index(TemplateView): template_name="index.html" def custom_method(self): # do some stuff here print("Test") How can I test this method in a TestCase? I've tried the following but it's not working: def test_custom_method(self): response = self.client.get(reverse("index")) view_instance = Index.as_view() view_instance(response.wsgi_request) view_instance.custom_method() -
LimitOffsetPagination not working globally by default in Generics View if added in settings
In my settings.py I have the following code : REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', } In my generics view I have the following code: class ChildrenList(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = CheckItSerializer queryset = CheckIt.objects.all().order_by('-id') def get(self, request): try: queryset = CheckIt.objects.filter(box=request.user.userdetail.box_obj.id).order_by('-id') serializer = CheckItSerializer(queryset, many=True) context = {"success": True, "message": "CheckIt List", "error": "", "data": serializer.data} return Response(context, status=status.HTTP_200_OK) except Exception as error: context = {'error': str(error), 'success': "false", 'message': 'Failed to get CheckIt Details.'} return Response(context, status=status.HTTP_500_INTERNAL_SERVER_ERROR) ` How to make LimitOffsetPagination work on all the APIs without changing much of the APIs individually -
How to perform bulk update instead of updating each row?
I am new to python and django world and confused if there is a better way of doing the below: #retrieve account row, correct soc code and save record. for i in xrange(0,len(accIdList)): acc = account.objects.filter(id=accIdList[i])[0] acc.soc = getAccSocCode(acc) acc.save() def getAccSocCode(acc): #apply business rules on acc # and return new soc code return socCode This is what my code is doing now: Get account row from database Pass account object to a seperate method This method performs some business rules and returns new soc code Update account row Here I am updating each account row separately, is there a better way to this like below: #retrieve account row, correct soc code and save record. accList = [] for i in xrange(0,len(accIdList)): acc = account.objects.filter(id=accIdList[i])[0] acc.soc = getAccSocCode(acc) accList.append(acc) accList.save() I tried the above code but it throws error saying AttributeError: 'list' object has no attribute 'save' In short, how to perform bulk update in django? -
How to make complacted API with custom field in Django Rest Framework?
This is my model Aggrement. class Agreement(models.Model): EXPORT = 'EXPORT' IMPORT = 'IMPORT' TURNOVER_CHOICE = ( (EXPORT, 'Loan turnover'), (IMPORT, 'Debit turnover'), ) begin_date = models.DateField() end_date = models.DateField() period = models.ManyToManyField(Period, blank = True) company = models.ForeignKey(Company, on_delete = models.CASCADE) negotiator = models.ForeignKey('auth.User', on_delete = models.CASCADE) turnover = models.CharField(max_length = 6, choices = TURNOVER_CHOICE, default = EXPORT) Using Django Rest Framework i need to get something like that: /agreements/calendar/ in JSON: { 2014: [0, 0, 0, 0, 0, 0, 0, 0, 12, 1, 0, 5], 2015: [1, 0, 0, 4, 0, 0, 0, 1, 7, 10, 0, 4] } For each year need to get closed agreements per month. But i am more intrested how to get that kind of JSON. -
permission to create logfiles
I´m trying to create logfiles in django 2.0.8. As long as i´m using it on localhost, the logfiles will be created and everything is fine. But when i´m running it on iis7, it won´t create the logfiles anymore. The Logfiles are created with python(3.6.5) logging. manage.py: logging.config.fileConfig('ProjektServer/logging.ini') logging.ini_: [loggers] keys=root [handlers] keys=consoleHandler, rotatingFileHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler,rotatingFileHandler [handler_consoleHandler] class=logging.StreamHandler level=INFO formatter=simpleFormatter args=(sys.stdout,) [handler_rotatingFileHandler] class=logging.handlers.RotatingFileHandler args=(r'C:\log\project.log', 'a', 1000000, 3) level=INFO formatter=simpleFormatter [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= Afterwords it´s called like this in the pythonclasses for example: logger = logging.getLogger(__name__) ... logger.info("ID is %d", int(shiftid)) I allready tried to follow the following instructions, thinking it is an permission problem: https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities Open Windows Explorer List item Select a file or directory. Right click the file and select Properties Select the Security tab Click the Edit button and then Add button Click the Locations button and make sure that you select your computer. Enter IIS AppPool\DefaultAppPool in the Enter the object names to select: text box. Click the Check Names button and click OK. I also tried to run the website on the ISS with another Identity which is an Admin. But still no success. Am I still missing …