Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return JSON queryset for search
I am trying to write a function to search and display its result as a JSON format to the user. Currently, I am doing the search successfully from the database and I can find and list down the data from the database in products attribute. But I have the issue of displaying the results as I return the list of products from the database. def search_titles(request): if request.method == "POST": search_text = request.POST['search_text'] else: search_text = '' products = Product.objects.filter(title__contains = search_text) return HttpResponse(json.dump(products), content_type = 'application/json') I cannot display the results to the user. How to return the products list and display the items? -
get two foreign key parameters via view
The user enters the comment in the profile of the NEGOCIO, and I need only the comments with the id of that NEGOCIO appear and that all comments have the USUARIO id. when registering the COMENTARIO table, I need it to automatically get the ID of the NEGOGIO Table, and the NOME of the USUARIO table. and pass these two values automatically via form. And only logged in users will be able to comment. I use user extending to NEgocio and Usuario models.py class Negocio(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) empresa = models.CharField(max_length=50, blank=False) class Usuario(models.Model): nome = models.CharField(max_length=50, blank=False) sobrenome = models.CharField(max_length=50, blank=False) class Comentario(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) nome = models.ForeignKey(Usuario, on_delete=models.CASCADE) comentario = models.CharField(max_length=255, blank=True) nota = models.CharField(max_length=255, choices=NOTA_CHOICES, blank=True) views.py def comentario_form(request): comentario = Comentario.objects.all() form = ComentarioForm() data = {'comentario': comentario, 'form': form} return render(request, 'profile_negocio/comentario.html', data) def cadastro_comentario(request): if request.method == 'POST': form = ComentarioForm(request.POST) if form.is_valid(): user = form.save() form.instance.user = request.user form.instance.nome = request.user user.usuario.nome = form.cleaned_data.get('comentario') user.usuario.sobrenome = form.cleaned_data.get('nota') user.save() return redirect('sistema_perfil') else: form = UsuarioForm() return render(request, 'profile_negocio/comentario.html', {'form': form}) comentario.html <form method="post" action="{% url 'cadastro_comentario' %}" class="form-signin" enctype="multipart/form-data" id="form" name="form" validate> {% csrf_token %} <div class="form-row "> <div class="form-group col-md-6 … -
HINT: Try using path() instead of a tuple
I am currently using Django third-party application called Django-messages to handle user-user massaging. I'm encountering this Error for some days ERRORS: ?: (urls.E004) Your URL pattern ('^messages/', (, None, None)) is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. HINT: Try using path() instead of a tuple. System check identified 1 issue (0 silenced). The complain is about the urls.py Can you help me out please? I have tried every single ways but not working out. Thanks Here is the urls.py file from django.conf.urls import url from django.views.generic import RedirectView from django_messages.views import * urlpatterns = [ url(r'^$', RedirectView.as_view(permanent=True, url='inbox/'), name='messages_redirect'), url(r'^inbox/$', inbox, name='messages_inbox'), url(r'^outbox/$', outbox, name='messages_outbox'), url(r'^compose/$', compose, name='messages_compose'), url(r'^compose/(?P<recipient>[\w.@+-]+)/$', compose, name='messages_compose_to'), url(r'^reply/(?P<message_id>[\d]+)/$', reply, name='messages_reply'), url(r'^view/(?P<message_id>[\d]+)/$', view, name='messages_detail'), url(r'^delete/(?P<message_id>[\d]+)/$', delete, name='messages_delete'), url(r'^undelete/(?P<message_id>[\d]+)/$', undelete, name='messages_undelete'), url(r'^trash/$', trash, name='messages_trash'), ] My Django Version is 2.1 django-messages==0.5.3 -
Django testt: AttributeError: 'WSGIRequest' object has no attribute 'user'
The test: 1) login with a user 2) favourite a post class FormTest(TestCase): def setUp(self): self.user = ProjectUser.objects.create(username='testUser', email='testUser@user.com') self.user.set_password('testPassword') self.user.save() self.client = Client() self.factory = RequestFactory() def sometest(self): self.client.login(username='testUser', password='testPassword') user = auth.get_user(self.client) assert user.is_authenticated new_object_2 = SampleModel.objects.create(unique_id='123456', name='sample') request = self.factory.post(reverse('page1:favourite_post', kwargs={'fav_id': new_object_2.id})) response = favourite_post(request, new_object_2.id) print(response) My url file is path('favourite_post/<int:fav_id>', views.favourite_post, name='favourite_post'), The views.py is def favourite_post(request, fav_id): post = get_object_or_404(Post, id=fav_id) if request.method == 'POST': if post.favourite.filter(id=request.user.id).exists(): post.favourite.remove(request.user) else: post.favourite.add(request.user) return HttpResponseRedirect(reverse('page:some_page', args=(fav_id,))) The error I get is AttributeError: 'WSGIRequest' object has no attribute 'user' -
Adding extra font into an HTML page
Question is how to apply specific font to a whole page? I did it in the example bellow and it doesn't work. It is only work when I apply it to the exact tag, like here: <p style="font-family: Palatino Linotype; src: url({% static "fonts/Palatino.ttf" %})">Description-{{ current_boat.boat_description }}</p> </div> {% load bootstrap4 %} {% load static %} {% load staticfiles %} {% load thumbnail %} <html lang="en"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>Boat pdf</title> <style type="text/css"> @font-face { font-family: Palatino Linotype; src: url({% static "fonts/Arial.ttf" %}); } body { font-family: "Palatino Linotype", Arial, sans-serif; color: #333333; } </style> </head> <body> <p style="font-family: Palatino Linotype; src: url({% static "fonts/Palatino.ttf" %})">Description-{{ current_boat.boat_description }}</p> </div> <div class="row"> {% for instance in current_boat.images %} <a href=" {{ instance.boat_photo.url}}"> <img class=" ml-3" src="{% thumbnail instance.boat_photo "default" %}"></a> {% endfor %} </div> </body> </html> -
Django get choice display on using .values
For a Model with field type, is there any way to get the choice display value on using Model.objects.values() ? I tried Model.objects.values('get_type_display') but it doesn't work. -
How lazy evaluation in django query works?
I'm having doubt regarding lazy evaluation in django-querysets. This is my django query: Method1: tyres_in_car = Car.objects.filter(serial_no__startswith('AB')).values('tyre__type') In this query I'm accessing foreign key values using .values() (tyre type) in this case. Another approach which I use is: Method2: Line1 : tyres = Car.objects.filter(serial_no__startswith('AB')) Line2 : all_tyres = tyres.tyre.all() Line3 : tyres_in_car = [ ty.type for ty in all_tyres ] Since, I'm using .values() in both the methods, does the query hits database only once in both the cases( because of lazy evaluation in case of Method 2) or it hits two times in case of Method 2. From the perspective of code readability, Method 2 looks more appropriate in my opinion. -
AJAX JSON response doesn't refresh for tag at Django template
I have built a view in views.py that returns a JSON when user press a button. The page updates simple html divs (last_bid, credits, message) without reloading but I have some {% for %} tags that don't refresh although JSON response is updated with extra data. template.html script <script> $('#bid').on('submit', function(event){ event.preventDefault(); $.ajax({ method: 'POST', url: '{% some url %}', datatype: 'json', data: { some data }, success: function(data) { $('#last-bid').html(data.last_bid); $('#credits').html(data.credits); $('#message').html(data.message); $('#registered_players').html(data.registered_players); } }); }); template.html <div id="registered_players"> {% for i in registered_players %} {{ i.auction_player__user__username }} {% endfor %} </div> JSON {"registered_players": [{"auction_player__user__username": "admin"}, {"auction_player__user__username": "minos"}], "last_bid": "8.10", "credits": 612, "message": ""} -
how to display drop-down selection based on the previous selected option in django
Here is my some code to handle the student fee management.This code works as i wanted but the only thing i want to change is while submitting studentfee form through template.While adding the student fee information if a user select some course then only this selected course's basic_price and advanced_price should displayed in the select fee dropdown item.I tried so many things but did't worked.How can i achive this ?? models.py class Course(models.Model): title = models.CharField(max_length=250) basic_price = models.IntegerField(default=0) advanced_price = models.IntegerField(default=0) basic_duration = models.CharField(max_length=50) advanced_duration = models.CharField(max_length=50) shift = models.CharField(max_length=1000) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class StudentFee(models.Model): student = models.ForeignKey(Student,on_delete=CASCADE) course = models.ForeignKey(Course,on_delete=models.DO_NOTHING,related_name='course') total_fee = models.ForeignKey(Course,on_delete=models.DO_NOTHING,related_name='total_fee') first_installment = models.IntegerField(default=0) date_first_installment = models.DateField(default=datetime.date.today) second_installment = models.IntegerField(default=0) date_second_installment = models.DateField(default=datetime.date.today) third_installment = models.IntegerField(default=0) date_third_installment = models.DateField(default=datetime.date.today) remaining = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.total_fee views.py def addstudentfee(request): if not request.user.is_superuser: messages.info(request, 'You have to logged in first as a admin') return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) students = Student.objects.all() courses = Course.objects.all() if request.method == "POST": form = StudentFeeForm(request.POST) total_fee = form['total_fee'].value() first_installment = form['first_installment'].value() second_installment = form['second_installment'].value() third_installment = form['third_installment'].value() remaining = int(total_fee) - int(int(first_installment)+int(second_installment)+int(third_installment)) if form.is_valid(): student = form.save(commit=False) student.remaining = int(remaining) student.save() messages.success(request,'data saved for … -
"detail": "Incorrect authentication credentials."
How to add token in the header of url. It is showing "detail": "Incorrect authentication credentials." in output. How to use environment in this. -
How to fix blank page django 2
Please help. I'm following along the following django crash course: https://ceiphr.com/blog/a-crash-course-in-django but I get a blank page after the final section titled "Templates with Style". I'm using django 2.2.0. The what the command tree returns. . ├── blog │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── django_cc │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ └── wsgi.py ├── manage.py ├── Pipfile ├── Pipfile.lock └── templates └── index.html My settings.py file looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Thank you. -
TypeError: $.post is not a function when trying to send a stringified json object
Receive this error message every time I click submit. What's the problem? Tried changing to a non-slim version, it seems that It's still not working properly. First time using ajax post not sure if this is how to use it function func() { var formData = JSON.stringify($("#form").serializeArray()); $.post('test.php', { elements: formData }); console.log(formData) } <form id="form"> <div class="form-group"> <label for="Email1">Email address</label> <input name="Email1" type="email" class="form-control" id="Email1" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">Please double check</small> </div> <div class="row"> <div class="col"> <input name="firstname" type="text" class="form-control" placeholder="First name"> </div> <div class="col"> <input name="lastname" type="text" class="form-control" placeholder="Last name"> </div> </div> <div class="form-group"> <label for="Select1">Select a reason</label> <select name="reason" class="form-control" id="Select1"> <option>No idea how this website works</option> <option>Notice a bug</option> <option>Notice many bugs</option> <option>Others</option> </select> </div> <div class="form-group"> <label for="Textarea1">Enter your message here</label> <textarea name="text" class="form-control" id="Textarea1" rows="3"></textarea> </div> <input type="submit" class="btn btn-primary" onclick="func()" value="submit" /> </form> <div id="b" style="visibility:hidden"></div> <div id="d"></div> <script src="https://code.jquery.com/jquery-3.4.0.js" integrity="sha256-DYZMCC8HTC+QDr5QNaIcfR7VSPtcISykd+6eSmBW5qo=" crossorigin="anonymous"> </script> -
Multiple button in django : Accept and Reject
I am new to django and need help to implement button. I am working on a project where i want accept and reject button and whenever client click on the respective button that object will go into the accept or reject template. and i have no idea how can i do this this is my .html file which is displaying all the objects and have a accept and reject button. ''' <table class="table table-hover"> <thead> <tr> <th>S No.</th> <th>COMPANY NAME</th> <th>TEAM MEMBER</th> <th>EMAIL</th> <th>STATUS</th> <th><center>#</center></th> </tr> </thead> <tbody> {%for team in object%} <tr> <th scope="row"> {{ forloop.counter }}</th> <td>{{team.company_name}}</td> <td>{{team.team_member}}</td> <td>{{team.email}}</td> <td>-</td> <td><center><a href="{% url 'admin_team_detail'%}"><button type= "button" class= "btn btn-default">Accept</button></a> <a href="#"><button type= "button" class= "btn btn-default">Reject</button></a></center></td> </tr> {% endfor %} </tbody> </table>''' here is views.py ''' def admin_team_detail(request): obj= Create_Team.objects.all() print(request.method) return render(request, "admin/team-details.html", {"object": obj})'''' this is rendering all the objects from database and displaying on the website. i know that i have to make two templates for accept and reject but i don't know how it will take the objects that have a accept or reject response. and i also want that if client click on the button then that response will be saved in the … -
Django: Models relationship and queries
I been testing with model relationships several times for a User to select a number of ticket/s that will contain the information in the form of Ticket ID, and along with it, comes an Order ID that I will use after when the user input their CC information with it. A user can order many ticket/s and each Ticket ID has an Order ID attached with it. When I query for the Ticket to be created in my views.py--it shows that "order_id" is not defined. How do I query so that when I create the ticket information, an order ID attaches with it? Your suggestions would be helpful! models.py class User(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email=models.CharField(max_length=100) password=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Order(models.Model): full_name=models.CharField(max_length=100) cc_number=models.PositiveIntegerField() exp_date=models.PositiveIntegerField() cvc=models.PositiveIntegerField() buyer=models.ForeignKey(User, related_name="bought_tickets", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Ticket(models.Model): venue=models.CharField(max_length=100) quantity=models.PositiveIntegerField() price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True) loop=models.CharField(max_length=100) purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT) order=models.ForeignKey(Order, related_name="orders", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) views.py def add(request): if not 'user_id' in request.session: return redirect('/chrisgrafil') if request.method!='POST': messages.error(request, 'Please select the following options') return redirect('/dashboard') else: Ticket.objects.create(venue=request.POST['venue'], quantity=request.POST['quantity'], loop=request.POST['loop'], purchaser=User.objects.get(id=request.session['user_id']), order=Order.objects.get(id=['order_id'])) return redirect ('/confirmation') -
Django model query all fields including the ManyToManyField in a single command
While playing around with the ManyToManyField, I wondered is there a way you can query a ManyToManyField automatically the same way you'd do a ForeignKey using select_related()? Tables: class Author(models.Model): fullname = models.CharField(max_length=100) class Foo(models.Model): bar = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) foo = models.ForeignKey(Foo) author = models.ManyToManyField(Author) In order to get the data I need from Book I usually do: book = Book.objects.select_related('foo').get(pk=1) authors = book.author.all() which makes 2 trips. Is there a way to combine them the way select_related() does? -
CSS fails when passing a list to render(request)
I am trying to follow a tutorial online and for some reason I cannot get css to work correctly with my views.py file and django 2.2. when I remove the "My_context" from return render(request, 'blog/home.html', My_context) and pass something else like return render(request, 'blog/home.html', {'title': 'blah') it seems to work just fine. I have tried restarting the server and and clearing the page cache. I am new to django and not sure what else to try. # views.py from django.shortcuts import render posts = [ { 'author': 'xxxxx', 'title': 'Blog Post 1', 'Content': 'My First Post Content', 'date_posted': 'August 27, 2019' }, { 'author': 'xxxxx', 'title': 'Blog Post 2', 'Content': 'My Second Post Content', 'date_posted': 'August 27, 2019' } ] This function fails to load css correctly def home(request): My_context = { 'posts': posts } return render(request, 'blog/home.html', My_context) This function works fine def about(request): `return render(request, 'blog/about.html', {'title': 'About'})` code for home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }} on {{ post.date_posted }}</p> <p>{{ post.Content }}</p> {% endfor %} {% endblock content %} code for about.html {% extends "blog/base.html" %} {% block content %} <h1>About … -
Beanstalk Migration Failing for Geodjango
I want to deploy geodjango in aws beanstalk. I have already tried this solution. It worked before. commands: 01_yum_update: command: sudo yum -y update 02_epel_repo: command: sudo yum-config-manager -y --enable epel 03_install_gdal_packages: command: yum --enablerepo=epel -y install gdal gdal-devel packages: yum: git: [] postgresql96-devel: [] gettext: [] libjpeg-turbo-devel: [] libffi-devel: [] But right now it's showing this error. AttributeError: /usr/lib64/libgdal.so.1: undefined symbol: GDALGetMetadataDomainList (ElasticBeanstalk::ExternalInvocationError) -
Filtering based on many-many and avoiding duplicates
I am new to using Many-Many fields and I really could not find a good example that explained on how to go on with this task. I currently have two models modelJob and modelSkillSubscription now modelJob contains a Many-To-Maney fields of skills. What I would like to do is retrieve modelSkillSubscription if they contain any of the skills that I have obtained. Say modelJob contains [SkillA,SkillB,SkillC]. I would like to pass this to a filter and obtain all modelSkillSubscription that contains any of the skills from the List avoiding duplicates. class modelJob(models.Model): skills = models.ManyToManyField(modelSkill,blank=True) class modelSkillSubscription(models.Model): employer = models.ForeignKey(modelEmployer, on_delete=models.CASCADE, default=None, blank=True) skills = models.ManyToManyField(modelSkill, blank=True) Any suggestions on how I can accomplish this ? -
Connecting to the port Atom-live-server using Django
I start the server running the manage.py in my CMD. Then in atom I am opeing the atom-live-server on the same port to establish the connection. WHe I save In atom the page will not reload until I reload it manually. I looked for documentation and found none. I do not know why I still have to manually refresh the page for the changes to appear. -
Implementing google maps searching in Django backend
I want to implement google maps search functionality in my Django backend. So the users could have the ability to search something on the website and find them on the map (e.g restaurants). I did an extensive research but couldn't find a useful tutorial or a guide. What's the best way to do it? -
Getting error add() got an unexpected keyword argument 'id' in django
when i run the URL http://127.0.0.1:8000/crud/add/1 it gives me error add() got an unexpected keyword argument 'id', can anyone please help me why i am getting this error ? here i have added my whole code, can anyone please help me how to resolve this issue ? urls.py app_name = 'crud' urlpatterns = [ path('',views.index, name='index'), path('add/',views.add, name='add'), path('add/<int:id>',views.add, name='update'), ] views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from .models import Pages from django.urls import reverse from django.shortcuts import get_object_or_404, render def index(request): pagelist = Pages.objects.all() context = {'pagelist': pagelist} return render(request, 'polls/index.html', context) def add(request): if request.POST: title = request.POST.get("title") permialink = request.POST.get("permialink") updated_date = request.POST.get("updated_date") bodytext = request.POST.get("bodytext") page_data = Pages(title=title,permialink=permialink,updated_date=updated_date,bodytext=bodytext) page_data.save() return HttpResponseRedirect(reverse('crud:index', args=(''))) else: return render(request,'polls/add.html') -
Best way to structure my urls/views to access a users inventory
For my frontend routing, the logic I want is like this: www.mysite.com/inventory If there is no params for this, it returns the logged in users list of items. For www.mysite.com/inventory/uuid-of-other-user/, it will return user B's inventory. For my backend, I am using django-rest-framework ViewSets. This is my current url: router = DefaultRouter() router.register(r'products',ProductViewSet, base_name='products') urlpatterns = router.urls And this is my current views: class ProductViewSet(viewsets.ModelViewSet): def list(self, request): queryset = Product.objects.filter(user=user) serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): name = request.data['name'] description = request.data["description"] category = request.data["category"] user = request.user i =Product(name=name,description=description,category=category,user=user) i.save() serializer = ProductSerializer(i) return Response(serializer.data) Currently if I got to mysite/api/products/, it will return me a list of all products, and then I just filter out the ones that match the user. If I input a parameter after products/, then I will be querying for the uuid of a specific product, not a user's uuid. How should I structure my back end for this if I want to be able to do both (get detailed view of item which I assume will follow the url of mysite.com/api/product/uuid-of-my-item) and get all items that belong to user X? My first guess is to create an inventory model, … -
i have learnt python and Django without going to any college or institute, should i get a job?
i have learnt python and Django without going to any college or institute because in our state(Kashmir India), here is no teaching center for python. i have no certification, what should i do to be became best in Python/django and get a job without certification. -
could not convert string to float: 'cafe'
I start to developpe a web application using django, this application predict the sale, for that I used linear regression, I have some variables string, in order to train the model I convert all the string variables to int using method handle_non_numerical_data(). the user of application enter the field of string as string method def handle_non_numerical_data(df): columns = df.columns.values for column in columns: text_digit_vals = {} def convert_to_int(val): return text_digit_vals[val] if df[column].dtype != np.int64 and df[column].dtype != np.float64: column_contents = df[column].values.tolist() unique_elements = set(column_contents) x = 0 for unique in unique_elements: if unique not in text_digit_vals: text_digit_vals[unique] = x x = x + 1 df[column] = list(map(convert_to_int, df[column])) return df my model # Libraries import numpy as np import pandas as pd import pickle from matplotlib import pyplot as plt from sklearn import metrics from sklearn import model_selection #from sklearn import preprocessing from sklearn.cluster import KMeans from sklearn.linear_model import LinearRegression from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split #from sklearn.linear_model import Ridge from sklearn.externals import joblib # Importing Dataset data = pd.read_csv('ml_code/ml_process/test.csv') data.fillna(0, inplace=True) def handle_non_numerical_data(df): columns = df.columns.values for column in columns: text_digit_vals = {} def convert_to_int(val): return text_digit_vals[val] if df[column].dtype != np.int64 and df[column].dtype != np.float64: column_contents = … -
How to create a form in Django with dropdown items?
I need to create a form which contains fields Group Name, Mentor, Students. Group Name : Text Field, Mentor : dropdown menu(can select only one), Students :(dropdown menu) (can select multiple) . Mentors and Students should be from my users table based on their User group How can I create such form in django?