Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest-Framework Nested serializer Posting Two models
So I wanted to post request nested models, and I got the idea how to do it here: Django Rest Framework using nested serializer for posting data two models Here's my attempt to nest two models in order to make a post request, one label can have many packages views.py class LabelsView(APIView): def post(self, request, *args, **kwargs): packages = request.data.pop("packages", []) _label = super(LabelsView, self).create(request, *args, **kwargs) for package in packages: package["packages"] = _label.id serializer = PackagesSerializer(data=package) assert serializer.is_valid() serializer.save() return Response(_label) models.py class Packages(models.Model): label = models.ForeignKey(Labels, on_delete=models.CASCADE) weight_value = models.CharField(max_length=100) weight_unit = models.CharField(max_length=100) class Meta: managed = True db_table = 'core_packages' def __str__(self): return self.reference class Labels(models.Model): sender_name = models.CharField(max_length=100) sender_company = models.CharField(max_length=100) receiver_name = models.CharField(max_length=100) receiver_company = models.CharField(max_length=100) timestamp = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = 'core_labels' def __str__(self): return self.timestamp serializers.py class LabelsSerializer(serializers.ModelSerializer): class Meta: model = Labels packages = PackagesSerializer(read_only=True) fields=( 'sender_name', 'sender_company', 'receiver_name', 'receiver_company', ) class PackagesSerializer(serializers.ModelSerializer): class Meta: model = Packages fields=( 'weight_value', 'weight_unit', ) But I'm getting an error: AttributeError at /create/labels/ 'super' object has no attribute 'create' -
Test Image Upload Always Fails
I cannot get any of my image upload unit tests to work. The following test fails with AssertionError: <ImageFieldFile: profile_pics/default.jpg> != 'test_image.jpg' (Ignoring the fact that my test would fail regardless because it's comparing an ImageFieldFile to my string, more importantly the image doesn't update. I'll fix the assertion later). def test_upload_image_works(self): user = User.objects.create(username='testuser', email='user@example.com') self.client.force_login(user) with open(settings.MEDIA_ROOT+'\profile_pics\\default_test.jpg', 'rb') as infile: self.client.post( reverse('update_profile', args=('testuser',)), content_type='multipart/form-data', data = {'image': infile}, follow=True ) user.refresh_from_db() self.assertEqual(user.profile.image, 'default_test.jpg') However this similar test passes def test_info_update_works(self): user = User.objects.create(username='username', email='user@example.com') self.client.force_login(user) self.client.post(reverse('update_profile', args=('username',)), { 'email': 'updated@example.com' }) user.refresh_from_db() self.assertEqual(user.email, 'updated@example.com') EDIT: @login_required @allowed_users(allowed_roles=['admin', 'registered_user']) def update_profile(request, username): # refuse access if logged in user does not match username if not request.user == User.objects.get(username=username): response = HttpResponse() response.status_code = 403 return response if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated') return redirect('update_profile', username=User.objects.get(username=username)) else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form' : u_form, 'p_form' : p_form } return render(request, 'users/update_profile.html', context) Thank you. -
Generating fake data to populate database
I am trying to use factory boy and faker to generate some fake data for a website I am building. Here is my models.py: # External Imports from django.db import models import uuid # Internal Imports from applications.models.application import Application from users.models.user import User from .session import Session # Fake data import factory import factory.django import factory.fuzzy from datetime import datetime from faker import Faker from faker.providers import BaseProvider import random class ButtonClick(models.Model): """**Database model that tracks and saves button clicks for an application** """ # identifier id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) # info button_name = models.CharField(max_length=128, null=True, blank=True) application = models.ForeignKey( Application, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE) user = models.ForeignKey( User, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE) session = models.ForeignKey( Session, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'button_clicks' ordering = ('-timestamp', ) def __str__(self): return f'{self.application} - {self.button_name}' fake = Faker() faker = Factory.create() class ApplicationFactory(factory.DjangoModelFactory): class Meta: model = Application application = factory.LazyAttribute(lambda _: faker.word()) class FakeButtonClick(factory.django.DjangoModelFactory): class Meta: model = ButtonClick button_name = factory.Faker('first_name') application = factory.SubFactory(ApplicationFactory) user = factory.Faker('name') session = factory.Faker('random_int') timestamp = factory.Faker('date') When I try to run the following code in the terminal, I get an error: >>> from analytics.models.button_click import … -
Saving a JSON list - Django
I am working with a JSON request.get that returns a list. I will like to save each individual object in the response to my models so I did this: in views.py: def save_ram_api(request): r = requests.get('https://ramb.com/ciss-api/v1/') # data = json.loads(r) data = r.json() for x in data: title = x["title"] ramyo_donotuse = x["ramyo"] date = x["date"] thumbnail = x["thumbnail"] home_team_name = x["side1"]["name"] away_team_name = x["side2"]["name"] competition_name = x["tournament"]["name"] ramAdd = ramSample.objects.create(title=title, ramyo_donotuse=ramyo_donotuse, date=date, thumbnail=thumbnail, home_team_name=home_team_name, away_team_name=away_team_name, competition_name=competition_name) ramAdd.save() return HttpResponse("Successfully submitted!") This works fine except that it would only save the last objects on the list. the JSON response list (as a random 60 objects at any time) would look something like: [ { "title": "AY - BasketMouth", "ramyo": "AY de comedian" "side1": { "name": "Comedy Central", "url": "https:\/\/www.rabithole.com\/laugh\/dave-chappel\/" }, "side2": { "name": "Basket Mouth", "url": "https:\/\/www.rabithole.com\/laugh\/chris-rockie\/" }, "tournament": { "name": "Night of a thousand laugh", "id": 15, "url": "https:\/\/www.rabithole.com\/laugh\/chris-rockie\/" }, "points": [ { "nature": "Gentle", "phrase": "Just stay" }, { "nature": "Sarcastic", "phrase": "Help me" } ] }, { "title": "Dave - Chris", "ramyo": "Dave Chapelle" "side1": { "name": "Comedy Central", "url": "https:\/\/www.rabithole.com\/laugh\/dave-chappel\/" }, "side2": { "name": "Chris Rockie", "url": "https:\/\/www.rabithole.com\/laugh\/chris-rockie\/" }, "tournament": { "name": "Tickle me", "id": 15, … -
How to update status in Admin from a drop downlist
Hi I have in my order Model a status where I can choose the status of the order. I want to be able to update the status from the external display of the admin instead of going inside of the detail view of the order. Here is the models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) status = models.CharField(max_length=50, choices=[('pending', 'Pending'), ('ofd', 'Out For Delivery'), ('recieved', 'Recieved')], default='pending') Here is the admin.py class OrderAdmin(admin.ModelAdmin): list_display = ['user', 'ordered', 'ordered_date', 'status','ref_code'] -
How to pass in the token for authorization in between React pages (in a Django Knox setup)?
I have 2 components/pages. One is the login page and one is the user customization page. I want the user customization page to be token authorized so you can only see it after you login. I am using a Django + React setup with Django Knox being used as the authorization tokens. I now have a workflow using this.props that passes the token from the login component to the main app.js and then to the user customization component. But I guess during the routing/switching between pages, my token is lost. How do I maintain this token? -
What's the correct way of defining a method in a model class that queries for other models?
Recently I found the need to create a method for a class that queries another model. While my solution works, I would like to know if it's the correct or conventional way of handling this scenario (I'm fairly new to Django). The problem looks like this: class Company(models.Model): # Company properties # ... pass class Worker(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) # Other properties # ... active = models.BooleanField(default=True) Now, a very common scenario in many views is to require all the active workers from a given company. Usually, I would do something like this: Worker.objects.filter(company=some_company, active=True) The problem with the above code is that it has to be repeated in many places, and if I forget one of the filters, I would get the wrong results. To avoid this, I created a method in the Company class: class Company(models.Model): # Company properties # ... def active_workers(self): return self.worker_set.filter(active=True) # Which lets me use: some_company.active_workers() This has been working fine so far, but I'm wondering if there is a better way of handling this in Django. Maybe using an object manager? -
Populate web page using API result directly from API server
Firstly sorry if this question has been asked before but I'm a novice so even if it has I'm unaware of the language I'd even use to try and seek it out. I'm beginning to learn about REST API's and it got me thinking. Is it possible to load the JSON response directly from the API server into the user's browser and bypass your own server? Imagine you have say a Django app running on a server that accesses email messages from Outlook.com using the graph API. I assume an ordinary flow would go something like: User request->your server->graph api-> your server-> user browser. It seems like a waste for it to hit your server that second time before it goes on to be presented to the user's browser. Is there a way the Django app can render a template and effectively tell the browser "expect some data from X source, and place it in y location in this template"? -
Storing and downloading files from Redis in Django Celery Queue
I'm zipping a large number of files in my app, which leads to problems with performance. So now I've decided to zip files in a separate queue, store results in Redis and make available to user as soon as the process is done. I'm storing data in Redis to make it faster, and because I don't need files to be stored on server hard drive. Here is my task.py: @shared_task def zip_files(filenames, key): compression = zipfile.ZIP_STORED s = BytesIO() zf = zipfile.ZipFile(s, mode="w") for fpath in filenames: fdir, fname = os.path.split(fpath) zf.write(fpath, fname, compress_type=compression) zf.close() caches['redis'].set(hash_key, {'file':s.getvalue()}) return hash_key And then here is my simple download view: def folder_cache(request, folder_hash): cache_data = caches['redis'].get(folder_hash) if cache_data: response = FileResponse(cache_data['file'], content_type="application/x-zip-compressed") response['Content-Disposition'] = 'attachment; filename=hello.zip' response['Content-Length'] = len(cache_data['file']) return response return HttpResponse("Cache expired.") Problem is that I can only download a part of the file, then the download is stopped by "Network connection was lost" message. The downloaded file seems to contain a set of numbers (not binary data). But I don't know, maybe I use FileResponse wrong? Or I need to serialize data before / after putting it to Redis cache? I also tried same code in shell, it works when … -
Printful API Key on Python script
I will use the Printfull API, but I can't find on way to test the API Key, on my script. Some of you can tell me how is the best way to do this? Thank you. Flavio import json import requests key = ('mwi4tpvh-j0ka-pwsk:dgj0-83boo2cnfog2') r = requests.get('https://api.printful.com/sync/products') packages_json = r.key.json() print(packages_json) -
In Django, how do I link my verification email's link to a dynamic URL?
I'm trying to have users verify their email address by clicking a verification link sent to their email. So far, I've managed to accomplish just that, except that the issue I'm running into is that Django doesn't recognize the URL and returns the error Page not found (404). As instructed here, my urls.py looks like this: from django.contrib import admin from django_email_verification import urls as mail_urls url_patterns = [ re_path(r"^verification-successful/$", views_register.verification_successful, name="verification_successful"), # The view I want the users to see when the link is clicked path('admin/', admin.site.urls), # This is needed according to the instructions path('email/', include(mail_urls)), ] And the resulting error looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/verfication-successful/email/this-is-the-generated-token-letters-and-numbers So clearly, what's provided out of the box isn't the most conducive to being redirected where I want. There's also the off chance I'm using this third party email verification package incorrectly, so here's more context as what I'm trying to accomplish: I'm using Django 3.0.7 and the package django-email-verification. This package implies that it works on Django version 3.0.7 exclusively, so if possible, I would like to keep using this version of Django. The user should be able to click on the given … -
In Django, when using ManifestStaticFilesStorage, why do I get 404s when trying to serve the collected static files?
I have a Django site hosted on Google App Engine. My goal is to version the static files with MD5 tags like is done with ManifestStaticFilesStorage. I worried a bit about ManifestStaticFilesStorage's compatability with Google App Engine. But since I've heard about Django on Heroku with Whitenoise so often, and as far as I know Heroku and Google App Engine are very similar, I am trying to install Whitenoise in my development environment and get it running there. I have had some difficulty in setting this up; I think I have eliminated Whitenoise itself as the cause of my problem, because it replicates exactly when using ManifestStaticFilesStorage, but I have not been able to figure out what is the cause of my problem. Whitenoise's documentation says I know it's working correctly if I can set DEBUG=False, run collectstatic, then see the static files served from their collected location in development; it should then be working exactly how it will be working in production. This is the problem: under these conditions, I get a lot of 404s related to static files and I'm not sure why. I have been trying to follow the instructions listed here quite closely. This document implies … -
Django rest framework serializer data for empty queryset
If there are no objects in a queryset, is there a way to send null values for all the attributes models.py class ExampleModel(models.Model): key1 = models.CharField(max_length=100) key2 = models.CharField(max_length=100) key3 = models.CharField(max_length=100) serializer.py class ExampleModelSerializer(serializers.ModelSerializer): class Meta: model = ExampleModel fields = '__all__' views.py @api_view(['GET']) def objects_list(request): if ExampleModel.objects.all(): objects = ExampleModel.objects.all() serializer = ExampleModelSerializer(objects, many=True) return Response(serializer.data) else: return Response('No Objects') Here in this case if there are no objects then is there a way to get a response like this instead of a string [ { "id": null, "key1": null, "key2": null, "key3": null, } ] -
My code does not return the correct view in Django
View def compose(request): if request.method == "POST": if request.POST["confirmation"] is True: form = ComposeForm() return render(request,"practice/compose.html",{"form":form}) else: a = reverse("practice:index") return HttpResponseRedirect(a) else: a = reverse("practice:index") return HttpResponseRedirect(a) Form <form action= "{% url 'practice:Compose' %} " method=post> Do you want to send emails to the following list?<br> <br> <button name="confirmation" type="submit" value="True">Yes</button> <button name="confirmation" type="submit" value="False">No</button> </form> When the Yes button was clicked, the index page was shown. However, it should have executed return render(request,"practice/compose.html",{"form":form}) I suspect my if and else are wrong. Please help, thanks! -
Nginx Reverse proxy is rerouting to my api gateway instead of sending a post request
I have created a single page application, I just want to send a post request to my Django server to login into my application from another device on a different network. Whenever I travel to my domain name I am re-routed to my API gateway, instead of my application. server{ listen 80; listen 443 ssl; ssl_certificate C:/Certbot/live/buzzcola.com/fullchain.pem; ssl_certificate_key C:/Certbot/live/buzzcola.com/privkey.pem; server_name buzzcola.com www.buzzcola.com; root /nginx_test/www1/buzzcola.com; index index.html; location = /favicon.ico { return 204; access_log off; log_not_found off; } location / { proxy_pass http://localhost:8000; } } Whenever I set up the location to point directly at an endpoint it won't work. location /get-token/ { proxy_pass http://localhost:8000; } I am new to Nginx so any help would be appreciated, thank you. -
User matching query does not exist in django
I have been trying to add a following system to my django project which is very similar to instagram's follow system. Well, I got to a point where I had to add a signals.py file so that there could be a follower count in a user's profile, as soon as I run the code, I got a 500 error on jquery and a User matching query does not exist error in the url that has the follow view. What can I do to stop having this errors? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = models.ManyToManyField(User, related_name="followed") follower = models.ManyToManyField(User, related_name="follower") @classmethod def follow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.add(another_account) print("followed") @classmethod def unfollow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.remove(another_account) print("unfollowed") def __str__(self): return f'{self.user.username} Profile' views.py def follow(request, username): main_user = request.user to_follow = User.objects.get(username=username) following = Following.objects.filter(user = main_user, followed = to_follow) is_following = True if following else False if is_following: Following.unfollow(main_user, to_follow) is_following = False else: Following.follow(main_user, to_follow) is_following = True resp = { 'following': is_following, } … -
get_absolute_url() missing 1 required positional argument: 'self'
I imagine the solution to this can be found i similar topics, however, it seems a little bit different from problems I have seen. The redirect, in add_post view, should send me to the Post class, where I have a get_absolute_url. But it happens that I get the following error message: get_absolute_url() missing 1 required positional argument: 'self' I literally copied the coded form the "Django Projects Cookbook" in case you wanna check it out and try the code yourself. Thank you. from django.contrib.auth.decorators import user_passes_test from django.shortcuts import redirect, render_to_response, get_object_or_404, render from .models import Post from .forms import PostForm, CommentForm @user_passes_test(lambda u: u.is_superuser) def add_post(request): form = PostForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect(Post) # redirect to Post class return render(request, 'blog/add_post.html',{ 'form': form }) def view_post(request, slug): post = get_object_or_404(Post, slug=slug) form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect(request.path) return render(request, 'blog/blog_post.html',{'post': post,'form': form,}) from django.db import models from django.template.defaultfilters import slugify from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) text = models.TextField() created_on = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): # … -
Django If condition in view.py
TO SAVE DATA that is inputted in form in Django i tried tomake it like this I put this in my model.py class Item(models.Model): CATEGORY = ( ('Gudang Kering', 'Gudang Kering'), ('Gudang Basah','Gudang Basah'), ) name = models.CharField(max_length=200,null= True) stock = models.IntegerField(default='0', blank=False, null=True) category = models.CharField(max_length=200,null= True,choices=CATEGORY) reorderlevel = models.IntegerField(default='0', blank=False, null=True) maxreorderlevel = models.IntegerField(default='0', blank=False, null=True) description = models.CharField(max_length=200,null= True, blank= True) date_created = models.DateTimeField(auto_now_add= True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name class Issue(models.Model): STATUS = ( ('Pending', 'Pending'), ('Granted','Granted'), ('Denied','Denied'), ) customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) item = models.ForeignKey(Item, null=True, on_delete= models.SET_NULL) quantity = models.IntegerField(default='0', blank=False, null=True) date_created = models.DateTimeField(auto_now_add=True, auto_now=False) status = models.CharField(max_length=200,null= True, choices=STATUS) Then in view.py i define the form like this def issue_items(request, pk): queryset = item.objects.get(id=pk) queryset2 = issue.onjects.get(id=pk) form = issueform(request.POST or None, instance=queryset, instance2=queryset2) if form.is_valid(): if instance2.status == "Granted" instance.quantity -= instance2.quantity instance2.customer instance2.item instance2.datecreated instance.save() instance2.save() else: instance.quantity -= instance2.quantity instance2.customer instance2.item instance2.datecreated instance.save() instance2.save() return redirect('/issue_detail/'+str(instance2.id)) # return HttpResponseRedirect(instance2.get_absolute_url()) context = { "title": 'Pengeluaran ' + str(queryset2.item), "queryset2": queryset2, "form": form, , } return render(request, "add_items.html", context) This is the form in form.y class Meta: model = item fields = ['issue_quantity','status'] def clean_issue_quantity(self): issue_quantity = … -
amazon AWS RDS and Django not playing well
I am trying to run the command ./manage.py loaddata to populate my rds postgres db, however when i run it the command just hangs forevor. Any ideas how to fix this? -
How to pass python list to javascript array using Django
I have a Django project where I am trying to pass a list of values from a python function to my 'index.html' file. This list of values comes from a DB query in my views.py file my views.py def index_view(request): context = {} con=sqlite3.connect("db.sqlite3") cursor=con.cursor() db_query="SELECT distinct product_name from dboinvproduct" cursor.execute(db_query) result=cursor.fetchall() con.close() list_of_products = list(itertools.chain(*result)) context['product_names'] = list_of_products return render(request, 'index.html', context) then within the body of my index.html {% for list_item in product_names %} {{ list_item }}<br> {% endfor %} it prints the following on the homepage: product a product b product c product d Which is great because that means it is working. Those are the values stored in 'product_name' in the database and the template is working! Now I need to put those values into a javascript array. In the index.html file I have a script that runs 'onload' of the body. In that same script, I need to declare an array, and loop through the product_names from the context, and assign them to the array... but I am unsure how to do that exactly because I am new to Django so I am unsure exactly how to use the templates. Below is an examples as … -
get value from Dict in Django
given a dict: context {'department': <QuerySet [<DepartmentDetails: Administration>]>, 'globalalert': <QuerySet []>, 'globalmessage': <QuerySet []>, 'next_task': {'instance': {'activityId': 'Process_B_PerProject:1:9481d86a-cc57-11ea-8be8-00155d891509', 'activityName': 'B Activites Per Project', 'activityType': 'processDefinition', 'childActivityInstances': [{'activityId': 'Task_5.1', 'activityName': '5.1 ' 'Assessment ' 'and ' 'Need', 'activityType': 'callActivity', 'childActivityInstances': [], 'childTransitionInstances': [], 'executionIds': ['9c3307e8-cc63-11ea-8be8-00155d891509'], 'id': 'Task_5.1:9c3307e9-cc63-11ea-8be8-00155d891509', 'name': '5.1 ' 'Assessment ' 'and Need', 'parentActivityInstanceId': '9c3292b0-cc63-11ea-8be8-00155d891509', 'processDefinitionId': 'Process_B_PerProject:1:9481d86a-cc57-11ea-8be8-00155d891509', 'processInstanceId': '9c3292b0-cc63-11ea-8be8-00155d891509'}], 'childTransitionInstances': [], 'executionIds': ['9c3292b0-cc63-11ea-8be8-00155d891509'], 'id': '9c3292b0-cc63-11ea-8be8-00155d891509', 'name': 'B Activites Per Project', 'parentActivityInstanceId': None, 'processDefinitionId': 'Process_B_PerProject:1:9481d86a-cc57-11ea-8be8-00155d891509', 'processInstanceId': '9c3292b0-cc63-11ea-8be8-00155d891509'}}, 'organisation': <QuerySet [<OrganisationDetails: Acme developments PLC>]>, 'project': <QuerySet [<ProjectLive: ProjectLive object (30d44422-7b90-4b6b-ac88-fb52a4e3edb9)>, <ProjectLive: ProjectLive object (bea0ed54-a81e-4241-8cfd-0e60c66cdbf1)>]>, 'result': {'process': {'businessKey': '57a4c7e9-fd9f-4d71-a39d-7bd8e112a39a', 'caseInstanceId': None, 'definitionId': 'Process_B_PerProject:1:9481d86a-cc57-11ea-8be8-00155d891509', 'ended': False, 'id': '9c3292b0-cc63-11ea-8be8-00155d891509', 'links': [{'href': 'http://localhost:8080/engine-rest/process-instance/9c3292b0-cc63-11ea-8be8-00155d891509', 'method': 'GET', 'rel': 'self'}], 'suspended': False, 'tenantId': None, 'variables': {'Organisation': {'type': 'String', 'value': '98901267-543b-4c02-be66-38252e857a3d', 'valueInfo': {}}, 'StartDate': {'type': 'String', 'value': '<django.db.models.query_utils.DeferredAttribute ' 'object at ' '0x04A364A8>', 'valueInfo': {}}, 'Startedby': {'type': 'String', … <trimmed 4283 bytes string> I am trying to get the value of name within - context --> next_task -->instance -->childActivityInstances. The method i used to get id from 'result' although not efficient works ok: set_new = context['result'] my_id = set_new.get('process') my_id1 = my_id.get('id') This doesn't work for getting name as its enclosed within [] and i get a type error : … -
Django Custom User Model Failes to encrypt password from admin site
I have created a custom user model by inheriting AbstractBaseUser, PermissionsMixin and also created a Custom Manager for creating users and superuser. But when I try to add new user from Django admin site, it fails to encrypt the password field and keeps the plain text. But when I request from the client site by using the Serializer's create function it works fine. Custom Model Class Code: from django.db import models from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin) from .managers import UserManager class CustomUser(AbstractBaseUser, PermissionsMixin): """ Responsible for handleing App user's data """ username = models.CharField(max_length=20,unique=True) email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_authority = models.BooleanField(default=False) is_general_user = models.BooleanField(default=False) timestamps = models.DateTimeField(auto_now_add=True) update_on = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username Custom Manager: from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): """ Creates and saves a new user """ user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): """ For superusers registration """ user = self.create_user(email=email, password=password) user.is_staff = True user.is_superuser = True user.is_active = True user.is_authority = True user.save(using=self._db) return user … -
Django making a user comment on a post where the user is automatically made the author
Hello im trying to make a django application where when a post is made the someone who is logged in can comment on the post but it will automatically insert their name/account rather then them having to put it. So all the user has to do is add body content. forms.py ''' from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name','body',) ''' views.py ''' from django.shortcuts import render, get_object_or_404 from .models import Post, Comment from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.views.generic import ListView from .forms import CommentForm from django.contrib.auth.models import User class PostListView(ListView): queryset = Post.cleared.all() context_object_name = 'posts' paginate_by = 3 template_name = 'posts/post/list.html' def post_detail(request, year, month, day, post): post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request,'posts/post/detail.html', {'post':post , 'comments': comments,'new_comment': new_comment,'comment_form': comment_form}) ''' models.py ''' from django_currentuser.db.models import CurrentUserField from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.conf import settings class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='cleared') class Post(models.Model): STATUS_CHOICES = … -
Get Subclass of Individual Instance Django
I have a database schema in Django: Employee: - Name: CharField - Email: EmailField RankedEmployee: - Employee: ForeignKey with Employee - Ranking: IntegerField SoftwareEngineer (extends Employee): - Favorite language: CharField Janitor (extends Employee): - Cleaning location: CharField I can access an Employee like this: RankedEmployee.objects.get(id=1).employee But this returns an instance of type Employee, not SoftwareEngineer or Janitor. How can I get the subclass? Anything helps! Thanks! -
How to return single object in a Django model and view
I would like to return a very basic, single paragraph from a model but I don't know how or which is the best approach. It's a simple description textField (maindescription) that I would like to be able to change in the future instead of hard-coding it. It has to be simple way but I just could find a good example. Would appreciate any help on how to properly write the view and retrieve it in the template. model.py from autoslug import AutoSlugField from model_utils.models import TimeStampedModel from time import strftime, gmtime # Receive the pre_delete signal and delete the file associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver class Song(models.Model): author = models.CharField("Author", max_length=255) song_name = models.CharField("Song Name", max_length=255) slug = AutoSlugField("Soundtrack", unique=True, always_update=False, populate_from="song_name") created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) audio_file = models.FileField(upload_to='mp3s/', blank=True) def __str__(self): return self.song_name class MainDescription(models.Model): main_description = models.TextField() slug = AutoSlugField("Main Description", unique=True, always_update=False, populate_from="main_description") def __str__(self): return self.main_description view.py from django.views.generic import ListView, DetailView from .models import Song class SongListView(ListView): model = Song #doesn't work as expected # class MainDescriptionListView(ListView): # model = MainDescription admin.py from django.contrib import admin from .models import Song, MainDescription admin.site.register(Song) admin.site.register(MainDescription) song_list.html {% …