Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I call a java script function from django html page?
Looking for help to call a java script function from a html page, I have no idea about java script. js function to be called window.purpose.postMessage({ type: 'collection' }, {accesstoken: '1234rr55r3'},'*'); my html page in which this js function needs to be called <!DOCTYPE html> <html> <head> <title>User Redirect</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body onload="document.frm1.submit()"> <form action="{{url}}" name="frm1" method="post"> <p>Please wait.......</p> <input type="hidden" name="customerName" value="{{postData.customerName}}" /> <input type="hidden" name="customerEmail" value="{{postData.customerEmail}}" /> <input type="hidden" name="customerPhone" value="{{postData.customerPhone}}" /> </form> </body> </html> -
I have getting a problem in django url when I am at url ...abc/pqr and I click on xyz than It is not getting to the ...xyz but ...abc/xyz
I am new to django and on this plateform so for now I dont know how to post a question here, but is someone see this please help. I am getting a problem in my project of college management system. I have try to add a assignment submition functionality in my project. In which a student will click on a assignment created by teacher which will land him to a page either submition page of assignment or if he already submitted that assignment than update or only showing information about that. ***this is my url file.*** urlpatterns = [... path('studentattendancereport', studentviews.student_attendance_report, name='studentattendancereport'), path('fetchstudentattendance', studentviews.fetch_student_attendance, name='fetchstudentattendance'), path('applyforleavestudent', studentviews.applyforleave, name='applyforleavestudent'), path('marksreportstudent', studentviews.marksreportstudent, name='marksreportstudent'), path('assignment', studentviews.assignments, name='assignment'), path('assignmentupload/<int:id>', studentviews.assignment_upload, name='assignmentupload'), ] ***this is my views.py*** def assignments(request): subject = Subject.objects.filter(course=Student.objects.get(admin=request.user.id).course) assignments = [] for s in subject: for a in Assignment.objects.filter(subject_id=s.id): assignments.append(a) context = {'assignments': assignments} return render(request, 'cmsapp/student/assignments.html', context) def assignment_upload(request, id): if request.method == 'POST': student_id = Student.objects.get(admin=request.user.id) assignment = Assignment.objects.get(id=id) assignment_file = request.FILES['assignment'] try: Student_Assignment.objects.create(assignment_id=assignment, student_id=student_id, document=assignment_file) messages.success(request, 'Assignment is submited successfully.') return redirect('assignment') except: messages.error(request, 'There is some problem, Please try again later.') return redirect('assignment') else: assignment = Assignment.objects.get(id=id) student_id = Student.objects.get(admin=request.user.id) assignment_report = Student_Assignment.objects.filter(assignment_id=assignment.id, student_id=student_id).first() if assignment_report: context … -
How to check if json data has empty value or not in django
I have created a CRUD application in Django. and want to know how I can check if the input JSON data is empty or not for example: I am getting a JSON input dictionary as {'firstname':'abc','lastname':'xyz','username':'abc@123','email':'abc@abc.com'} I want to check if username is not empty and email is not empty. I don't want a required field in model but to handle the JSON data. If the JSON input is not valid i.e if username and email is valid then save the data into database else give a warning 400. -
how to fix Pylance missingImports? cannot import my app.How to add extra paths in settings.json?
image image2 I cannot import my "todolist_app" in my "urls.py", I get the message "Import "todolist_app" could not be resolved Pylance(reportMissingImports)" the code in urls.py is from todolist_app import views from django.contrib import admin from django.urls import path urlpatterns = [ path('/', views.todolist, name='todolist') ] I don't know what the problem is. I'm new to coding. I tried to add path in settings.json { "python.pythonPath": "tmenv\\Scripts\\python.exe", "python.analysis.extraPaths": ["todolist_app","E:\Django Projects\Django_projects\\taskmate\\todolist_app"] } and I get an error "Invalid escape character in string.jsonc(261)" -
Django unable to send email behind nginx proxy
My django project sends email verification correctly till its not put behind nginx proxy, when i add a nginx proxy i am unable to send email, it sometimes sends as well sometimes it doesnt. it doesnt show any error in console Nginx config: upstream django { server unix://ucurs/ucurs.sock; # for a file socket } # configuration of the server server { # the port your site will be served on listen 7000; # the domain name it will serve for server_name 127.0.0.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /log { access_log off; error_log off; uwsgi_pass django; include /ucurs/uwsgi_params; } # Django media location /media { alias /ucurs/media; # your Django project's media files - amend as required } location /static { alias /ucurs/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /ucurs/uwsgi_params; # the uwsgi_params file you installed } } Django library used for sending email : https://pypi.org/project/django-email-verification/ Django email config EMAIL_FROM_ADDRESS = 'noreply@ucurs.com' EMAIL_MAIL_SUBJECT = 'Confirm your email' EMAIL_MAIL_HTML = 'mail_body.html' EMAIL_MAIL_PLAIN = 'mail_body.txt' EMAIL_TOKEN_LIFE … -
How can i get the id related to specfifc user in django
I am trying to get the saloon id related to specific employee. After the login employee can add the service, but my filter query show the error "Field 'id' expected a number but got <bound method MultiValueDict.get of <QueryDict: {}>>." i don't know how can i get the saloon id Model.py class SaloonRegister(models.Model): saloon_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() is_active = models.BooleanField(default=False) class SignUp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) contact_no = models.BigIntegerField() class Men(models.Model): saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Service = models.CharField(max_length=30) price = models.BigIntegerField() View.py class MenView(TemplateView): template_name = 'men.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): saloonId = SaloonRegister.objects.filter(signup__user__signup__saloon=self.request.GET.get) try: men = Men( saloon_id=saloonId, user_id=request.user, Service=self.request.POST.get('service'), price=self.request.POST.get('price') ) men.save() return redirect('saloonMenu') except Exception as e: return HttpResponse('failed{}'.format(e)) -
Django-Vue app: allow access from certain PCs only
I have a Django-DRF (backend) and Vue.js(frontend) web application. This application is for our company only and I want to allow access from certain PCs only. There are no static IPs, so I cant use a whilelist of IPs. What is the most appropriate solution in this case? -
how to delete objects from DB and Django API view with Javascript (Django REST Framework)
I'm using Django as backend, PostgresSQL as DB , and HTML, CSS, Javascript for frontend. I am using Djnago Rest Framework to show all the product in Cart and now I got stuck on to delete those specific product. I'm using Javascript to show all the detail of the product which is selected by user. Here is the code: views.py @api_view(['GET']) def showproduct(request): if request.method == 'GET': result = CartProduct.objects.all() serialize = productserializers(result, many = True) return Response(serialize.data) and now the javascript code which I'm calling the Django API index.html <script> $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/index/showdata/', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td style="font-style:bold">'+data[i].name+'</td><td style="font-style:bold">'+data[i].price+'</td><td><a href='+data[i].link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><a href="" class="btn btn-outline-danger"><i class="fas fa-trash"></i></a></td></tr>'); $("#table").append(row); } } }); }); </script> Now above code in index.html, there is a trash button where I want to add code to delete object from Django api and DB. How to do that? -
data given in the Ajax is not reaching in the views.py file and hence alert function is not working
I tried to reset password using Ajax in Django.For that, firstly I took email id from input box using a function and send it to views.py file using Ajax.In views.py file,there is a code for receiving email-id using GET method and check whether the email-id is available or not in the table.If available send the email-id back to html file using HttpResponse and display it using alert function.But it does not work properly.Can anyone suggest a solution for this. HTML file : <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>Index Page</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="{% static 'styles/style.css' %}" rel="stylesheet"/> <script> function getpass(){ let username=$("#uname").val() $.ajax({ url : "{% url 'passwordreset' %}", type : "GET", data : {username : username}, success :function(data){ alert(data); } }) } </script> </head> <body> <section class="sflog" id="sflog"> <div class="container-fluid"> <div class="row"> <div class="col-12" id="std"> <form method="GET" action=""> {%csrf_token%} <center> <h3>Password <span>Reset</span></h3><br><br> </center> <div id="result"></div> <label style="color:white;padding-left:13%;">Enter Your Username</label> <center> <input type="text" id="uname" name="username" placeholder="Username" required><br> </center> <button type="submit" style="margin-left:12%;" onclick="getpass()" name="login">Submit</button><br><br><br><br> </form> </div> </div> </div> </section> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> urls.py from django.urls import path from . import views … -
gunicorn errors :gunicorn.service: Failed with result 'exit-code' and gunicorn.socket: Failed with result 'service-start-limit-hit'
As i am following through the tutorial of https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 gunicorn is not running when i used the command sudo systemctl status gunicorn my gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=developer Group=www-data WorkingDirectory=/home/developer/myprojectdir ExecStart=/home/developer/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bharathwajan.wsgi:application [Install] WantedBy=multi-user.target error comes when i try to check the status of gunicorn by the command sudo systemctl status gunicorn Error: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2021-06-04 03:53:42 UTC; 48min ago TriggeredBy: ● gunicorn.socket Main PID: 51351 (code=exited, status=1/FAILURE) Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: self.stop() Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: File "/home/developer/myprojectdir/myprojectenv/lib/python3.8/site-packages/gunicorn/arbiter.py> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: time.sleep(0.1) Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: File "/home/developer/myprojectdir/myprojectenv/lib/python3.8/site-packages/gunicorn/arbiter.py> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: self.reap_workers() Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: File "/home/developer/myprojectdir/myprojectenv/lib/python3.8/site-packages/gunicorn/arbiter.py> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.service: Failed with result 'exit-code'. lines 1-16/16 (END) when i tried sudo journelctl -u gunicorn.socket Logs begin at … -
Reloading a <div> element in Django but no refresh happening
I'm adding objects to my array list from a bar code scanner. The data is added after every scan of the barcode scanner it depends on how fast the user is in scanning. To display this data I have created a page. I don't want the whole page to refresh but that specific div that should display the scanned codes. This is what I have done so far urls.py path('status', include('detect_barcodes.urls')), views.py: @ms_identity_web.login_required def detect(request): stream = CameraStream() success, frame = stream.camera.read() if success: status = True else: status = False bar_codes = stream.used_codes data = (",\n".join(bar_codes)) return render(request, 'detect_barcodes/detect.html', context={'data': data, 'cam_status': status}) template file(detect.html):(I want to auto-refresh just the div with id="container") <div class="main-wrap"> <div class="container"> {% if cam_status %} <img src="{% url 'camera_feed' %}" style="width: 640px; height: 480px;"/> {% else %} <h3>Camera stream status: Camera is either not accessible or busy</h3> <h5>Things to check:</h5> <ul class="text-right list-inline"> <li>USB connection?</li> <li>Camera number in your .env file?</li> <li>Camera is already in use?</li> </ul> {% endif %} </div> <div class="container" id="container"> <form action="/submit/" method="post"> {% csrf_token %} Fill the Detail: <br/> <textarea id="description" rows="17" cols="90" name="description" class="myForm"> {{ data }} </textarea> <input type="submit" value="submit"/> </form> </div> </div> When I run … -
django-login-required middleware giving type error
In my django project I am trying to use the django-login-required-middleware. Upon running the server, I get the following error message: TypeError at / 'bool' object is not callable Traceback (most recent call last): File "/home/krishnan/anaconda3/envs/django_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/krishnan/anaconda3/envs/django_env/lib/python3.8/site-packages/login_required/middleware.py", line 26, in __call__ is_authenticated = request.user.is_authenticated() Exception Type: TypeError at / Exception Value: 'bool' object is not callable When I go to line 26 of the file site_packages/login_required/middleware.py, I see the following code: # Django v2 now has request.user.is_authenticated as a boolean instead # of a function that returns a boolean if django.VERSION[0] == 2: is_authenticated = request.user.is_authenticated else: is_authenticated = request.user.is_authenticated() I am using Django 3.1.6. I installed the middleware on 04 June 2021 with pip as instructed in the pypi page, and I presume it is the latest version(the middleware.py file does not show version info). As per the pypi page the middleware version is 0.6.1 and supports Django 3.0 also. But from the above code snippet, it would seem that the middleware code checks only for Django version 2 to use the is_authenticated property instead of the is_authenticated() function, and could be the reason for the error. Am I correct? Or … -
Celery Argument Passed Incorrectly
When I was trying to pass a string as an argument into my celery file, this error occurred: celery.beat.SchedulingError: Couldn't apply scheduled task add-every-10-seconds: get_data() takes 1 positional argument but 138 were given However, I can't quite figure out why this means -- I passed in the argument as a string, but somehow, Celery converts it into a char array or something. |-- data |-- tasks.py |-- nttracker |-- celery.py |-- manage.py nttracker\celery.py from __future__ import absolute_import app = Celery('nttracker', broker='amqp://', backend='rpc://', include=['nttracker.tasks']) app.autodiscover_tasks() app.conf.update( timezone = "Asia/Taipei", result_backend = 'django-db', broker_url = 'redis://127.0.0.1:6379', cache_backend = 'default', beat_schedule = { 'test': { 'task': 'data.tasks.get_data', 'schedule': 10.0, 'args': "https://gist.githubusercontent.com/crimsonpython24/8a42e1c7226b73d59dcb2447fa961caa/raw/57441c0912cf51695b113745052c4829459dec02/test.json" }, } ) if __name__ == '__main__': app.start() data\celery.py from __future__ import absolute_import import django django.setup() import requests from celery import Celery from celery.schedules import crontab app = Celery() @app.task def get_data(url): r = requests.get(url=url) data = r.json() print(data) Can anyone please help? Many thanks in advance. -
Going through in a loop with random float values via next and previous button?
my model: class Comics(models.Model): comic_english_name = models.CharField(unique=True, max_length=250, verbose_name='English Name') class Comic_banks(models.Model): comic_english_name = models.ForeignKey(Comics, on_delete=models.DO_NOTHING) comic_chapter = models.FloatField(verbose_name='Comic Chapter No.') my view: def chapter(request, myid, chid): comic = get_object_or_404(Comics, id=myid) # passed current comic chapter_max = Comic_banks.objects.filter(comic_english_name=comic.id).aggregate(Max('comic_chapter')) #max or last chapter chapter_min = Comic_banks.objects.filter(comic_english_name=comic.id).aggregate(Min('comic_chapter')) # min or first chapter comicbank = Comic_banks.objects.filter(comic_english_name=comic.id, comic_chapter=chid) #chapter list with different comics my template code: {% load mathfilters %} <!-- Chapter link section Start --> <!-- Previous button Start --> <div class="flex-containerchapter"> {% for comicbank in comicbank %} {% if comicbank.comic_chapter <= chapter_min.comic_chapter__min %} <!-- if current chapter is below than First or minimum chapter then no previous button --> {% else %} <a class="btn but1" href='/comic/comicview/{{ comic.id }}/{{ comicbank.comic_chapter|floatformat:1|mul:10|sub:1|div:10}}/chapter'>Prev</a> <!-- it will subtract 0.1 in the previous value of chapter from chapter list --> {% endif %} {% endfor %} <!-- Previous button end --> <!-- Next button Start --> {% for comicbank in comicbank %} {% if comicbank.comic_chapter == m.comic_chapter__max %} <!-- if current chapter is above than last or maximum chapter then no next button --> {% else %} <a class="btn but1" href='/comic/comicview/{{ comic.id }}/{{ comicbank.comic_chapter|floatformat:1|mul:10|addition:1|div:10}}/chapter'>Prev</a> <!-- it will add 0.1 in the next value of chapter from chapter list … -
Display images in visual studio with D jungo and html
im trying display pictures on my html page using D jungo but its not displaying it show like this I add this code in the setting STATIC_URL = '/static/' STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static'])) MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR, 'media') and this at the end of url ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i have html page and i wrote image code like this <img src="images/offer.jpg" alt="" /> and this is my files hope I find solution here -
I want to display only the sentences of the passed id on the screen
Template Language question. I want to pass the ID of the sentence I want to the url and display only the sentence of the passed ID on the screen. url: path('sentenceCard/<str:listName>/<int:listId>/', views.sentenceCard, name='sentenceCard') views.py: def sentenceCard(request, listName, listId): sentence = Sentence.objects.filter(Classification=listName) return render(request, 'english_note/sentenceCard.html', {'sentences':sentence, 'listId': listId}) html: <a href='#'>{{sentences.0.korean_sentence}}<br> <a href='#'>{{sentences.1.korean_sentence}}<br> Variables in Template Variables? like this? {{sentences.listId.korean_sentence}} -
Celery wont run when initiated by supervisor on aws elasticbeanstalk
I am attempting to daemonize celery beat and worker. I have no troubles running celery or beat when I ssh into my Elastic Beanstalk instance and do the following steps: cd /opt/python/current/app /opt/python/run/venv/bin/celery -A myDjangoApp beat --loglevel=INFO /opt/python/run/venv/bin/celery -A myDjangoApp beat --loglevel=INFO Tasks are scheduled and able to execute with ease. However when I run the exact same commands with supervisor I am getting an uniformative error. From looking at supervisorctl status I see the process runs for a few seconds then fails. Upon further examination the the log files show me the following error: File "/opt/python/run/venv/bin/celery", line 11, in <module> sys.exit(main()) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/opt/python/run/venv/local/lib/python3.6/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/click/core.py", line 760, in main _verify_python3_env() File "/opt/python/run/venv/local/lib/python3.6/site-packages/click/_unicodefun.py", line 130, in _verify_python3_env " mitigation steps.{}".format(extra) RuntimeError: Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/python3/ for mitigation steps. Listed below are my supervisor.conf and celery.sh(activates virtualenvironment and runs celery) files. Following is my supervisor.conf file. [unix_http_server] file=/opt/python/run/supervisor.sock ; (the path to the socket file) chmod=0777 ; socket file mode (default 0700) ;chown=nobody:nogroup … -
Django - view available reservation dates based on occurrence of the Event
consider we have a class that occurs 3 days a week ex: Mon,Wed,Fri from 14:00 to 18:00. I want to show only Mon,Wed,Fri and the corresponding dates - consider student wants to reserve after month, he should see the day and the date of that day. |Mon|Wed|THU|Mon|Wed|THU| |:----|:------| :-----|:----|:------| :-----| |7JUN|9JUN|10JUN|14JUN|16JUN|17JUN| I have django-recurrence and I can get the occurrence time i.e Mon,Wed,Fri How can I tie it with a date for future reservation ? Thanks in advance. -
Django admin problem with changed table column's name
I'm new to Django. Everything was fine before, but now that I've changed the name of some columns in the table, when I want to check all data inside the admin panel, It returns error. It seems that the admin still expect the previous column's names. And also the name of the models has an extra "s" at the end! For example, one of the previous column's name was "note_text" which I've changed to "text". So, what should I do now? -
Aggregating change list rows in Django using values
I'm trying to modify my model's changelist so that the user can select different filters which will sum specific fields in the model, grouping by different time frames (week, month, year). I have created a custom SimpleListFilter which correctly performs the aggregation. The problem is that it uses the values method which returns dict objects instead of my model, causing various errors. My model: class UsageReport(models.Model): install = models.ForeignKey( Installation, on_delete=models.CASCADE, help_text='The install this report is associated with' ) date = models.DateField( null=False, blank=False, default=None, help_text='The day this report\'s data is compiled for' ) players_count = models.PositiveIntegerField( null=False, blank=False, default=0, help_text='The number of new players created' ) captures_count = models.PositiveIntegerField( null=False, blank=False, default=0, help_text='The number of new captures created' ) created_at = models.DateTimeField(auto_now_add=True, null=True) My custom list filter: class DateGroupFilter(SimpleListFilter): title = 'Group By' parameter_name = 'group_by_date' def lookups(self, request, model_admin): return ( ('week', 'Week'), ('month', 'Month'), ('year', 'Year') ) def queryset(self, request, queryset): if self.value() == 'week': return queryset.annotate(week=ExtractWeek('date')).values('install', 'week').annotate( sum_players=Sum('players_count')).annotate(sum_captures=Sum('captures_count')) if self.value() == 'month': return queryset.annotate(month=ExtractMonth('date')).values('install', 'month').annotate( sum_players=Sum('players_count')).annotate(sum_captures=Sum('captures_count')) if self.value() == 'year': return queryset.annotate(year=ExtractYear('date')).values('install', 'year').annotate( sum_players=Sum('players_count')).annotate(sum_captures=Sum('captures_count')) Since each filter option returns slightly different fields (week, month, year) I tried to code a work-around which overrides the get_list_display method … -
Django - Traceback (most recent call last): File "C:\Users\Usuario\Desktop\Tinkuy\T2\T\manage.py", line 21, in <module> main()
I would like you to help me with this problem I have when opening my project in Django, I've been trying anyway and I can't find what the problem would be to run it correctly. I understand that the Django version does not influence much and I use an advanced Python version Traceback (most recent call last): File "C:\Users\Usuario\Desktop\Tinkuy\T2\T\manage.py", line 21, in <module> main() File "C:\Users\Usuario\Desktop\Tinkuy\T2\T\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'admin_interface' PS C:\Users\Usuario\Desktop\Tinkuy\T2\T> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Usuario\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise … -
Queryset en Django
soy nuevo en Django y quería saber si hay alguna forma de hacer filtrados de querys con multiples valores de un mismo campo de mi modelo? Follow es mi modelo donde guardo los pk de los usuarios follower y following; la consulta follows me devuelve todos los follows en los que yo figuro como follower para después poder acceder al atributo following. Después hago un lista de los pk de following para filtrar los posts hechos por usuarios con los pk de mi lista de following. Sé que entregar un lista como parametro da error, pero la plasmo para intentar explicar lo que quiero hacer que es filtrar todos los post de los usuarios que sigo. Dejo la vista que lista los posts: class PostsFeedView(LoginRequiredMixin, ListView): """Return all posts published by following.""" template_name = "posts/feed.html" ordering = ("-created") paginate_by = 30 context_object_name = "posts" def get_queryset(self): user = self.request.user follows = Follow.objects.filter(follower=user.pk) following = [] for follow in follows: following.append(follow.following) posts = Post.objects.filter(user__id=following) return posts -
How to create a product filter, when products are just foreigns keys in attribute class? (Django Ecommerce)
I'm trying to create a product filter that filters on product attributes (like this example), but I have a couple of issues: The attributes of my products are defined indirectly as a foreign key in a ProductAttributesValue class, which connects a product and an attribute key to an attribute value, i.e.: class ProductAttributesValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(ProductAttributes, on_delete=models.RESTRICT) value = models.CharField( verbose_name = "value", max_length = 255 ) For now, I simply show all associated products on each product category page. Meaning attributes aren't used, yet. How do I, on the product category pages, create a filter on the product attributes, when they aren't directly defined in the Product class as a model field? Is this even the optimal way of setting up product attributes? (Categories are set up using MPTT, and I found this attribute implementation through online guides). An important note is that I want product filtering to be "hard URLs", meaning /red/ instead of ?color=red. This one requires some sort of hierarchy in the filtering, as there must be no duplicate URLs (e.g: /red/hugo-boss and /hugo-boss/red). Thanks! -
How can I pass modelformset_factory validation in Django?
I have 2 two models with a one-to-one relation as follow. class Kategori(models.Model): urun = models.CharField(db_column='Urun', max_length=255, blank=True, null=True) # Field name made lowercase. kategori = models.CharField(db_column='Kategori', max_length=255, blank=True, null=True) # Field name made lowercase. ust_kategori = models.CharField(db_column='Ust_Kategori', max_length=255, blank=True, null=True) # Field name made lowercase. urun_adi = models.CharField(db_column='URUN_ADI', max_length=255, blank=True, null=True) # Field name made lowercase. ur_id = models.CharField(db_column='UR_ID', max_length=255, blank=True, null=True) # Field name made lowercase. marka = models.CharField(db_column='MARKA', max_length=255, blank=True, null=True) # Field name made lowercase. cesidi = models.CharField(db_column='CESIDI', max_length=255, blank=True, null=True) # Field name made lowercase. miktar = models.FloatField(db_column='MIKTAR', blank=True, null=True) # Field name made lowercase. birim = models.CharField(db_column='BIRIM', max_length=255, blank=True, null=True) # Field name made lowercase. adet = models.FloatField(db_column='ADET', blank=True, null=True) # Field name made lowercase. class categoryprob(models.Model): urun = models.OneToOneField(Kategori,on_delete=models.CASCADE,related_name="prob") kategori = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. ust_kategori = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. urun_adi = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. marka = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. cesidi = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. miktar = models.FloatField(blank=True, null=True) # Field name made lowercase. birim = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase. adet = models.FloatField(blank=True, null=True) # … -
Recommendations for an AutoComplete library for Django Taggit
Aside of another post I created earlier this evening relating to the configuation of Django AutoComplete Light, I just wanted to ask - What are the most recommended AutoComplete libraries out there which work with the latest version of Django? A lot of the libraries I have come across seem to be no longer maintained or are 6+ years old. I am tempted currently to continue with implementing Django AutoComplete Light although, I thought I would check here first to see if there are any other alternatives which exist? If anyone could provide me with any tips with which is the most favourable library (which works with the latest version of Django, that would be great!) Ideally, I am wanting the Select2 and tag bubbles similar to the Tagulous AutoComplete library. All suggestions are welcome. Thanks!