Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to use Pagination with filter function?
I am trying to use Pagination with the Django Filter function, But I am getting this error. http://127.0.0.1:8000/product_search/?page=2&search=e Cannot use None as a query value product = Product.objects.filter(productName__contains=name) Here is The view.py function def searchProduct(request): name = request.POST.get("search", None) try: product = Product.objects.filter(productName__contains=name) paginator = Paginator(product, 2) page = request.GET.get('page') page_product = paginator.get_page(page) if page_product: context = { 'searchResults': page_product, 'name': name } return render(request, "Amazon/searchResult.html", context) else: return render(request, "Amazon/searchResult.html", {'message': "No Product Found"}) except Product.DoesNotExist: return HttpResponse("Page Not Found") Here is HTML/Jinja code <nav aria-label="..."> {% if searchResults.has_other_pages %} <ul class="pagination justify-content-center"> {% if searchResults.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ searchResults.previous_page.number }}&search={{ name }}" tabindex="-1"> Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" tabindex="-1">Previous</a> </li> {% endif %} {% for i in searchResults.paginator.page_range %} {% if product.number == i %} <li class="page-item active"> <a class="page-link" href="#">{{ i }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}&search={{ name }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if searchResults.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ searchResults.next_page_number }}&search={{ name }}">Next</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">Next</a> </li> {% endif %} </ul> {% endif %} </nav> I have a rough … -
How to use a list field in django
lets say we have model which is an exam (am making an educational website), and the exam has a list of people who have done it, the question is what filed type should i use? class Exam(models.Model): difficulty = models.CharField(max_length=10, choices=[('ez','easy'),('hrd', 'hard')]) module = models.CharField(max_length=10, choices=[('math','math'),('physics', 'physics')]) completed_by = ???????????? (lets assume that there an other module callded user and i want this field to be a list of that users) ` -
How to design database for online examination
I'm working on a project using Django, MySQL in which I need to store the information about the Students and information about the Courses, Subjects, Questions, Result and etc. My goal is to give the services to the students for giving online examinations to know how good they are at the particular Subject just like the JEE, IEEE. I have created these tables in my project : 1. Student_tbl : stuId(PK), name, email, password, mobile, course 2. Course_tbl : courseId(PK), Course_name 3. Subject_tbl : subId(PK), class_id(FK), Subject_name 4. Topic_tbl : topicId(PK), class_id(FK), subject_id(FK), Topic_name 5. Question_tbl : quesId(PK), subjectId(FK), topicId(FK), Question_text, Answer_text, Marks(per question i.e. 2marks for 1 question etc.) 6. Result_tbl : id(PK), studentId(FK), subjectId(FK), Total_Marks My Requirement is: Register the students in the Student_tbl Show them the test paper just like JEE or any other online exams Once they complete the test then based on the performance they can get result from the Result_tbl we're storing the info. Please help me out to achieve this features and also suggest me what the extra column with Foreign Keys or tables should be there , if I have committed any mistakes -
how can pass height and width to the imagekit templatetag?
views.py class imagess(ImageSpec): processors = [SmartResize(100,100)] format = 'JPEG' options = {'quality': 100} register.generator('main:imagess', imagess) index.html {% generateimage 'main:imagess' source=source_file %} this generates a image of height 100 x 100 how can pass/define a custom height and width for the generated image from the HTML file....like {% generateimage 'main:imagess' source=source_file height=1080 width=720 %} -
Django - Show history in admin working but only when actions take place in admin
In Django admin, when you are looking at a record there is a button called "history". When you click on this button, it tells you when the record was created and by whom and also each time a field was changed and by whom. I find this extremely useful. However, I noted that these only show up for actions that are done on the admin page. So when I change the record through a view, this is not displayed in that history. Is there an easy way to have my views store this information also so that it will all be visible from the admin page? Thanks so much in advance for your help. -
Filtered search for MultiSelectField in Django 3
Now that I change some choice fields into multi select fields for usability. When I set up the drop down filtering for sorting using iexact with the MultipleSelectField it is no longer supported. Is there a way to Filtered search for MultiSelectField using unique individual values to find both individual and multiple results. Desired functionality I am try to get to a drop down sort with only one choice of each decade for the multiple select fields that can find. Then the search to find single or multiple select results. Select decade 1950s ... 2000 2010 2020 Currently I was about the front end displays what is created for each new entry so if single of combination it creates a unique entry for each combo or single entry so its kind of ugly and messy. The .distinct() worked good when only one choice per choices but with many possibilities of combinations are now also unique. I assume the iexact no longer working for filtering. Select decade 1950s, 1960s, 1970s ... 2000 2010, 2020 2020 act / views.py # SEARCH BASED-KEYWORD def search(request): act = Act.objects.order_by('-created_date') demographics_search = Act.objects.values_list('demographics', flat=True).distinct() defaultgenre_search = Act.objects.values_list('defaultgenre', flat=True).distinct() decade_search = Act.objects.values_list('decade', flat=True).distinct() genre_search = Act.objects.values_list('genre', … -
get result from Json string to dict in python django
I use serialize to get data in view. contract_posts = serializers.serialize('json', Contracts.objects.all()) Then I use json.loads get data, but I just get 1 by 1 case not all data from model. contract_posts = json.load(contract_posts)[0] print(contract_posts["fields"]) I want to get all data, I try to use for loop but it show error 'str' object has no attribute 'read' my for loop for i in range(100): contract_posts = json.load(contract_posts)[i] print(contract_posts["fields"]["contract"]) i+=1 I dont know how to get len json.load(contract_posts), so I use range 100 as an example number Please help me all -
Django generic class view
I'm new to Django, and I started to learn about the generic views. Indeed they're useful, the problem is I don't know for which purpose each view is used. So, Can somebody help with this? Psst. I read a lot and been searching for an article or post to explain them, but I couldn't find one. -
I am trying to install pip, virtualenv but it is displaying something else, which will be in the description below
traceback (most recent call last): File "/usr/local/bin/pip", line 11, in <module> load_entry_point('pip==21.0', 'console_scripts', 'pip')() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 489, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2843, in load_entry_point return ep.load() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2434, in load return self.resolve() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 2440, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/Library/Python/2.7/site-packages/pip-21.0-py2.7.egg/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax -
Accessing ID of the latest a django model file upload
I have a django model as below: class excel_upload(models.Model): my_excel_file = models.FileField() I only every have one file uploaded to it. Because i delete the previous one. However i am accessing the path to the file via the ID. The problem with this is that when I delete the old file and upload the new file the id counter for the file needs to increase in order for me to access the newly uploaded file. Does anyone know how i can update automatically pull the latest uploaded file? How i am currently accessing it is by: the_uploaded_excel_file = excel_upload.objects.get(id=11) As you can see this is the 11th time have had to change the id number. -
Django update model instance asynchronously
My website has a button to check notifications as a drop down while still remaining on the same page. I would like to update the field unread of every notification from Trueto False of that user when the button is clicked, without having to change or update the page. I have been looking into Celery to solve this, but before digging to deep I would like to ask the community on what the best practice is to solve this type of functionality. -
why object field changed in api get request?
i want test my api so i wrote test and run my test that works well.but when i run another irrelevant (GET) API my previous test do not work and have strange behavior When the following code is executed from another api: api1 query_set = (Project.objects.all() .annotate( name=Substr( Cast(TruncMonth("created_at"), output_field=CharField()), 1, 7 )) .values("name") .annotate(slug=Concat(V("en-"), "name")) .order_by("name") .distinct() ) return Response( data=ProjectArchiveListSerializer(query_set, many=True).data, status=status.HTTP_200_OK, ) i see this behavior from test: in test of api2 print(Project.objects.all().values('overview','title','text',"slug")) response = self.client.get("/api/v1.0.0/projects/project/pslug-1/") print(Project.objects.all().values('overview','title','text',"slug")) and object field changed like this: output of api test2 <MultilingualQuerySet [{'slug': 'pslug-1', 'overview': 'ov-project-1', 'text': 'text-project-1', 'title': 'project-title1'}]> <MultilingualQuerySet [{'slug': 'pslug-1', 'overview': '', 'text': '', 'title': ''}]> can help me why did this happen and what should I do? -
Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x053A7E68>
I'm trying to create a shopping cart api with django rest framework. I created my view and serializer and urls . but when I want to test my api with postman i have this error: Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x053A7E68>. I want to add a product to my cart. my authentication system is token authentication. I'll pass the token in the header of the request but still I have that error. i will share my code here: serializers class OrderItemSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() final_price = serializers.SerializerMethodField() class Meta: model = OrderItem fields = ( 'id', 'product', 'quantity', 'final_price' ) def get_product(self, obj): return ProductSerializer(obj.item).data def get_final_price(self, obj): return obj.get_final_price() class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() total = serializers.SerializerMethodField() class Meta: model = Order fields = ( 'id', 'order_items', 'total', 'coupon' ) def get_order_items(self, obj): return OrderItemSerializer(obj.products.all(), many=True).data def get_total(self, obj): return obj.get_total() #views: class AddToCartView(APIView): def post(self, request, *args, **kwargs): slug = request.data.get('slug', None) if slug is None: return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST) product = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( product=product, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if … -
Django user information creation problem use User.objects.create_user() in the admin
I try to create user with user information like first name, last name, bio and hobby. But it show some problem on admin. On admin only show and save first name and last name but don’t show and save other field. myuser = User.objects.create_user(username,email,password) myuser.hobby = hobby myuser.first_name = fname myuser.last_name = lname myuser.bio = bio myuser.save() -
Django stops without any errors
I've set up a django echo server, used for internal uses only. because of this, I run the server with manage.py runserver & (yeh, I know, the development mode) with the & so it will keep running in the background. Lately the server always stops working without any notices or error messages. When I type jobs to see the current job, it status is Exit 247. Any idea why this happens? I looked online and no help. -
Show created and edited fields in Django admin form
I have this model class Volunteer(models.Model): STATUSES = ( ('Active', 'Active'), ('Paused', 'Paused'), ('Inactive', 'Inactive'), ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email_address = models.CharField(max_length=100, null=True, blank=True) picture = models.ImageField(null=True, blank=True) status = models.CharField(max_length=20, choices=STATUSES, default="Active") created = models.DateTimeField(auto_now_add=True, editable=False) edited = models.DateTimeField(auto_now=True, editable=False) And I register it like this class VolunteerAdmin(admin.ModelAdmin): fields = ('first_name', 'last_name', 'email_address', 'status', 'created', 'edited') list_display = ('first_name', 'last_name', 'email_address', 'status') list_editable = ('status',) list_filter = ('status',) search_fields = ('first_name', 'last_name') admin.site.register(Volunteer, VolunteerAdmin) I get an error because I have manually added the created and edited fields as I want to see them in the view/edit forms. I know that the user should not be able to change these so I set the attributes to editable=False for both. However, it throws an error. Any idea what I need to do to be able to display these two fields in my admin forms? This is my error: 'created' cannot be specified for Volunteer model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class VolunteerAdmin. Thanks for your help. -
How to make django settings file read the user model from inside a model folder instead of models.py folder
I am trying to separate the models for user from models.py to a user.py file inside model folder.The user.py is inside model folder in core app.The core app is installed in settings.py folder.Everything works fine when the User Model is in models.py.In my init.py file in models folder i have imported the model according to the docs from .user import * In my settings.py to use the custom user model i have the settings as AUTH_USER_MODEL = 'core.user' The user is the user.py file inside the model folder.When i do the migrations i get the error "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'core.user' that has not been installed Help appreciated from you experts.Did searched a lot here but couldnt get this.Help please -
Internal Server Error - Django 3.0 - python3.6 - mysqlclient1.4.6 - apache2.4
I try to set up a Django application but I faced these errors. I tried to fix it but It's not working. Please tell me some ideas for resolving. Thanks a lot. myproject.conf <VirtualHost *:80> ServerName myserver DocumentRoot /var/www/EtestOnline <Directory /var/www/EtestOnline/static> Require all granted </Directory> <Directory /var/www/EtestOnline/media> Require all granted </Directory> Alias /static /var/www/EtestOnline/static Alias /media /var/www/EtestOnline/media WSGIDaemonProcess myserver python-path=/var/EtestOnline/myenv:/var/www/EtestOnline/myenv/lib/python3.6/site-packages WSGIProcessGroup myserver WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/EtestOnline/EtestOnline/wsgi.py <Directory /var/www/EtestOnline/EtestOnline> Require all granted AllowOverride all Options FollowSymlinks <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog /var/log/httpd/error.log CustomLog /var/log/httpd/access.log combined </VirtualHost> wsgi.py import os,sys from django.core.wsgi import get_wsgi_application sys.path.append('/var/www/EtestOnline') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EtestOnline.settings') application = get_wsgi_application() error.log mod_wsgi (pid=13226): Target WSGI script '/var/www/EtestOnline/EtestOnline/wsgi.py' cannot be loaded as Python module. [Sat Jan 30 23:27:44.990735 2021] [wsgi:error] [pid 13226] [remote 14.169.251.249:55000] mod_wsgi (pid=13226): Exception occurred processing WSGI script '/var/www/EtestOnline/EtestOnline/wsgi.py'. [Sat Jan 30 23:27:44.990842 2021] [wsgi:error] [pid 13226] [remote 14.169.251.249:55000] Traceback (most recent call last): [Sat Jan 30 23:27:44.990876 2021] [wsgi:error] [pid 13226] [remote 14.169.251.249:55000] File "/var/www/EtestOnline/EtestOnline/wsgi.py", line 18, in [Sat Jan 30 23:27:44.990879 2021] [wsgi:error] [pid 13226] [remote 14.169.251.249:55000] application = get_wsgi_application() [Sat Jan 30 23:27:44.990884 2021] [wsgi:error] [pid 13226] [remote 14.169.251.249:55000] File "/var/www/EtestOnline/myenv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Sat Jan 30 23:27:44.990886 2021] [wsgi:error] [pid 13226] … -
Having trouble deploying my Django app on AWS
When I run "eb deploy" from the command line I get this: Uploading App/app-210130_162554.zip to S3. This may take a while. Upload Complete. 2021-01-30 16:25:55 INFO Environment update is starting. 2021-01-30 16:25:59 INFO Deploying new version to instance(s). 2021-01-30 16:26:06 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2021-01-30 16:26:09 ERROR [Instance: i-0527480e0c398a08d] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2021-01-30 16:26:09 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-01-30 16:26:10 ERROR Unsuccessful command execution on instance id(s) 'i-0527480e0c398a08d'. Aborting the operation. 2021-01-30 16:26:10 ERROR Failed to deploy application. My requirements.txt file is as follows (ive seen some people having issues with psycopg2 but even after removing that it still doesn't work): asgiref==3.3.1 Django==3.1.5 geojson==2.5.0 psycopg2==2.8.6 pytz==2020.5 sqlparse==0.4.1 And finally, this is the error I get from the aws website: Degraded - Command failed on all instances. - Incorrect application version found on all instances. Expected version "app-210130_132526" (deployment 1). Severe - Application update failed at 2021-01-30T16:26:06Z with … -
Requests to the Django API from React are not allowed
I was introduced to web development using React and Django. As a tutorial, I was creating a to-do application. When I sent an API request from React, it was marked as Not Allowed. However, when I send the same request from curl, it is allowed. It seems that the API side is not set up properly. The code in question is shown below. import React, { useState } from "react"; import {CustomModal} from "./components/Modal"; import axios from "axios"; function App() { const [isComplete, setComplete] = useState(true); const [modal, setModal] = useState(false); const [todoItems, setToDoItems] = useState([]); const handleSubmit = (item) => { setModal(!modal); if (item.id) { axios .put(`http://localhost:8000/api/todos/${item.id}/`, item) .then(res => refreshList); } else { axios .put(`http://localhost:8000/api/todos/`, item) .then(res => refreshList); } }; const handleDelete = (item) => { axios .post(`http://localhost:8000/api/todos/${item.id}`, item) .then(res => refreshList); }; const [Item, setItem] = useState({title: "", description: "", completed: false }); const createItem = () => { const item = { title: "", description: "", completed: false }; setItem(item); setModal(!modal); }; const editItem = ( item ) => { setItem(item); setModal(!modal); }; const refreshList = () => { axios .get("http://localhost:8000/api/todos/") .then(res => setToDoItems(res.data)) .catch(err => console.log(err)); }; const displayCompleted = (status) => { if … -
Accessing a database with a different programming language
I built an app in Django, and have a script I wrote in Java that I'd like to use on the data from the Postgres database. I understand I can simply run a raw SQL query with the data in Java, but would it be more efficient to create ORM models with Java to access and process the data? More generally, if I mainly use a database with one framework, but need to access the data with another language or outside of the framework, should I build models with an ORM or use raw SQL? -
How to generate and return CSV file from pandas to django views?
I have a pandas script that takes in a CSV file, does some pandas stuff on it, and returns a new CSV file(or a response if we want that). The thing is that I want to be able to get that file in my django views.py file to be able to save it to the "converted file" database table. In short, I want to be able to store that file in a variable similar to uploaded_file = request.FILES['upload-field] I've tried various methods like returning the response but that just returns a string instead of an actual file. Also, I should mention that all of this happens when the user POSTS the data (uploads a csv file) here's my views.py from .models import ConvertedDocument def uploadView(request): if(request.method == 'POST'): uploaded_file = request.FILES['upload_field'] generated_uid = get_random_string(16) generated_name = generated_uid+".csv" actual_name = uploaded_file.name # Block to save converted file converted_file = analysis(uploaded_file) converted_file.name = generated_name converted_document = ConvertedDocument() converted_document.file_uid = generated_uid converted_document.file_name = "converted_"+actual_name converted_document.file_size = converted_file.size converted_document.file_document = converted_file converted_document.uploaded_by = user converted_document.save() return redirect('upload') return render(request, 'functions/upload.html') here's the save block from my analysis function def analysis(file): upload_df = pd.read_csv (file) # pandas conversion code goes here... response = HttpResponse(content_type='text/csv') response['Content-Disposition'] … -
Bold fonts in the label of models.IntergerField()
I am trying to let subjects input an answer to the following question and then store the answer using Django: "Your partner players in the game caught on average of 20 fish. Now how many fish you want to catch in this round?" And I use the following code: q = models.IntegerField(label="Your partner players in the game caught on average of 20 fish. Now how many fish you want to catch in this round?", min=0, max=40) Is there any way to make the number "20" bold? -
RelatedObjectDoesNotExist at /login/ while running the server locally
I using One To One field in Django to save some extra information about user but even afte migrating i got the issue which i mentioned in title my models.py the issue I got issue while running server please help if you can -
My save function is not working - I am new to Jquery
This i my first time with using jquery and i am trying to save a reply but it gives a successful message but it not actually but i cant see the reply that the system says it saved - any help will be appreciated - thank u in advance $(document).ready(function(){ $(".reply_open_modal").click(function(){ var id=$(this).parents("tr").children("td:eq(0)").text(); var name=$(this).parents("tr").children("td:eq(2)").text(); $("#reply_id").val(id); $("#reply_name").text(name); }); I think this part of my system works but i am not sure and the purpose of this code is to send the reply message $(document).on("click","#reply_btn",function(){ $(this).attr("disabled","disabled") $(this).text("Sending Reply") var id=$("#reply_id").val(); var message=$("#reply_message").val(); $.ajax({ url:'{% url 'admin_message_replied' %}', type:'POST', data:{id:id,message:message}, }) .done(function(response){ if(response=="True"){ alert("Sent") } else{ alert("Not Sent") } location.reload() }) .fail(function(){ alert("Error in Sending Reply") }) }) }) This is the fuction that saves the reply into my database but it not working @csrf_exempt def admin_message_replied(request): reply_id=request.POST.get("id") reply_message=request.POST.get("reply_message") try: messages = SendmessageAdmin.objects.get(id=reply_id) messages.message_reply = reply_message messages.save() return HttpResponse("True") except: return HttpResponse("False")