Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extend gettext_lazy to translate strings in variables?
There is a code that works fine: from django.utils.translation import gettext_lazy gettext_lazy('Hello!') But this, does not work: from django.utils.translation import gettext_lazy greetings = 'Hello!' gettext_lazy(greetings) Also this, does not work: from django.utils.translation import gettext_lazy def custom_gettext_lazy(content): return gettext_lazy(content) custom_gettext_lazy('Hello!') It seems, that makemessages scans for all files as plain text and searches for gettext_lazy imports and then its explicit usage Is it possible to force makemessages grab strings from custom functions like custom_gettext_lazy that performs some additional stuff? -
Haystack index_queryset filter not working when updating object from Admin panel
I'm indexing a model with some conditions. It works fine. But, when I'm updating some info from Admin panel the conditions are not working. SearchIndex: class QuestionBankIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True, template_name='search/question_bank_text.txt') question_id = indexes.IntegerField(model_attr='id') owner = indexes.CharField(model_attr='owner', null=True) def get_model(self): return QuestionBank def index_queryset(self, using=None): return self.get_model().objects.filter(active=True) So, while I'm changing an object from Admin panel, this object is indexing even if it's active=False I'm using Haystack==3.0 with Realtime_Signal_Processor configuration. -
Different PostgreSQL database: local and remote | Django
I've just configured my remote PostgreSQL database @ Elephant but now I'd like to also set the local PostgreSQL connection in order to make some tests before going online (remote db). This is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'lallah.db.elephantsql.com', 'PORT': '5432', } } How can I update the settings.py to also let me use the localhost PostgreSQL connection without erasing the elephant configurations? Thank you! -
Update Customer metadata in stripe using dj-stripe in Django
I'm integrating Stripe via dj-stripe into a Django project. Everything is working well, but I now want to add something in the Customer metadata field either at customer creation, or right after. The problem is, I can't find how to add metadata to a customer object anywhere in the dj-stripe code (here is the Customer model), or docs. It seems like fairly standard functionality, so I feel like I must be missing something. -
How to order Django objects by the attributes of their foreign keys?
I have the following code: from django.db import Models class Model1(models.Model): #Attributes... class Model2(models.Model): model1_foreign_key = models.ForeignKey(Model1, related_name='some_name', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) My objective is to order the first item by the latest creation of their foreign keys. For example: Today is September eighth Model A is an instance of Model1 and has two models related to it via the foreign key, model B (created on September 5th) and model C (created on September 6th). Assume times don't matter here. Model D is an instance of Model1 and has another two models related to it via a foreign key, E and F (Created on September 5th and 7th respectively). Given access to a list of objects of Model1, such as Model1.objects.all, how can I order the models such that model D comes first (It has the latest Model2 object, created on september 7th). Alternatively, what can I change to achieve the same result? -
Creating Profile with Django Signals: Custom user field not showing up in signal
I currently have a custom user model that triggers a signal which creates an associated profile. My problem is that I need the signal to create a different type of profile depending on the user type selected during user creation. For whatever reason, it seems that I am able to access the user instance but not the instance.user_type in my signal. I've been searching all over for a similar case and I just can't figure out what I am doing wrong. My signal and user model are below: in users.signals.py @receiver(post_save, sender=User) def build_profile_on_user_creation(sender, instance, created, **kwargs): if created: if instance.user_type == 'T1': profile = Type1(user=instance) profile.save() if instance.user_type == 'T2': profile = Type2(user=instance) profile.save() in users.models.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, user_type, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, user_type=user_type, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) … -
Django signals does not work with get_user_model()
I am trying to add profile picture to user when user is created but upon creating user when I try to log in I get User has no profile, even when I try to log in into Django admin with superuser. This error is caused by instance.profile.save() in signals.py file. Here is my signals.py: from django.contrib.auth import get_user_model from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile User = get_user_model() @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print('inside signals') print(created) if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def create_profile(sender, instance, **kwargs): print('inside profile create') instance.profile.save() Here is my Profile model: from django.db import models from django.conf import settings # Create your models here. User = settings.AUTH_USER_MODEL class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f"{self.user.username} Profile" Here is my register view: User = get_user_model() def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') password2 = form.cleaned_data.get('password2') try: user = User.objects.create_user(username, email, password) except: user = None if user != None: # request.user == user # login(request, user) return redirect('login') else: request.session['register_error'] = 1 return render(request, "recipe/forms.html", {'form': form, 'title': 'Join Today'}) I did import accounts.signals … -
Websocket Handshaking Error in Python Django
I am getting issue with websocket connection as it is getting closed due to handshake error , The error Message are as below: WebSocket HANDSHAKING /ws/polData/ [127.0.0.1:59304] Exception inside application: object.__init__() takes exactly one argument (the instance to initialize) Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/usr/lib/python3.7/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/usr/lib/python3.7/site-packages/channels/sessions.py", line 172, in __call__ return await self.inner(self.scope, receive, self.send) File "/usr/lib/python3.7/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/usr/lib/python3.7/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/usr/lib/python3.7/site-packages/channels/routing.py", line 160, in __call__ send, File "/usr/local/lib/python3.7/dist-packages/asgiref/compatibility.py", line 33, in new_application instance = application(scope) File "/usr/lib/python3.7/site-packages/channels/generic/websocket.py", line 159, in __init__ super().__init__(*args, **kwargs) TypeError: object.__init__() takes exactly one argument (the instance to initialize) WebSocket DISCONNECT /ws/polData/ [127.0.0.1:59304]\ Please do the Needful. -
mock attribute assertion failure
I am relatively new to python testing. I am using unittest.mock to test a Django view function. I am mocking a model. I am using TDD and once the view layer has got all its test passed, I will implement the changes in the model. def new_list(request): form = ItemForm(data=request.POST) if form.is_valid(): list_ = List() list_.owner = request.user print(list_.owner) list_.save() form.save(for_list=list_) return redirect(list_) else: return render(request, 'home.html', {'form': form}) The test code is as follows: @patch('lists.views.list') @patch('lists.views.ItemForm') def test_list_owner_is_saved_if_user_is_authenticated( self, mockItemFormClass, mockListClass): user = User.objects.create(email='a@b.com') self.client.force_login(user) self.client.post('/lists/new', data={'text': 'new item'}) mock_list = mockListClass.return_value self.assertEqual(mock_list.owner, user) The error that I get is as follows: FAIL: test_list_owner_is_saved_if_user_is_authenticated (lists.tests.test_views.NewListTest) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 1204, in patched return func(*args, **keywargs) File "/Users/asim/python-projects/django-todo-list/superlists/lists/tests/test_views.py", line 181, in test_list_owner_is_saved_if_user_is_authenticated self.assertEqual(mock_list.owner, user) AssertionError: <MagicMock name='list().owner' id='140457579271392'> != <User: User object (a@b.com)> I thought that Magic mock will return any assertion true. Any help and an explanation will be highly appreciated. -
How to have multiple slug_field to display my other fields from model.py
This is my serializers.py class ServiceSerializer(serializers.ModelSerializer): technologies = serializers.SlugRelatedField(read_only=True, many=True, slug_field="title") class Meta: model = Service fields = ('id', 'title', 'description', 'technologies') class TechnologiesAndFrameworkSerializer(serializers.ModelSerializer): class Meta: model = TechnologiesAndFramework fields = ('id', 'title', 'description') This is my models.py class Service(models.Model): title = models.CharField(blank=False, null=False, max_length=256) description = models.CharField(blank=False, null=False, max_length=256) def __str__(self): return self.title class TechnologiesAndFramework(models.Model): title = models.CharField(blank=False, null=False, max_length=256) description = models.CharField(blank=False, null=False, max_length=256) service = models.ForeignKey(Service, on_delete=models.CASCADE, null=True, related_name='technologies') def __str__(self): return self.title This is the output i am getting. [ { "id": 1, "title": "Backend", "description": "Back-end Development refers to the server-side development. It is the term used for the behind-the-scenes activities that happen when performing any action on a website. It can be logging in to your account or purchasing a watch from an online store.", "technologies": [ "Django", "Postgres" ] }, { "id": 2, "title": "Frontend", "description": "Front-end web development, also known as client-side development is the practice of producing HTML, CSS and JavaScript for a website or Web Application so that a user can see and interact with them directly.", "technologies": [ "React JS", "Wagtail", "Bootstrap" ] }, Currently I am only able to fetch only titles. How can i also fetch description … -
Why I'm getting this error while building docker image?
I got the following error while building a docker image by "docker-compose build". ERROR: Couldn't connect to Docker daemon at http://127.0.0.1:2375 - is it running? If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable. Even if I try with "sudo", I got this: Building web Step 1/8 : FROM python:3.8.3-alpine ---> 8ecf5a48c789 Step 2/8 : WORKDIR /usr/src/app ---> Using cache ---> 87bb0088a0ba Step 3/8 : ENV PYTHONDONTWRITEBYTECODE 1 ---> Using cache ---> 4f1a6ddf9e1f Step 4/8 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 5d22b6b7a0f5 Step 5/8 : RUN pip install --upgrade pip ---> Using cache ---> 169ee831f728 Step 6/8 : COPY ./requirements.txt . ---> Using cache ---> 4b4351e31632 Step 7/8 : RUN pip install -r requirements.txt ---> Running in a4dae2fe3761 Collecting asgiref==3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) Collecting cffi==1.14.3 Downloading cffi-1.14.3.tar.gz (470 kB) Collecting cryptography==3.2.1 Downloading cryptography-3.2.1.tar.gz (540 kB) Installing build dependencies: started Installing build dependencies: finished with status 'error' ERROR: Command errored out with exit status 1: command: /usr/local/bin/python /usr/local/lib/python3.8/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-p3ocmpkd/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.6.0' wheel 'cffi>=1.8,!=1.11.3; platform_python_implementation != '"'"'PyPy'"'"'' cwd: None Complete output (128 lines): Collecting setuptools>=40.6.0 Downloading setuptools-50.3.2-py3-none-any.whl (785 kB) Collecting wheel Downloading wheel-0.35.1-py2.py3-none-any.whl … -
How to simplify the code and is it necessary?
I work on the API in the Django REST Framework. And now there is such a problem: there is a ModelViewSet and in its functions the same request to the database, the same check in the if block. Is it possible to somehow move this matter into a separate function and how to do it? class LinkViewSet(ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = LinkSerializer queryset = Link.objects.all() def retrieve(self, request, *args, **kwargs): instance = Link.objects.filter(Q(user_id=self.request.user.id) & Q(id=kwargs["pk"])).first() if not instance: return Response(data="Not found", status=status.HTTP_404_NOT_FOUND) return super().retrieve(request, *args, **kwargs) def partial_update(self, request, *args, **kwargs): instance = Link.objects.filter(Q(user_id=self.request.user.id) & Q(id=kwargs["pk"])).first() if not instance: return Response(data="Not found", status=status.HTTP_404_NOT_FOUND) return super().partial_update(request, *args, **kwargs) -
Django server stops running after I add a new app to settings
from django.db import models Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" Return self.text After creating this model and adding the "justice" app to the settings, the server stops working -
Get property from django template tag
I have a simple tag from which I return rendered_payload which has two properties html and reduxState: @register.simple_tag def header_and_sidebar(): user = {} # Here's what we've got so far render_assets = { 'url': '/policy-portal/list',#request.path_info, 'user': user } try: res = requests.post('http://docker.for.mac.localhost:8000/' + 'render', #settings.FRONTEND_URL json=render_assets, headers={'content_type': 'application/json'}) rendered_payload = res.json() except Exception as e: print(e) ... return rendered_payload when I attempt to use the tag in a template as so: {% load project_tags %} {% header_and_sidebar.html %} But this errors out with: Invalid block tag on line 164: 'header_and_sidebar.html'. Did you forget to register or load this tag? How should I go about accessing a nested property? This setup works fine when I am not trying to access a nested property, so I know it is configured properly for the most part. Here is my settings.py for good measure: TEMPLATES = [ { ... 'OPTIONS': { 'libraries': { 'project_tags': 'base.templatetags.custom_tags', }, ... } -
Django IntegrityError NOT NULL constraint failed (NO Foreign Key)
Have been searching on the Internet but still have no idea what's wrong... I got a message of this: Request Method: POST Request URL: http://localhost:8000/cases/location/form_submission Django Version: 3.1.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: cases_location.date_from I am submitting a form by post. All textfield have default values and aren't NULL. in the html file containing the form: <form name = "location" method="post" action="{% url 'form_submission' %}"> {% csrf_token %} Add a new location: <br> Name: <input name = "Name" type="text" value = '{{posts.nameEN}}'> <br> Address: <input name = "Address" type="text" value = '{{posts.addressEN}}'> <br> Grid Coordinates x: <input name = "Xcoord" type="text" value = {{posts.x}}> y: <input name = "Ycoord" type="text" value = {{posts.y}}> <br> <input type = "submit" value = "Add"> </form> in views.py def form_submission(request): name = request.POST["Name"] address = request.POST["Address"] x_coord = request.POST["Xcoord"] y_coord = request.POST["Ycoord"] location = Location(name=name,address=address,x_coord=x_coord,y_coord=y_coord) location.save() return redirect(#somewhere) in models.py (4 attributes, no foreign key) class Location(models.Model): name = models.CharField(max_length = 100) address = models.CharField(max_length = 200) x_coord = models.CharField(max_length = 10) y_coord = models.CharField(max_length = 10) #IntegerField() def __str__(self): return self.name I don't know what that "date_from" of the error message means. I have once added an attribute called … -
Django signals socket "Exception happened during processing of request"
I am implementing signals and error doesn't occur every time nor does it have specific time when it occurs or action error: Exception happened during processing of request from ('127.0.0.1', 56261) Traceback (most recent call last): File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Could it be due to py 3.8? # signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import CustomAuthUser @receiver(post_save, sender=CustomAuthUser) def my_handler(sender, created, **kwargs): if created: print('USER CREATED') # models.py from django.db import models from django.contrib.auth.models import AbstractUser from .managers import CustomAuthUserManager class CustomAuthUser(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomAuthUserManager() This is all logic -
django: problem with ajax request sent to ModelFormset template
I am trying to pass user data from one template inside of another template. For this I use an ajax request, as well explained here How do I integrate Ajax with Django applications? although no error shows up, nothing gets pulled. here is what my model formset view look like inside of template 1: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('id','Id', 'Date','Quantity', 'NetAmount', 'customer_name')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #blank_form = formset.empty_form if formset.is_valid(): request.session['sale'] = request.POST.get('sale') for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) return redirect('/invoice/pdf/assembly/') #else: #form = form(queryset= historical_recent_data.objects.none()) return render(request, 'new_sale.html', {'formset':formset}) and here is the view to access template 1 data into template 2: def generate_pdf_assembly(request): my_company = MyCompany.objects.get(id = 1) request = request.session.get('sale') context = {'request' : request, 'my_company' : my_company } print(context) and here is the ajax request to access the data from the template (in template 2): <h3> {{ context }} </h3> <script> $.ajax({ method: "GET", url: "/new_sale.html", sucess: function(context){ alert(context); }, failure: function(context){ alert('got an … -
Can I use single code base for web development and mobile applications?
I am searching for a technology, a framework or a library, etc. That can help me make: Website (not web app), Android and IOS app. (with a single code base) Kindly also clear : I learned Django. Can it help me ? Flutter is used for Android and IOS apps. If I learn flutter, will I need to write code for website separately ? -
UnboundLocalError at /Tag/HTC-Phones/ local variable 'tag' referenced before assignment - Django
I am getting the following error: UnboundLocalError at /Tag/HTC-Phones/ local variable 'tag' referenced before assignment /home/pc/Desktop/django_stuff/blog_project/blog_app/views.py in tag_detail, line 86 models.py : class Tag(models.Model): Tag_Name = models.CharField(max_length=100) slug = models.SlugField(unique=True,editable=True,max_length=200) def __str__(self): return self.Tag_Name def get_absolute_url(self): return reverse('tag_detail_url', kwargs={'slug':self.slug}) class Mobile(models.Model): name = models.CharField(max_length=100,default="") post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) tag = models.ManyToManyField('Tag',blank=True,related_name='posts') views.py : from .models import Tag def tag_detail(request,slug): tag = Tag.objects.filter(manytomanyfield=tag) return render(request,'website_primary_html_pages/tag_detail.html',context={'tag':tag}) the error in views in tag = Tag.objects.filter(manytomanyfield=tag) how to fix this problem , thanks -
How does the nested for loop prints data in django templates?
Well here i am trying to show the user followers and further their few followers and following but nested loop showing me weird behavior. I am not understanding how can i show exact information in template. when i am print the queryset in the terminal it showing me right information but it showing me wrong information on template. I have never worked with nested loop in templates before. so need help please. view.py : def get_context_data(self, *args, **kwargs): context = super(FollowerView,self).get_context_data(*args, **kwargs) user = context['user'] myfollowers = user.is_following.all() for target_list in myfollowers: user_obj = User.objects.get(username=target_list) followers_obj = user_obj.is_following.all() followerings_obj = user_obj.userprofile.follower.all() print(followers_obj,user_obj) #this return two query sets. which are given below context['myfollowers_data']= followers_obj context['myfollowerings_data']= followerings_obj return context output in terminal: Quit the server with CTRL-BREAK. <QuerySet [<UserProfile: admin>]> flash <QuerySet [<UserProfile: admin>, <UserProfile: flash>]> maddy this is right information. the problem is with template. follow template: {% for follower in user.is_following.all %} <div class="followers-body"> <img class="img-responsive img-circle" src="{{follower.avatar.url}}" alt=""> <div class="name-box"> <h4>{{follower}}</h4> <span>@{{follower}}</span> <div class="followers-base"> <ul class="list-group"> <li class="list-group-item full-width"> <div class="pull-left" style="margin-right: 20px;"> {% if myfollowers_data %} {% for user in myfollowers_data %} <img src="{{user.avatar.url}}" alt="" class="img-circle max-w-40 "> {% endfor %} {% endif %} <span> {{myfollowers_data.count}} Followers </span>#this … -
How to insert data in SQLite in Django
I am new to Django and I am following this website https://simpleisbetterthancomplex.com/tutorial/2018/02/03/how-to-use-restful-apis-with-django.html#passing-parameters-to-an-api-github-public-api views.py from django.shortcuts import render import requests def github(request): user = {} if 'username' in request.GET: username = request.GET['username'] url = 'https://api.github.com/users/%s' % username response = requests.get(url) user = response.json() return render(request, 'core/github.html', {'user': user}) core/github.html {% extends 'base.html' %} {% block content %} <h2>GitHub API</h2> <form method="get"> <input type="text" name="username"> <button type="submit">search on github</button> </form> {% if user %} <p><strong>{{ user.name }}</strong> has <strong>{{ user.public_repos }}</strong> public repositories.</p> {% endif %} {% endblock %} After passing parameters to an API and retrieve some location data, I would like to store the data to my SQLite in Django. I have created the model but I have no idea how to insert the data because I can't find examples under similar situations. And I am not sure where I should modify. Any hint or where I should look for? Many thanks. -
Add/remove elements from an array via Fetch
I have data in JSON format like this: [{"user": "shopaholic3000", "followers": ["Moderator", "poetry2"]}] I want to use a Fetch API to add and remove users from the followers array. My thoughts are that the PATCH request is the best choice for this. I came up with this: function followUser(username){ fetch(`/profile/${username}/followers`) .then(response => response.json()) .then(profile => { console.log('checkpoint1') let followBtn = document.querySelector('[name="follow-user"]') let currentUser = document.querySelector('#current-user').value if (followBtn.innerHTML = "Follow (+)"){ fetch(`/profile/${username}/followers`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ followers: followers.push(currentUser) }) }) .then(response => response.json()) .then(profile => { console.log('checkpoint2') }) } }) } This showed an error in console: ReferenceError: followers is not defined. views.py def follower(request, user_username): try: user_profile = Profile.objects.filter(user__username=user_username) except Profile.DoesNotExist: return JsonResponse({"error": "No profile found."}, status=404) if request.method == "GET": return JsonResponse([user.serialize() for user in user_profile], safe=False) elif request.method == "PATCH": data = json.loads(request.body) user_profile.followers = data["followers"] user_profile.save() return HttpResponse(status=204) else: return JsonResponse({ "error": "GET or PATCH request required." }, status=400) urls.py path("profile/<str:user_username>/followers", views.follower, name="followers") How can I go about this? -
Django TypeError: argument of type 'PosixPath' is not iterable
I am using the latest version of django django 2.2.12 I tried checking for errors before migration with the command python3 manage.py check but then it throws the error below Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3/dist-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/usr/lib/python3/dist-packages/django/db/utils.py", line 224, in close_all connection.close() File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/base.py", line 248, in close if not self.is_in_memory_db(): File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/usr/lib/python3/dist-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable -
Serializing a list of same class, but different "type" objects
Let's suppose I had a Test class in my django app and TestItem class. After that I have multiple child classes of TestItem, e.g. ChoiceTestItem (multi-table inheritance). Now it would be nice to return a list of the items in Test retrieve views, so I would like my serializer to output something like { "pk": 1, "name": "My example test", "items": [ { "pk": 1, "title": "How are you?", "type": "comment" }, { "pk": 2, "title": "How old are you?", "type": "choice", "choices": [ { ... }, { ... } } } ] } To acomplish that, I created a meta serializer, that returns another serializer depending on my items' item_typ property, like so: class TestItemBaseSerializer(serializers.ModelSerializer): class Meta: model = models.TestChallengeItem fields = [ 'pk', 'title' ] class ChoiceItemSerializer(TestItemBaseSerializer): class Meta(TestItemBaseSerializer): model = models.ChoiceItem # NOTE: Additional fields for this type of test item ! <--------------------- fields = TestItemBaseSerializer.Meta.fields + [ 'min_answers', 'max_answers', ] class TestItemSerializer(serializers.ModelSerializer): @classmethod def get_serializer(cls, model, item_type): item_type_serializers = { 'choice': ChoiceItemSerializer, ... } if item_type in item_type_serializers: return item_type_serializers[item_type] raise serializers.ValidationError(_("Unknown item type: " + item_type)) def to_representation(self, instance): serializer = self.get_serializer(instance.__class__, instance.item_type) return serializer(instance, context=self.context).data But it looks like I can't access ChoiceItem fields … -
I dont see Django profile update form in my templates
I am using Django. And the problems are with user profile update form, it seems like I have been doing everything right, but I cant see the update form in my generated HTML template. In form I see the submit button and because of that think that the problem is not from HTML file. And here are my files! HTML {% if not user.is_authenticated %} <script> window.onload = () => { window.location.href = "{% url 'main' %}"; } </script> {% else %} <h3>I am {{ user.username }}</h3> <img src="{{ user.profile.image.url }}" width="300"> {% endif %} <!-- User Update Forms --> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form|crispy }} {{ p_form|crispy }} <button type="submit">Update</button> </form> update form in forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() first_name = forms.CharField(min_length=5, max_length=30) def supervalid(self): expr_a = User.objects.filter(first_name=self.cleaned_data['first_name']).exists() expr_b = User.objects.filter(email=self.cleaned_data['email']).exists() if expr_b: raise ValidatioError(f'There already exists user with that email, use another one ;)') if expr_a: raise ValidatioError(f'This name is already used, sorry') class Meta: model = User fields = ['username', 'email', 'first_name'] def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = …