Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't import six.moves module
import json from six.moves.urllib_parse import urlencode from six.moves.urllib_request import urlopen from django.core.management.base import CommandError def call(method, data, post=False): """ Calls `method` from the DISQUS API with data either in POST or GET. Returns deserialized JSON response. """ url = "%s%s" % ("http://disqus.com/api/", method) if post: # POST request url += "/" data = urlencode(data) else: # GET request url += "?%s" % urlencode(data) data = "" res = json.load(urlopen(url, data)) if not res["succeeded"]: raise CommandError( "'%s' failed: %s\nData: %s" % (method, res["code"], data) ) return res["message"] module) moves Import "six.moves.urllib_parse" could not be resolved from sourcePylancereportMissingModuleSource installed the six module to Python virtual environment six can be imported without problems Occurs from six.moves MissingModuleSource Why can't Import? six.moves -
Spyne, Django change WSDL url
I am using django behind nginx reverse proxy and django sees the server url different than what it actually is hosted on like: Django: http://webserver.com Nginx: https://webserver.com When I try to add the WSDL to SoapUI it automatically defaults to the first http://webserver.com server and then all the requests fail. I have tried the code below, but it did not work: ... app = Application( [EXTWS], tns='soap.views', in_protocol=Soap11(validator='soft'), out_protocol=Soap11(), ) app.transport = "no_transport_at_all" ... wsdl = Wsdl11(app.interface) if os.environ.get("DEBUG"): wsdl.build_interface_document('http://localhost:8000/wsdl/') else: url = f'https://{settings.DOMAIN}/wsdl/' wsdl.build_interface_document(url) Inspirations: here and here -
django user's session key has been changed to another user's session key sometimes
base.py AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] middleware.py class CountVisitorMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) ... return response There are currently social login users and general users. Would using the runserver(not gunicorn or uwsgi) in production be a problem? response = self.get_response(request) <-- Could it be a thread safety issue? Is there anything else i need to check? -
How to overcome Django urlize() method including leading text+. in the url, e.g. x.http://example.com
I am getting an unwanted result from django's urlize method when there is a leading number and period (as might be typed in a numbered list without the expected space) This output surprises me: In [4]: urlize("1.www.test.com") Out[4]: '<a href="http://1.www.test.com">1.www.test.com</a>' It doesn't seem like the parser should include anything before the www prefix unless it's a scheme, but... In [6]: urlize("1.http://test.com") Out[6]: '<a href="http://1.http://test.com">1.http://test.com</a>' What can I do to prevent this? Either by pre-parsing the input or post-parsing afterwards? or is there a better method out there? In [2]: from django.utils.html import urlize In [3]: urlize("www.test.com") Out[3]: '<a href="http://www.test.com">www.test.com</a>' In [4]: urlize("1.www.test.com") Out[4]: '<a href="http://1.www.test.com">1.www.test.com</a>' In [5]: urlize("1.test.com") Out[5]: '<a href="http://1.test.com">1.test.com</a>' In [6]: urlize("1.http://test.com") Out[6]: '<a href="http://1.http://test.com">1.http://test.com</a>' In [7]: urlize("a.http://test.com") Out[7]: '<a href="http://a.http://test.com">a.http://test.com</a>' -
Django framework: unable to load 'services' page
I'm working on a Django project. I think there is some problem with the use of 'services' word in the django project. Please see if you can find some corrections required in the project. The project name is Hello. There is one additional app 'home'. When I navigate to the index, contact, or about page, all of them are working (loading) as expected. But services page is not loading. If I change 'services' to 'service' everywhere, then it works as usual. It's giving the following error: Following are some of the file contents: Hello->urls.py from django.contrib import admin from django.urls import path, include admin.site.site_header = "Harry Ice Cream Admin" admin.site.site_title = "Harry Ice Cream Admin Portal" admin.site.index_title = "Welcome to Harry Ice Creams!" urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ] home->urls.py from django.contrib import admin from django.urls import path from home import views urlpatterns = [ path('', views.index, name='home'), path('about', views.about, name='about'), path('services', views.services, name='services'), path('contact', views.contact, name='contact'), ] home->views.py from django.shortcuts import render, HttpResponse # Create your views here. def index(request): context = { } return render(request, 'index.html',context) #return HttpResponse("This is homepage") def about(request): context = { } return render(request, 'about.html',context) def services(request): context = { } return … -
Django - Retrive user information with JWT token
MY FUNCTION ONLY SHOWS ACCESS TOKEN API when I hit (user-info)API/login link. I want to show API tokens with user information. http://127.0.0.1:8000/api/login/ link show API with user information # Import libraries from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView from base.api.serializers import UserSerializer from base.models import User from rest_framework.permissions import IsAuthenticated, AllowAny class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['username'] = user.username return token # Token Access class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer # Registration class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) # User information class LoginView(APIView): permission_classes = [IsAuthenticated] def get(self, request): user_id = request.user.id user = User.objects.get(id=user_id) serializer = UserSerializer(user) return Response(serializer.data) API Token Access -
How to easily debug Redis and Django/Gunicorn when developing using Docker?
I'm not referring to more sophisticated debugging techniques, but how to get access to the same kind of error messages that are normally directed to terminal tabs? Basically I'm adopting Docker in a Django project also using Redis. In the old way of working I opened a linux terminal tab for gunicorn like this: gunicorn --reload --bind 0.0.0.0:8001 myapp.wsgi:application And this tab kept running Gunicorn and any Python error was shown in this tab so I could see the problem and fix it. I could also open a second tab for the celery woker: celery -A myapp worker --pool=solo -l info The same thing happened, the tab was occupied by Celery and any Python error in a task was shown in the tab and I could see the problem and correct the code. My question is: Using docker is there a way to make each of the containers direct these same errors that would previously go to the screen, to go to log files so that I can debug my code when an error occurs in Python? What is the correct way to handle simple debugging during development using Docker containers? -
DJANGO : How to print the value from a class in the prefetch_related class, which calls another class as a Foreign key?
I am very new to Django and tried various answered questions on this forum. But I could not display the TITLE of the Product. I want to display the TITLE for my product from the DB. From models.py : class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Order(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] placed_at = models.DateTimeField(auto_now_add=True) payment_status = models.CharField( max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING) customer = models.ForeignKey(Customer, on_delete=models.PROTECT) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT) product = models.ForeignKey(Product, on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) From views.py : order = Order.objects.select_related('customer').prefetch_related('orderitem_set__product').order_by('-placed_at')[:5] From hello.html : {% for prod in order %} <li>Order ID : {{ prod.id }} -- Customer {{ prod.customer.first_name }} -- Product {{ prod.orderitem_set.product.title }}</li> I have 2 questions here: In hello.html : How do I display the Product Title? In the views.py : How do I load and display the promotions from the product class in same call? Expected output : Order ID : 408 -- Customer Olin -- Product -- Cheese -- Promotion : … -
Updating a field within another Model's save method with F()
I'm attempting to create a voting system where the score of a given post is separate from the type of votes placed by users. In the event that a user deletes a profile, a given score should not increment/decrement due to their vote being deleted. Therefore scores are only updated by using an F('score') + 1 or F('score') - 1 expression. Within Vote.save(), I'm trying to implement this, yet the Question.score field doesn't update when the Vote is created. How can I get the test to pass where the score in the question goes from 0 to 1? class TestQuestionScoreUpVote(TestCase): '''Verify that a Question's score increments by one point when the Vote is an "up" vote.''' @classmethod def setUpTestData(cls): tag1 = Tag.objects.create(name="Tag1") user = get_user_model().objects.create_user("TestUser") profile = Profile.objects.create(user=user) cls.question = Question.objects.create( title="Question__001", body="Content of Question 001", profile=profile ) cls.question.tags.add(tag1) user_vote = Vote.objects.create( profile=profile, type="upvote", content_object=cls.question ) def test_new_user_vote_on_question(self): self.assertEqual(self.question.score, 1) class Post(Model): body = TextField() date = DateField(default=date.today) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) vote = GenericRelation( 'Vote', related_query_name="%(class)s" ) score = IntegerField(default=0) class Meta: abstract = True class Question(Post): title = CharField(max_length=75) tags = ManyToManyField( 'Tag', related_name="questions", related_query_name="question" ) views = … -
Attribute error 'int' object has no attribute 'items'
Attribute error 'int' object has no attribute 'items' her my Modelserializer def validate(self, validated_data): gameevent = validated_data.get('gameevent') match_round =validated_data.get('match_round') if not match_round : raise serializers.ValidationError("Enter value more than 0 ") if match_round == 1: return match_round round = range(1,match_round) match = Matchscore.objects.filter(gameevent=gameevent,match_round__in=round).values_list('match_round',flat=True) match = set(match) if match : return validated_data else: raise serializers.ValidationError("Enter a valid match_round") -
How do I return multiple and single record using one view Django
So, I am trying to use one view to give multiple and a single record. Is it possible? So in urls.py I have defined path as path('main/actor/<int:pk>', views.getMainActor) In my views file @api_view(['GET']) def getMainActor(request, pk=None): if pk is None: actor = ActorModel.objects.all() serializer = ActorSerializer(actor, many=True) else: actor_single = CheeringCharacter.objects.get(id=pk) serializer = ActorSerializer(actor_single) return Response(serializer.data) The error I am getting is admin/ main/actor/<int:pk> The current path, main/actor/, didn’t match any of these. -
How do I manage Django migrations when commiting changes from local development to remote?
During Django development, I have to create many migrations to get to what I'm looking for. For example, I might change the name of a field and later decide to set it back to what it was. So a lot of my migrations are just toying with the ORM. I assume I don't need them all to show up in the remote repo (which might be a wrong assumption!). I know excluding the migrations via .gitignore is not the right way. Also can't include random ones in commits as they are all linked to one another. So far, I squash my migrations each time I made changes: squashmigrations app_label [start_migration_name] migration_name and then commit. What would be a better solution? -
Python Django load data from text document
I am using python and django to make a website that should be able to load data from a text document and display it. Until now I have converted the data from txt format to html and loaded it to a div like so : <div id='data'> {% include "data.html" %} </div> Unfortunately when I hit refresh after I have modified data.html there is no update. I would like to be able to load the html file on every refresh -
Django-redis for caching time working properly in my PC as Memurai installed but after deploying on heroku error showing 500 in a specific page
I am building a E-commerce website for a client applying OTP verification fir registration for that I have used Django-redis for caching time for OTP expiring also installed Memurai after making debug=false it is working properly but after deploying it on Heroku error showing 500 in page where OTP generate -
How to view data in Django pass to external js
I've been using an id to get all data from external js but the question is I want to display data from the database, but using the template is on external js, I just call an 'id' from external js to my HTML, is somebody know how to read {for data} under external js? views.py def dashboard(request): tasks = task.objects.all() tasks = {'requestsdata':tasks} return render(request, 'dashboard.html',tasks) dashboard.html - I've been using id to fetch all data inside external js <div class="card-body"> <div id="demo2"></div> </div> custom.js External js {% for listofdata in requestsdata%} var kanban2 = new jKanban({ element: '#demo2', gutter: '15px', click: function (el) { alert(el.innerHTML); }, boards: [{ 'id': '_todo', 'title': 'To Do (Item only in Working)', 'class': 'bg-info', 'dragTo': ['_working'], 'item': [{ 'title': ` <a class="kanban-box" href="#"><span class="date">24/7/20</span><span class="badge badge-info f-right">medium</span> <h6>{{listofdata .description}}</h6> //etc. so on ......... `, } ] }, ] }); {% endfor %} -
Valid JSON in Django admin
can you help me figure out what kind of valid data I would need to enter in the Django admin for a schema defined as follow?: REQUIREMENTS_SCHEMA = { "type": "array", "items": { "type": "object", "properties": { "chain": {"type": "string", "enum": BLOCKCHAINS_ENUM}, "asset_type": {"type": "string", "enum": ASSET_TYPES_ENUM}, "asset_address": {"type": "string", "pattern": "^(0x|0X).*$"}, "amount": {"type": "integer", "minimum": 1}, "token_id": {"type": "array", "items": {"type": "integer"}, "minItems": 0}, }, "required": ["chain", "asset_type", "asset_address", "amount"], }, } I tried this [{"type": ["f"], "items": {"type": "x", "properties": {"chain": "ETHEREUM", "asset_type": "ERC20", "asset_address": "0x711Dfd645411B741E6FE3aeaA37d504C0e44B0F9", "amount": 2, "token_id": 2}}}] But im am getting an error -
Django AssertionError No api proxy found for service "memcache"
I'm running a Django app on GAE and I want to use memcache in my views.py to store some data for caching. I have not setup anything for caching in my settings.py and immediately use from google.appengine.api import memcache inside of views.py and pulls/insert data using the .add() and .get() method. This however, results in an AssertionError at / : No api proxy found for service "memcache" What am i missing here? Should I be setting up something inside of settings.py? From my understanding memcache is a built-in feature of GAE and I figured it worked the same way as an API key where we would not need to specify them inside of the settings.py Plus the documentation also does not provide any information on proxy setup or whatsoever. -
How to achieve dynamic filter in django
In my frontend, I have three kinds of filter and when user selects selects those and click on filter then I need to update the results. The problem is user may select any one or two or all the three filters combinedly. But my code just filters only one condition: Here is my code: filter1 = request.POST.getlist("filter1") //Every filters are in arrays filter2 = request.POST.getlist("filter2") //Every filters are in arrays filter3 = request.POST.getlist("filter3") //Every filters are in arrays data = Data.objects.filter(is_approved=True, published=True) //This the model to be filtered if len(filter1) > 0: data = data.filter(intakes__contains=filter1) if len(filter2) > 0: data = data.filter(elevel__contains=filter2) if len(filter3) > 0: data = data.filter(country__in=filter3) How to make this dynamic ? Like it should filter based on more than one selections. Please help -
What do i need to know to develop python AI chat bot?
I am currently developing a social media website with a lot of privacy settings and processes, which may require the users utilizing the application to need guidance through them smoothly and clearly, and I have been wondering to make an AI chat bot to serve as an assistant to the users, This website is made by Python Django MVC framework, What I am looking for is a python library that is executed like NumPy with C++, Fast performance Python AI library. I would how to create an AI chatbot?. Thanks in advance. -
ModuleNotFoundError: No module named 'whitenoise.django'
I'm getting this error (no module named 'whitenoise.django'), even though I ran pip install whitenoise on my project's folder. When I do that, it shows that the requirement is already satisfied. The code where the error appears is in my wsgi.py file. More specifically in this line: from whitenoise.django import DjangoWhiteNoise How do I install it properly? -
Best way to create a custom view and serializer output grouping the results based on a foreying key filter
I am doing some work around the Django rest framework to get an custom output that matches with the charts that i am using. But i am trying to figure out how can i group the serializer by the categories, that are a foreying key field. I don`t know if that would be nice to use filters in the get_query, or if there is a better solution, as there are many categories. Thats what i have made so far: my models: class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) class Asset(models.Model): category = models.ForeignKey(Category, related_name='categories', on_delete=models.CASCADE) ticker = models.CharField(max_length=255, unique=True) class PortfolioAsset(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) total_today_brl = models.FloatField() Here is the serializer: class PortfolioAssetSerializer(serializers.ModelSerializer): category = serializers.CharField(source='asset.category.name') x = serializers.CharField(source='ticker') y = serializers.FloatField(source='total_cost_brl') class Meta: model = models.PortfolioAsset fields = ( 'category', 'x', 'y', ) And here the view: class PortfolioAssetList(generics.ListAPIView): serializer_class = serializers.PortfolioAssetSerializer def get_queryset(self): return models.PortfolioAsset.objects.all() # return models.PortfolioAsset.objects.filter(asset__category__name="Fundos Imobiliários") def list(self, request, *args, **kwargs): response = super(PortfolioAssetList, self).list(request, *args, **kwargs) response.data = { "name": "category", "data": response.data } return response The output thath i could get with that code was that one: { "name": "category", "data": [ { "category": "category 1", "x": "ASSET1", "y": 10373.4 … -
How to duplicate Django models with OneToOneField relations
Start with the following models using django==3.2.12: from django.db import models class Root(models.Model): pass class Leaf(models.Model): root = models.OneToOneField(Root, related_name='leaf_data', on_delete=models.CASCADE) Run the following in the shell: >>> from myapp.models import Root, Leaf >>> root = Root() >>> root.save() >>> leaf = Leaf(root=root) >>> leaf.save() >>> root <Root: Root object (1)> >>> leaf <Leaf: Leaf object (1)> >>> new_root = Root() >>> new_root.save() >>> new_root <Root: Root object (2)> >>> root.leaf_data <Leaf: Leaf object (1)> >>> leaf = root.leaf_data >>> leaf.pk = None >>> leaf.root = new_root >>> leaf.save() >>> leaf.root <Root: Root object (2)> >>> root.leaf_data <Leaf: Leaf object (2)> Why does the original root.leaf_data reference change? I would expect that by setting leaf.pk = None and leaf.root = new_root that the original root/leaf structure would remain intact. I'm trying to create a full duplicate from the original. -
Python/Docker ImportError: Couldn't import Django but it's installed
I am trying to run a microservices program through my manager.py file that uses docker, but when I run the program using docker-compose up I get an ImportError that tells me that Django is not installed even though it is. I have tried to use the venv library to create and install Django using my virtual environment vegatestnet, have also tried to change my Windows path variable to point to the project, and finally, I have tried to even use import sys print(sys.path) to find where my PYTHON_PATH is but no dice. I have also tried to use these links to help me: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?, ModuleNotFoundError: No module named 'django' while running server in virtual environment, and Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? --> WSGI.PY file and I have tried their solutions but I still get this error. Here is the directory structure that I am working with: -veganettest ... -posts (folder) -profiles (folder) ... producer.py (my producer file) -static_cdn (folder) -static_project (folder) ... -veganettest (folder) -vegatestnet (virtual envoirment folder) admin (my admin file) consumer.py (my consumer … -
the problem is still return object not title and how to add in reference models
class Interest(models.Model): title = models.CharField(max_length=200) def _str_(self): return self.title I have trying use str to return the title but unfortunately it return back object 1 -
Apply Bulma css to Django drop down menu
How do I apply css from bulma to my Django field which is a drop down menu using widget=forms.Select. Bulma CSS: from the bulma.io site, their example implementation: <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Dropdown button</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> <a href="#" class="dropdown-item"> Dropdown item </a> <a class="dropdown-item"> Other dropdown item </a> <a href="#" class="dropdown-item is-active"> Active dropdown item </a> <a href="#" class="dropdown-item"> Other dropdown item </a> <hr class="dropdown-divider"> <a href="#" class="dropdown-item"> With a divider </a> </div> </div> </div> This is what I tried: forms.py: class PostModelForm(forms.ModelForm): STATUS=[ ('live', 'Live'), ('draft', 'Draft'), ] status = forms.CharField(label='Status', widget=forms.Select(choices=STATUS)) class Meta: model = Post fields = ( 'status', ) def __init__(self, *args, **kwargs): super(PostModelForm, self).__init__(*args, **kwargs) self.fields['status'].widget.attrs.update({'class': 'dropdown-menu','id': 'dropdown-menu', 'role': 'menu'}) models.py class Post(models.Model): status = models.CharField(default='draft', max_length=10) post.html <form method="post"> {{ form.status.errors }} <p class="title">Status</p> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup="true" aria-controls="dropdown-menu"> <span>Select status</span> <span class="icon is-small"> <i class="fas fa-angle-down" aria-hidden="true"></i> </span> </button> </div> {{ form.status }} </div> {% csrf_token %} <div class="control"> <button type="submit" class="button">Submit</button> </div> </form> Further info I kept the form short for the question, but I have successfully implemented other …