Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
How can i deploy Django to Heroku with static files
I want to publish my django application on heroku, but I am getting the error I mentioned. I researched and tried many things about it, but I could not get a positive result. remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'css/semantic.min.css' failed! remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 138, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'css/themes/default/assets/images/flags.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f96f75bdf90>. remote: The CSS file 'css/semantic.min.css' references a file which could not be found: remote: css/themes/default/assets/images/flags.png remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: … -
Не отображаются поля формы django в модальном окне bootstrap
При создании формы отображаются все поля по прямой ссылке. При связывании формы с модальным окном бутстрап(5 без использования jquery) поля не отображаются. Модальное окно открывается, но полей формы там нет. Мой первый проект на django. Возможно не корректно передаю параметры во view, либо что-то ещё не верно. Вот код модели из файла models.py: class Order(models.Model): name = models.CharField(max_length=50, verbose_name='Имя') phone = models.IntegerField(verbose_name='Номер телефона') chosen_service = models.CharField(max_length=255, verbose_name='Выбранная услуга') ordered_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата отправки') agree_policy = models.BooleanField(verbose_name='Согласен с Политикой конфиденциальности') def __str__(self): return self.name class Meta: verbose_name = 'Заявка(у)' verbose_name_plural = 'Заявки' ordering = ['-ordered_at'] Код формы из файла forms.py: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['name', 'phone', 'agree_policy', 'chosen_service'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'agree_policy': forms.CheckboxInput(attrs={'class': 'form-check-input', 'id': 'flexCheckChecked', 'checked': 'checked'}), 'chosen_service': forms.HiddenInput(attrs={'id': 'chosen_service'}), } Код из view.py: def get_order(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect(request.path) else: form = OrderForm() return render(request, 'blog/form.html', {'form': form}) def service_page(request, slug): advantage = Advantage.objects.all().order_by('id') detailed_service = DetailedService.objects.all().order_by('id') slug = Service.objects.values('slug') options_detailed_service = OptionsForDetailedService.objects.all().order_by('id') response_data = { 'advantage': advantage, 'detailed_service': detailed_service, 'options_detailed_service': options_detailed_service, 'slug': slug, # 'get_order': get_order, } return render(request, 'blog/service.html', response_data) Код из urls.py: urlpatterns = [ path('', main_page, … -
How to compare DateTimeFueld with Date in Django filter funtion?
In my django app I have a MessageModel with a DateTimeField "send_date". I want to filter the messages to get all messages send a certain day (Date). How do I compare the DateTimeField with a Date to get all messages send within that day. I have try with query_result= MessageLogModel.objects.filter(received_date=myDate) but it does not show the correct results. Here is the deffinition of the Model class MessageModel(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', verbose_name=_('Destinatario'), editable=False, null=True, blank=True) subject = models.CharField(verbose_name=_("Asunto"),max_length=50) send_date = models.DateTimeField(verbose_name=_("Fecha de envío") ,auto_now_add=True) message_body = models.TextField(verbose_name=_("Mensaje")) class Meta: db_table = 'riesgo_message' managed = True verbose_name = _("Mensaje") verbose_name_plural = _("Mensajes") def __str__(self): return self.subject -
TemplateDoesNotExist at /products/login
how can i fix this PLZ enter image description here i want to delete this directory in make it instead of what you see in image to make this looking in this one C:\Users\Katsuker\PycharmProjects\first\templates 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', ], }, }, ] -
How to split a long line in a Django template needed for formatting?
I have a line like this in a Django template: {{ some_prefix }}{% if obj.obj_type == A_LONG_CONSTANT %}1{% elif obj.obj_type == A_LONG_CONSTANT %}2{% endif %}{{some_suffix}}: where some_prefix might be a ( or something longer, and some_suffix might be a ) or maybe even empty. I don't know how to break this up, since putting any whitespace in such a template make it look different in a browser. Think "( hi )" instead of "(hi)". Any suggestions? You might say, "Put this in python, not Django templates." However, I'm not sure how to split it up into a tag either. It depends on the template context. I see this question, but that's just renaming variable names, which might make this thing even more heinous. I think there's probably nothing to do. -
Strange Error with Django oauth-toolkit and Azure App Service. Returns 401 {"detail":"Error decoding token."} when attempting to authenticate token
Hi I am deploying an app to Azure App Service using Django Rest Framework with OAuth2 authentication handled by django-oauth-toolkit (https://github.com/jazzband/django-oauth-toolkit). Recently when trying to connect to my React frontend I have found out that I cannot successfully authorize despite having an access token. When I make a the following API call (as suggested by the documentation): curl 'http://exampleurl.azurewebsites.net/endpoint/' -H 'authorization:Bearer <sampletoken>' I get the following response: {"detail":"Error decoding token."} I cannot recreate this error locally nor can I find any information about this error anywhere online. I even searched the repository for the error to see if I could find what triggers it, unfortunately no luck. Has anyone else ever experience this or can give me some insight on what potentially occurred in my deployment to cause this? I also deleted out my old deployment and even app service to completely start from scratch and the problem persisted.