Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django returns MultiValueDictKeyError at / 'q'
django returns MultiValueDictKeyError at / 'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself. MultiValueDictKeyError at / 'q' def dashboard(request): photos = Photo.objects.all() query = request.GET['q'] card_list = Photo.objects.filter(category__contains=query) context = {'photos': photos, 'card_list':card_list} return render(request, 'dashboard.html', context) <div class="container"> <div class="row justify-content-center"> <form action="" method="GET"> <input type="text" name="q" class="form-control"> <br> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <br> <div class="container"> <div class="row justify-content-center"> {% for photo in photos reversed %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 style="color: yellowgreen; font-family: Arial, Helvetica, sans-serif;"> {{photo.user.username.upper}} </h2> <br> <h3>{{photo.category}}</h3> <h4>{{photo.price}}</h4> </div> <a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn- sm m-1">Buy Now</a> </div> </div> {% empty %} <h3>No Files...</h3> {% endfor %} </div> </div> -
How can I Generate 10 Unique digits in Model Form and Pass Form Context Variable in Django Class Based ListView
I am new to Django Class Based Views and I am working on a project where on the template I want to have Form for creating customer accounts on the left and list of existing customers on the right. So far I have the list of existing customers displayed but for the form I don't know how to pass its variable context to the same template, or it is not possible to Pass a Form that would be submitted inside a ListView Method. And I also want to generate unique account numbers of 10 Digits in ModelForm which I want the form field to be auto-filled and disabled Here is my form code: import secrets #I want to Generate Account Number of 10 Digits but getting only 2 account = secrets.randbits(7) #class for Customer Account Form class CustomerAccountForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().init(*args, **kwargs) self.fields['accountnumber'].initial = account class Meta: model = Customer fields = ['accountnumber','surname','othernames','address','phone'] Code for my views (ListView) class CustomerListView(ListView): model = Customer form_class = CustomerAccountForm template_name = 'dashboard/customers.html' #Function to get context data from queries def get_context_data(self, **kwargs): context_data = super().get_context_data(**kwargs) #Get Day of today from current date and time now = datetime.datetime.now() #Get the date today … -
Django backend on aws lambda : what is considered a request?
Im considering setting up a django backend on aws lambda and i need to calculate the costs based on the number of requests and duration of these requests. How can I calculate the number of requests in django (ie what is considered in django as an aws lambda request)? Is a page requested equivalent to a request in aws lambda? Or is a database access equivalent to one request ? How can I compute the average duration of a request? THank you -
when I print @property value it return this <property object at 0xffff906b2048>
I am working on Django serve, my question is How I can print a actual value of this file modles.bookings.py @property def grand_total_amount_display(self) -> str: return format_currency_amount(self.grand_total_amount, self.currency) grand_total_amount_display.fget.short_description = 'Grand Total' util.spaces file def get_booking(): from sook_booking.models.bookings import Booking # circulation-import issue print('Booking.grand_total_amount',Booking.grand_total_amount_display) return str(Booking.grand_total_amount_display) and i am getting this value when I print Booking.grand_total_amount <property object at 0xffff906b2048> -
What type of problem am I having with logging on the website via Facebook?
I'm trying to implement a login on the site via Facebook using allauth. That's logs: 31.13.103.10 - - [11/May/2022:11:11:27 +0000] "GET /accounts/facebook/login/callback/ HTTP/1.1" 200 273 "-" "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)" "31.13.103.10" response-time=0.026 178.88.74.128 - - [11/May/2022:11:12:00 +0000] "GET / HTTP/1.1" 200 183 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36" "178.88.74.128" response-time=0.007 178.88.74.128 - - [11/May/2022:11:12:03 +0000] "GET /accounts/facebook/login/?process= HTTP/1.1" 200 408 "https://konstantin07.pythonanywhere.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36" "178.88.74.128" response-time=0.026 178.88.74.128 - - [11/May/2022:11:12:06 +0000] "POST /accounts/facebook/login/?process= HTTP/1.1" 302 0 "https://konstantin07.pythonanywhere.com/accounts/facebook/login/?process=" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36" "178.88.74.128" response-time=0.036 Everything is ok: 200-200-200-302 But Facebook says that something went wrong: Sorry, something went wrong. We're working on getting this fixed as soon as we can. Go Back How can I find out what was wrong? -
VISUALISATION OF DATA USING DJANGO /POSTGRESQL
i need to create a django app for data visualization , with Database on postgresql I need to obtain a graph (line) for values of 2 columns table_name: "sample" column1 " sampleID" : 4322,45346,765754 column2 " absorbance" : 3232;34325;6547634;346547;342;56546;2434;546458;34354236;566345735, 362482;25346;68465;56347;357548;768746;6574563;436467;9785676321;87834, 986853;285797;5436346;43634567;7547548;345345;4367548;3565634,6347536 We can see that for each sampleID , each value of absorbance it is a succession of differente values Each of this values will be a point in my axe of the graph and i will obtain 3 lines because 3 sampleID ''' How i can create a graph from this type of values ? i really want to use ChartJS because it s very dynamic dor design , someone can help me? -
How to get details from two models in django
I am trying to build an api endpoint that performs a GET request, path -> {url}/api/v1/users/:id I have three models class PvSystem(models.Model): modelNo = models.CharField(max_length=10, blank=False, default='') modelName = models.CharField(max_length=10, blank=False, default='') dimensionPanel: models.FloatField(max_length=10, blank=False, default=NULL) elevation = models.FloatField(max_length=10, blank=False, default=NULL) kwhPeak = models.FloatField(max_length=10, blank=False, default=NULL) avergaeSurplus = models.FloatField(max_length=10, blank=False, default=NULL) class EnergyData(models.Model): pvId = models.ForeignKey(PvSystem,related_name='orders',on_delete=models.CASCADE) energyNeeded = models.FloatField(max_length=10, blank=False, default=NULL) energyConsumption = models.FloatField(max_length=20, blank=False, default=NULL) energyProduction = models.FloatField(max_length=20, blank=False, default=NULL) energySurplus = models.FloatField(max_length=20, blank=False, default=NULL) floorPrice = models.FloatField(max_length=10, blank=False, default=NULL) capPrice = models.FloatField(max_length=10, blank=False, default=NULL) pvStatus = models.BooleanField(blank=False, default=False) dsoId = models.CharField(max_length=70, blank=False, default='') supplier = models.CharField(max_length=70, blank=False, default='') class User(models.Model): name = models.CharField(max_length=70, blank=False, default='') email = models.EmailField(max_length=70, blank=False, default='') password = models.CharField(max_length=70, blank=False, default='') address = models.CharField(max_length=70, blank=False, default='') roleId = models.IntegerField(blank=False, default='1') isActive = models.BooleanField(blank=False, default=TRUE) dsoId = models.CharField(max_length=70, blank=False, default='') supplier = models.CharField(max_length=70, blank=False, default='') dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL) Models Description UserModel: Registered details of the user. EnergyData: A table that provides more details of the user using the users dsoID and supplier to check. PVSystem: Connected to the Energydata hence return result of a user with energy data and pvstatus TRUE. From the above, when the api get request call is made, it … -
Django Framework : i do not understand how to show my data into my homepage.views from polls.views
thanks for reading ! I got some trouble to understand how to display my polls.views into my homepage.views. this is the code not working into my homepage_index.html : {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail.html' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} The same code working on his own application named polls and i fail to repeat this same thing into my homepage This is my homepage/urls.py : from django.urls import path, re_path from django.conf.urls import include from . import views app_name = 'homepage' urlpatterns = [ path('', views.homepage.as_view(), name='homepage'), ] and this is my homepage/views.py : from django.views import generic from django.utils import timezone from blog.models import Article class homepage(generic.ListView): template_name = 'homepage/homepage_index.html' context_object_name = 'latest_article_list' def get_queryset(self): return Article.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:20] When i launch my local server, go to homepage_index.html, i got the message : No polls are available. I miss something and i dont know what or where, its look like the access to the DATA are failing. I'm sorry if I misunderstood the situation, let me know if you want more details, thank you! -
How i can make condition readonly on some fields based on what i choose on foreignkey field (the fields exist on same model) : Django-admin
I have modelA contain field1(foreignkey), field2(float) and other fields(all are float) I would like to makes the some other fields readonly(not editable) depend on what i choose on the field1(foreignkey) and to be clear all those fields are in same model. I would like to do that on django-admin: Here my models.py: class Modele(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='sizes',null = True) w_profile = models.FloatField(null=True) b = models.FloatField(null=True, blank=True) tw = models.FloatField(null=True, blank=True) tf = models.FloatField(null=True, blank=True) Here my admin.py: admin.site.register(ProfileSize) class ModeleAdmin(admin.ModelAdmin): def __init__(self, *args, **kwargs): super(Modele, self).__init__(*args, **kwargs) if self.category.name == "Flate": return self.readonly_fields + ('tw', 'b') elif self.category.name == "Circular": return self.readonly_fields + ('b') else: return self.readonly_fields + ('tf') But what i have on admin.py didn't give me any result , any help will be appreciated.thanks. -
How do I associate a python file with the django web interface?
I have a Python code for the A* algorithm. And I want to modify it so that the user is the one who enters the names of cities, longitude and latitude and link it to the django web interface But I don't know these steps Please helpdownload file code A* Thanks -
I am creating a search function in django but it isn't working
I am trying to create a function to search for objects in base.html from the database using a keyword and printing the results in listing.html base.html <form method="post" action="{% url 'listing'}" name="searchform"> {% csrf_token %} <div class="custom-form"> <label>Keywords </label> <input type="text" placeholder="Property Keywords" name="search_keyword" value=""/> <label >Categories</label> <select data-placeholder="Categories" name = "home_type" class="chosen-select on-radius no-search-select" > <option>All Categories</option> <option>Single-family</option> <option>Semi-detached</option> <option>Apartment</option> <option>Townhomes</option> <option>Multi-family</option> <option>Mobile/Manufactured</option> <option>Condo</option> </select> <label style="margin-top:10px;" >Price Range</label> <div class="price-rage-item fl-wrap"> <input type="text" class="price-range" data-min="10000" data-max="100000000000" name="price-range1" data-step="1" value="1" data-prefix="$₦"> </div> <button onclick="location.href='listing'" type="button" class="btn float-btn color-bg"><i class="fal fa-search"></i> Search</button> </div> </form> views.py def listing(request): global search_keyword p = Paginator(Property.objects.order_by('-listed_on'), 2) page = request.GET.get('page') propertys = p.get_page(page) nums = "p" * propertys.paginator.num_pages if request.method == 'POST' and 'searchform' in request.POST : search_keyword = request.POST['search_keyword'] propertys = Property.objects.filter(name__contains=search_keyword) return render(request, 'listing.html',{'nums':nums, 'search_keyword':search_keyword, 'propertys':propertys}) return render(request, 'listing.html',{'nums':nums,'propertys':propertys}) -
How to parse years of experience from resume from Experience field present in resume?
I am working with a resume parser in Django that can parse all the data but I want to calculate years of experience from the dates mentioned in the resume in the experience field I have come up with a strategy that we can parse the experience section and parse all the dates but I am facing a hard time to implement it. Is there any other way to calculate the experience from different dates and add all the dates? def extract_experience(resume_text): ''' Helper function to extract experience from resume text :param resume_text: Plain resume text :return: list of experience ''' wordnet_lemmatizer = WordNetLemmatizer() stop_words = set(stopwords.words('english')) # word tokenization word_tokens = nltk.word_tokenize(resume_text) # remove stop words and lemmatize filtered_sentence = [w for w in word_tokens if not w in stop_words and wordnet_lemmatizer.lemmatize(w) not in stop_words] sent = nltk.pos_tag(filtered_sentence) # parse regex cp = nltk.RegexpParser('P: {<NNP>+}') cs = cp.parse(sent) # for i in cs.subtrees(filter=lambda x: x.label() == 'P'): # print(i) test = [] for vp in list(cs.subtrees(filter=lambda x: x.label()=='P')): test.append(" ".join([i[0] for i in vp.leaves() if len(vp.leaves()) >= 2])) # Search the word 'experience' in the chunk and then print out the text after it x = [x[x.lower().index('experience') + 10:] … -
use js variable in Django
userlist.html <a id="{{user.id}}" href="/followerPosting?id={{following.id}}" class="btn">profile</a> I want to pass the id value to the url when the btn is clicked. followerPosting.html <script type="text/javascript"> var url = require('url'); var queryData = url.parse(request.url, true).query; var fid = queryData.id; </script> So I parsed the URL and stored the id value in a variable (fid). {% for twit in twits %} {% if twit.User.id == fid %} <div class="twit"> <div class="twit-content">{{twit.content}}</div> </div> {% endif %} {% endfor %} I want to use this variable in html (django) how can I use this value? I tried to use Ejs but it didn't work well... -
filefield serializer is not parsing the file object
I have a model in my application: class GRNRFIDSerials(models.Model): grn = models.ForeignKey(Grn, on_delete=models.CASCADE) file = models.FileField(upload_to='grnrfid/', null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) I am trying to upload the file in the ORM like the following: class GRNRFIDSerialsUploadAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated, ) serializer_class = GrnRFIDSerialsSerializer parser_classes = (FormParser, MultiPartParser) def post(self, request, *args, **kwargs): owner = request.user.pk print("reached") d = request.data.copy() d['owner'] = owner print("d", d) serializer = GrnRFIDSerialsSerializer(data=d) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) where d is : d <QueryDict: {'no_of_fileA_files': ['1'], 'grn': ['479'], 'viewType': ['Pool Operator'], 'companyId': ['52'], 'document': [<InMemoryUploadedFile: EPC (4).xlsx (application/vnd.openxmlformats-officedocument.spr eadsheetml.sheet)>], 'owner': [27]}> This runs without an error but n the database entry filefield is shown as blank. How do I upload the file object? -
Is it good practice to do integration testing on Django's admin section?
I know StackOverflow discourages 'opinion-based' questions, but this seems very basic and I'm surprised by the lack of info on it. Normally I would think of some kind of Selenium test for any UX as mandatory, but the Django testing docs don't mention anything of the sort, and Googling for 'Django admin integration test' and similar isn't highlighting anything about the admin section. Do people just tend to unit test the admin.py subclasses and leave it at that, assuming the rest is covered by the framework? -
I just pip installed social-auth-app-django==3.1.0 and I got the error below
I just pip installed social-auth-app-django==3.1.0 and I got the error below while trying to migrate. ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\Hp\anaconda3\lib\site-packages\django\utils\encoding.py) -
how to write unit test using pytest for django url
my url and function are as follows url path('drivers/', views.drivers, name='drivers'), views.py @login_required(login_url='/account/login') def drivers(request): drivers = Drivers.object.all() return render(request, "drivers.html", {'drivers': drivers}) I've just started learning unit testing. How do i write unit test to check my url is working as expected. -
Nasa API pass the data so slow
I'm trying to get near-earth asteroid data from NASA API. And I'm getting the data I need but it's coming very slow. How can I optimize my code to get data quickly? @api_view(['GET']) def getDates(request, start_date, end_date): dates = [] all_data = list() api_key = 'hpdCBykg6Bcho1SitxAcgAaplIHD1E0SzNLfvTWw' url_neo_feed = "https://api.nasa.gov/neo/rest/v1/feed?" params = { 'api_key': api_key, 'start_date': start_date, 'end_date': end_date } response = requests.get(url_neo_feed, params=params) json_data = orjson.loads(response.text) date_asteroids = json_data['near_earth_objects'] for date in date_asteroids: dates.append(date) # Splitting the data to make it more meaningful for date in dates: collection = json_data.get('near_earth_objects') all_dates = collection.get('{}'.format(date)) all_data.append(all_dates) return Response(all_data) -
Many tasks at once in Celery?
If we use celery beat and run about 1000 tasks by same crontab schedule, will tasks run one by one or some tasks will not run (cause of out of time)? redis as MQ -
Third party Api with Header key integration in django-python
I want to use my old rest API for my new Django project. In the old API, I used the header key, but I don't know how to use this API key in my new Django project. Could anyone help me? -
Upload Django app to Heroku. ModuleNotFoundError:No Module named 'Name of Project"
I can not upload Django App to Heroku by command: git push heroku master. After uploading I have error: ModuleNotFoundError: No module named 'bot_diller' Procfile: web: gunicorn bot_diller.wsgi --log-file - enter image description here -
Jinja subtraction and variable declaring
In jinja, how to subtract. Eg: I have some number inside {{ review.rating }} , and I want to subtract the number with 5. Is it like {{ 5 - review.rating }} or how? And is it possible to put the answer in another variable in jinja itself? -
Is there a way to overwrite the Django Admin's Inline instance change text "Change" to something else more intuitive?
I am customizing the Django Admin and have an inline model's instances listed under another model. I am looking to change the text "Change" that leads to the selected inline model's instance change page but was unable to figure this one out. I just need to change this to something like "Change view/display all fields" as I am displaying only a limited number of fields in the inline view. Image displaying the text to be changed #models.py class TourItem(models.Model): tour = models.ForeignKey(Tour, related_name='items') ... class Tour(models.Model): ... #admin.py class TourItemInline(admin.TabularInline): model = TourItem show_change_link = True ... class TourAdmin(admin.ModelAdmin_ model = Tour inlines = (TourItemInline, ) ... -
No table is created when excuted "python3 manage migrate"
python version: 3.6.4 django version: 3.1.7 db: sqlite3 my_app: robot my_models: Check_Monitor_Task, Action_Manager, Questions_Answers_Task Step1: models Step2: python3 manager makemigrations Migrations for 'robot': robot/migrations/0001_initial.py - Create model Action_Manager - Create model Check_Monitor_Task - Create model Questions_Answers_Task Step3: python3 manager migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, robot, sessions Running migrations: Applying robot.0001_initial... OK Step4: confirm the tables There is record in django_migrations sqlite> select * from django_migrations order by id desc limit 3; id|app|name|applied 25|robot|0001_initial|2022-05-11 17:33:16.780900 18|sessions|0001_initial|2022-05-10 21:30:28.049031 17|auth|0012_alter_user_first_name_max_length|2022-05-10 21:30:27.985724 But no tables showed: python3 manage.py dbshell SQLite version 3.21.0 2017-10-24 18:55:49 Enter ".help" for usage hints. sqlite> .tables auth_group auth_user_user_permissions auth_group_permissions django_admin_log auth_permission django_content_type auth_user django_migrations auth_user_groups django_session sqlite> I have tried to delete migration files and pycache, but working like every times. Please tell my why, and how to create table. Thanks. -
Optimize recursive function in Django Tree structure Model
I am trying to implement a team hierarchy in a Django work application. My requirements are Team may have Team Lead, members and a Parent Team. current node will be considered as one of the child of parent team Team lead can access the members and all child team members( sub child nodes at any level in that hierarchy) For Example Team A have a child team Team A1 and Team Team A2, and Team A2 another child TEAM A21, Team Lead of A can acces all members data of Team A,Team A1,Team A2, and Team A21 Please see my model structure class Team(models.Model): title=models.CharField(max_length=200,null=True) team_lead=models.ForeignKey(StaffUser,on_delete=models.SET_NULL,related_name='teams_leaded',null=True) member_staffs=models.ManyToManyField(StaffUser,related_name='teams_joined') parent=models.ForeignKey("self", on_delete=models.SET_NULL,blank=True, null=True,related_name='children') published_date = models.DateTimeField(blank=True, null=True) class StaffUser(models.Model): name=models.CharField(max_length=100,null=True) email=models.CharField(max_length=100,null=True) user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='staffs',null=True) My intentian is to append all accesable members id'to user input when a request comes Fo that I have written a recursive function to extract the all subchilds after getting a staff object . But it is very slow. Is there any way to optimazie this function. def extractMembers(staff_obj,sub_members): try: if(staff_obj.user.id not in sub_members): sub_members.append(staff_obj.user.id) if(staff_obj.teams_leaded is not None): leaded_teams=staff_obj.teams_leaded.all() for team_obj in leaded_teams: team_members=team_obj.member_staffs.all() for tmember_obj in team_members: if(tmember_obj.user.id not in sub_members): sub_members.append(tmember_obj.user.id) child_teams=team_obj.children.all() for team_child_obj in child_teams: child_team_staffs=team_child_obj.member_staffs.all() …