Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: PhoneNumberField Not getting Installed
I intalled Phonenumber package via pip and mentioned in my installed apps. As well as imported the same as mentioned in documentation to my models.py Even re-checked at the stack answers most of the people did the installation and imported file, but why mine is not working can anyone help pip install django-phonenumber-field[phonenumbers] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'rk003.apps.Rk003Config', ] models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Agent(models.Model): agency_name = models.CharField(max_length=200) prop_name = models.CharField(max_length=30) agency_address = models.CharField(max_length=300) agency_city = models.CharField(max_length=50) agency_country = models.CharField(max_length=50) email_address = models.EmailField(max_length=50) contact_nu = models.PhoneNumberField() Error is as follows File "/Users/rishipalsingh/Projects/notes/mdndjango/rk002/rk003/models.py", line 13, in Agent contact_nu = models.PhoneNumberField() AttributeError: module 'django.db.models' has no attribute 'PhoneNumberField' -
NAME CHOICE NOT DEFINED
def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(request.POST['Choice']) except (KeyError, choice.DoesNotExist): return render(request, 'mysite/detail.html',{ 'question':question, 'error_message':"you didn't select a choice", } ) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('mysite:results', args=(question.id,))) -
React and Django session problem that works on Postman but not in browser
I was wondering what I'm doing wrong. I am trying to implement the most simple session with React frontend and Django backend. I am aware that my methods are insecure and bad but its just a project for university and I need something that works so I should do other stuff that require sessions in my project. This is how my backend looks for Login and SessionInfo: @api_view(['POST']) def login(request): data = request.data try: user = MyUser.objects.get(username=data.get('username'), password=data.get('password')) request.session['uuid'] = user.id request.session.modified = True except MyUser.DoesNotExist: return HttpResponse("User does not exist.") return HttpResponse(request.session['uuid']) @api_view(['GET']) def getsession(request): if request.session.has_key('uuid'): return HttpResponse(request.session['uuid']) else: return HttpResponse(False) When I am trying to test this with Postman it always work and I get wanted session ID but when I'm trying to do same stuff with react using Axios post method it always return False. I have no clue why? This is how my post method looks in React: function login(){ axios.post('http://127.0.0.1:8000/evidencija/login/',{ username: 'admin', password: 'admin' }).then( (response) =>{ console.info(response.data) getSession() }, (error) =>{ console.log(error) } ) } -
Embedding an automatically generated Sphinx for python code into a html page
I have a website that I would like to display my Sphinx documentation on. So far i have built it so that I have a _build directory with "doctrees" and "html" as subfolders, the html subfolder containing the generated Sphinx documentation. I would like to embed this on my website so it looks as following: https://damask3.mpie.de/documentation/the-python-library/ This implementation was done by embedding it into an iframe. Is there a different way to do this, or is there an efficient way to create an iframe link for myself from the generated documentation files? -
How to import models.py from one app to another models.py in another app?
I am making an app that is similar to google classroom. I am coding this in repl.it, so i can't see the main application. I have two apps and mysite folder. One app is room and another is users I am trying to import a class from models.py that is in the room app to the models.py in the users app But when I do from room.models import Course, I get an error This is the screenshot for my whole directory, code and error. -
request.user returns AnonymousUser even when user is logged in
I would like to create a user when saving an object to the database but every time it says the user is AnonymousUser even though the user is logged in, below is a snippet, any help would be appreciated. def post(self, request): response = json.loads(self.request.body.decode('utf-8')) result_code = response["Body"]["stkCallback"]["ResultCode"] if result_code == 0: if response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Name"] == 'Balance': del response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2] amount = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][0]["Value"] mpesa_receipt_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][1]["Value"] transaction_date = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Value"] phone_number = response["Body"]["stkCallback"]["CallbackMetadata"]["Item"][3]["Value"] str_transaction_date = str(transaction_date) transaction_datetime = datetime.strptime( str_transaction_date, "%Y%m%d%H%M%S") aware_transaction_datetime = pytz.utc.localize( transaction_datetime) our_model = Mpesa.objects.create( Paid_user=request.user MpesaReceiptNumber=mpesa_receipt_number, PhoneNumber=phone_number, Amount=amount, TransactionDate=aware_transaction_datetime, ) our_model.save() -
Fetch all instances of model in batch and then query in Django
Is there any way to first fetch all or a filtered set of rows from a model and then query the results in Django? Pseudocode: queryset = MyModel.objects.all().fetch_all() inst_one = queryset.get(pk=1) # Sends query to database inst_two = queryset.get(pk=2) # Doesn't query database because everything has already been fetched -
How to impelment DjangoModelPermissions for the class based APIView ? It throws queryset exception. Queryset error
Scenario: I have group and permissions, permissions associated to group and that very group is associated to the user. Now I am trying to implement the permissions to the views through DjangoModelPermissions This works fine for the follwing code lines where queryset is implemented; class UpdateCampaignView(generics.UpdateAPIView): authentication_classes = [TokenAuthentication] permission_classes = [DjangoModelPermissions] queryset = Campaign.objects.all() serializer_class = UpdateCampaignSerializer def get_object(self): campaign_id = self.request.data.get("id") return Campaign.objects.get(id =campaign_id) But I want to implement this to class based APIView without queryset keyword something like this: class RetrieveCampaignView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [DjangoModelPermissions] #this is what i want to do def get(self, request, *args, **kwargs): try: campaign = Campaign.objects.get(id = request.data.get("id")) searializer = GetCampaignSerializer(campaign) return Response({"status":True , "payload":searializer.data}) except: return Response({"status":False}, status=status.HTTP_404_NOT_FOUND) But This Gives following Error: django rest framework error Cannot apply DjangoModelPermissions on a view that does not set .queryset or have a .get_queryset() method -
Django-Graphene: On a model ChoiceField, graphene expects a Type but got a value
On Django-Graphene, I have this model: class Entry(models.Model): STATE_CHOICES = [ ("Open", "Open"), ("Processing", "Processing"), ("Closed", "Closed"), ("Deleted", "Deleted"), ] # ... state = models.CharField(max_length=10, choices=STATE_CHOICES, default="Open") With the following Graphene schema: class EntryType(DjangoObjectType): class Meta: model = models.Entry class Query(graphene.ObjectType): entries = graphene.List(EntryType) def resolve_entries(self, info): return models.Entry.objects.all() But when I use the next query: query AllEntries{ entries{ id state } } I get this error: { "errors": [ { "message": "Expected a value of type \"EntryState\" but received: OPEN", "path": [ "entries", 1, "state" ] } ], } Can someone explain me what I'm doing wrong ? -
can we make an django app as rabbitmq consumer?
I have a django web application that displays messages stored in rabbitmq server Should we use a javascript consumer or add a consumer code to the views file? How to write consumer codes within the Dijango app? How can I make a consumer django app for rabbitmq ? Please Help. -
django channels does not work with more than 20-40 users in one channel
My system: django == 1.11.22, cchannels == 2.1.7, channels-redis == 2.2.1, daphne == 2.2.0, asgiref == 2.3.2 I tried using django pipes to include websockets in my project. The web socket subsystem simply sends system status to administrators and allows messages to be exchanged. My channel layer settings: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', # 'BACKEND': 'channels.layers.InMemoryChannelLayer', 'CONFIG': { "hosts": [(DJANGO_REDIS_HOST, DJANGO_REDIS_PORT)], "capacity": 100000, # default 100 "expiry": 5 # default 60 }, }, } I have increased the capacity of the channels to 100000 messages, but after 20-40 connections to the same URL "/ws/admins/" (this is one group "admins"), I start to get disconnects and duplicate messages, and django on the prod server will stop taking all connections until restarting docker containers. Decreasing expiry does not help either. if i use InMemoryChannelLayer then there are no errors. The server is started by the command: daphne -b 0.0.0.0 -p 8000 web_server.asgi: application -
Stripe API, How to get "subscription.status" from definition of ListView from django
I'm trying to configure Django Stripe Subscriptions for Database WebApp. I want to make sure only "paid user(subscribed user)" can search database. Therefore I need to check whether subscription.status is "active" Here is ListView of view.py from django.http import HttpResponse from.models import TestEu from django.views.generic import ListView import stripe from django.conf import settings from subscriptions.models import StripeCustomer #search class DbList(ListView): model = TestEu def get_queryset(self): stripe_customer = StripeCustomer.objects.get(user=request.user) stripe.api_key = settings.STRIPE_SECRET_KEY subscription = stripe.Subscription.retrieve(stripe_customer.stripeSubscriptionId) if subscription.status == "active": sql = 'select * from test_eu' msg = "abcdefg" sql += " where eng_discription ~ '.*" + msg +".*' ORDER BY image_amount DESC " object_list = TestEu.objects.raw(sql) return object_list When executing the above code, an error message occurs at the code below. stripe_customer = StripeCustomer.objects.get(user=request.user) NameError: name 'request' is not defined In this paticuler situation, how can I define "request" to fetch Subscription data? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
How to do a format check in Django models
I am trying to allow people to register their vehicles in my system and I want to provide a format check, which is very similar to the format LL-0000. Is it possible to get this done in the models.py or at least in the forms.py. This is my models.py just in case you needed it. class Vehicle (models.Model): model = models.ForeignKey(VehicleModel, on_delete=models.PROTECT) vehicle_colour = models.CharField(choices=COLOURS, max_length=10) vehicle_number = models.CharField(max_length=8) user = models.ForeignKey(User, on_delete=models.CASCADE) I needed the format check for the vehicle_number field. Any help is greatly appreciated. Thanks!! -
Enabled CORS White listing for Cross Origin Requests, Now I do not get CORS Error but my API Code gets Executed
I have enabled Cross Origin Requests by using the following approach: 1.Add corsheaders to INSTALLED_APPS INSTALLED_APPS = [ ... 'corsheaders', ... ] 2.Add CorsMiddleware to MIDDLEWARE LIST MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] 3.Define list of whitelisted Origins from which Request is allowed. CORS_ORIGIN_WHITELIST=['abc.com', 'xyz.com'] By enabling this Cross Origin Request I am not getting CORS Error in Browser for WhiteListed Origins but When I can access my APIs from Origin which mentioned in WhiteListed Origins, it gives me CORS Error in browser but My API Code gets executed means Django is calling my API before checking whether the request is from WhiteListed Origin or not. I want to Block such Cross Origin Request before my API get Called. How can we do it? Note: I have also tried Whitelisting using Signals, but I gets same Result as Whitelisting by CORS_ORIGIN_WHITELIST -
Linking Django with PysimpleGUI
I am really new to both of them. I have created a app with PysimpleGUI that gets the webcam input. So I need to link it to a website that uses Django, so that the webcam input is displayed on a webpage. What I need to know is whether it is possible to connect the two components together and/or are there any alternatives ? -
Python Django: Insert dynamic form records to db
It is a Medical Lab Software solution. A user makes lab investigation request that is unique to a patient’s encounter, I.e., a patient can have 1 or more request per encounter. This uniqueness is denoted by the encounter_id. The challenge now is the ability to send the results back to the requester. I am able to display all requests per encounter_id on a template but unable to return the result since each result is tied to a particular investigation. This is largely because I have a limited knowledge on JS. My current approach can only submit one record, usually the last record Here’s the URL that displays the result template: https://smart-care.herokuapp.com/labs/lab_results/1/ Here’s the django template: <div class="container"> <form id="myForm" method="POST" action="">{% csrf_token %} {% for request in lab_request %} {{ request.test }}: <input type="text" class="result" id="{{ request.test.id }}" name="test_id"> <br> {% endfor %} <br><br> <button>Send Result</button> </form> </div> Here’s my view: def lab_results_view(request, enc_id): lab_request = LabRequest.objects.filter(encounter_id=enc_id, done=False, decline=False) # Get values from tempalte if request.POST.get('test_id'): entered_result = LabRequest() entered_result.result = request.POST.get('test_id') new_result = entered_result.result print("Just = ",new_result) template = "labs/lab_results.html" context = {"lab_request":lab_request} return render(request, template, context) The models: class LabRequest(models.Model): encounter = models.ForeignKey(PatientEncounter, on_delete=models.CASCADE, blank=True, null=True) patient = … -
Why Django admin search field taking too much time to response?
It's my first time to handle project with large data. I have 16millions of data. When i query in django shell it give me result in few seconds. But on django admin site when i register my model and apply search field . It takes too much time to query. I tried django debug toolbar and here is the result it's showing me Django debug toolbar result models.py: class TrademarkAvailability(models.Model): serial_number = models.IntegerField(unique=True) filing_date = models.IntegerField(null=True) status_code = models.IntegerField(null=True) status_date = models.IntegerField(null=True) mark_identification = models.CharField( max_length=5000, null=True, blank=True, db_index=True) mark_drawing_code = models.CharField( max_length=5000, null=True, blank=True) attorney_name = models.CharField(max_length=5000, null=True, blank=True) current_location = models.CharField(max_length=5000, null=True, blank=True) employee_name = models.CharField(max_length=5000, null=True, blank=True) correspondent = models.JSONField() classifications = models.JSONField(null=True) case_file_owners = models.JSONField(null=True) transaction_date = models.JSONField(null=True) registration_number = models.JSONField(null=True) case_file_statements = models.JSONField(null=True) case_file_event_statements = models.JSONField(null=True) admin.py @admin.register(TrademarkAvailability) class TrademarkAdmin(admin.ModelAdmin): list_display = ("mark_identification",) search_fields = ["=mark_identification"] paginator = LargeTablePaginator show_full_result_count = False -
Django and keyclok AUTHENTICATION BACKEND error
In my djando application i create my own middleware for authentication using keycloak, I create my class as: class KeycloakMiddleware(MiddlewareMixin): def __init__(self, get_response): """ :param get_response: """ self.keycloak_authorization_config = settings.KEYCLOAK_CONFIG.get('KEYCLOAK_AUTHORIZATION_CONFIG', None) self.default_access = settings.KEYCLOAK_CONFIG.get('KEYCLOAK_DEFAULT_ACCESS', "DENY") self.method_validate_token = settings.KEYCLOAK_CONFIG.get('KEYCLOAK_METHOD_VALIDATE_TOKEN', "INTROSPECT") # Create Keycloak instance self.keycloak = KeycloakService.connect_authentication_client() # Read policies if self.keycloak_authorization_config: self.keycloak.load_authorization_config(self.keycloak_authorization_config) # Django self.get_response = get_response .... and in my django settings.py i do: MIDDLEWARE = [ ... 'myapp_backend.utils.keycloak_middleware.KeycloakMiddleware', ... and AUTHENTICATION_BACKENDS = ( 'myapp_backend.utils.keycloak_middleware.KeycloakMiddleware', ) but when i run my /admin app i get: TypeError at /admin/login/ init() missing 1 required positional argument: 'get_response' If i try to leave AUTHENTICATION_BACKEND params blank i get an error because no AUTHENTICATION_BACKEND was defined. How can i pass the get_response argument from my django settings to my middleware for authentication? So many thanks in advance Manuel -
Django query looping
I have been trying to work out a more efficient way of doing below. Does one exist? The issue is i have to do this loop 100 times (in my test case but more in real life), and there are about 100 items in each loop, which makes it really quite slow. There must be a way to compare query results something like array.filter in JS. But i cant seem to find it for Django. for choice in question.answer_choices.all(): amount = 0 for ans in q_answers: if choice in ans.answers.all(): amount += 1 It is basically getting the choice of answers and counting how many match to give me a result for each choice from a set of answer choices. q_answers is just an array of answers that were given by user for 'question'. -
adding image in pdf using Django pisa: standard {% static 'path/to/image' %} do not working
I try to implement pdf output using pisa following this tutorial: https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ and it works except for images that are not displayed I understand the problem deal with relative/absolute path between pisa and Django system but do not manage to resolve. I read the solution in the xhtml2pdf document using link_callback method but it dosen work and have no error If I pass the absolute url of images in context to my html template it works : <img class="logo" src="{{ url }}" alt="logo alima"> -
Django 3, model textField returns byte string while saved a string
I have updated my Django version from Django 2.1.4 to Django 3.2.3 Now I am facing a weird behavior of my apps. I am saving string data in my textFiled of the model, but when I retrieve data from model it returns byte string which is not serializable in JSON. I have verified saved data in DB is string type. For now, I have overridden Django model method from_db and checking the data type and changing it. But I think this is not a good solution. using AWS MySQL aurora db, Django 3.2.3 and python 3.6 Your suggestions will be appreciated. -
Django 3 run server error ImproparlyConfigured on django 3
I installed the newest version of Django and when I did the runserver command it showed a really long error. I searched the internet for it but most of the sollutions I found were either not working or outdated. The error: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS _MODULE or call settings.configure() before accessing settings. Please help me as I have been stuck on this for a really long time. Thanks -
How can I group two same products to show them as one in django?
*Now as u see in the database table. In this table, we have two oranges but have different prices because pack size. From this table, I want to get data in this way that on my project product view list oranges shows only once and if we go to the product detail we have a combo box where we can display the different size of pack from the table like oranges. Oranges should we shown once from this table to the product list by grouping them and after going to oranges details we can see both the oranges packaging in a combo box. * -
hamburger icon not opening
my hamburger icon is currently not opening, i figure that is a problem with my javascript, any other tips and tricks when coming to javascript are very much welcome, i am a beginner so your assistance would be very much appreciated java.js $('.open-overlay').click(function() { var overlay_navigation = $('.overlay-navigation'), nav_item_1 = $('nav li:nth-of-type(1)'), nav_item_2 = $('nav li:nth-of-type(2)'), nav_item_3 = $('nav li:nth-of-type(3)'), nav_item_4 = $('nav li:nth-of-type(4)'), nav_item_5 = $('nav li:nth-of-type(5)'), top_bar = $('.bar-top'), middle_bar = $('.bar-middle'), bottom_bar = $('.bar-bottom'); overlay_navigation.toggleClass('overlay-active'); if (overlay_navigation.hasClass('overlay-active')) { top_bar.removeClass('animate-out-top-bar').addClass('animate-top-bar'); middle_bar.removeClass('animate-out-middle-bar').addClass('animate-middle-bar'); bottom_bar.removeClass('animate-out-bottom-bar').addClass('animate-bottom-bar'); overlay_navigation.removeClass('overlay-slide-up').addClass('overlay-slide-down') nav_item_1.removeClass('slide-in-nav-item-reverse').addClass('slide-in-nav-item'); nav_item_2.removeClass('slide-in-nav-item-delay-1-reverse').addClass('slide-in-nav-item-delay-1'); nav_item_3.removeClass('slide-in-nav-item-delay-2-reverse').addClass('slide-in-nav-item-delay-2'); nav_item_4.removeClass('slide-in-nav-item-delay-3-reverse').addClass('slide-in-nav-item-delay-3'); nav_item_5.removeClass('slide-in-nav-item-delay-4-reverse').addClass('slide-in-nav-item-delay-4'); } else { top_bar.removeClass('animate-top-bar').addClass('animate-out-top-bar'); middle_bar.removeClass('animate-middle-bar').addClass('animate-out-middle-bar'); bottom_bar.removeClass('animate-bottom-bar').addClass('animate-out-bottom-bar'); overlay_navigation.removeClass('overlay-slide-down').addClass('overlay-slide-up') nav_item_1.removeClass('slide-in-nav-item').addClass('slide-in-nav-item-reverse'); nav_item_2.removeClass('slide-in-nav-item-delay-1').addClass('slide-in-nav-item-delay-1-reverse'); nav_item_3.removeClass('slide-in-nav-item-delay-2').addClass('slide-in-nav-item-delay-2-reverse'); nav_item_4.removeClass('slide-in-nav-item-delay-3').addClass('slide-in-nav-item-delay-3-reverse'); nav_item_5.removeClass('slide-in-nav-item-delay-4').addClass('slide-in-nav-item-delay-4-reverse'); } }) my html <div class="overlay-navigation"> <nav role="navigation"> <ul> <li><a href="#" data-content="The beginning">Home</a></li> <li><a href="#" data-content="Curious?">About</a></li> <li><a href="#" data-content="I got game">Skills</a></li> <li><a href="#" data-content="Only the finest">Works</a></li> <li><a href="#" data-content="Don't hesitate">Contact</a></li> </ul> </nav> <section class="home"> <div class="open-overlay"> <span class="bar-top"></span> <span class="bar-middle"></span> <span class="bar-bottom"></span> </div> </section> -
i wanted to send a json response through url so that i can retrieve it from url in android app and display it in list but my code produces wrong json
this is how i got when i try to print it [{"model": "api.product", "pk": 1, "fields": {"productname": "keyboard", "productdesc": "keyboard is made by sony", "amount": 200.0, "available": 20, "image": "pics/Send.png"}}] but i wanted it in a correct way so that i can retrieve it form the application my django views.py: from django.http import HttpResponse from django.core import serializers as core_serializers from rest_framework import serializers from .models import users,product from django.views.decorators.csrf import csrf_exempt @csrf_exempt def viewproduct(self): obj=core_serializers.serialize('json',product.objects.all()) return HttpResponse(obj,content_type='application/json') models.py from django.db import models class users(models.Model): username=models.CharField(max_length=100) password= models.TextField() email=models.EmailField() class product(models.Model): productid=models.AutoField(primary_key=True) productname=models.CharField(max_length=255) productdesc=models.CharField(max_length=255) amount=models.FloatField(max_length=25) available=models.IntegerField() image=models.ImageField(upload_to='pics')