Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Update Button on AJAX Submit?
I have a follow button that allows a user to follow and or unfollow an object. The button value changes depending on whether the user is following or unfollowing. How do I update the button after the click event without refreshing the entire page? HTML Template {% if trending_store in store_connection_user %} <a href="" value="add" data-catid="{{ trending_store.pk }}" class="followBtn btn btn-primary" action_type="remove">Remove Store</a> {% else %} <a href="" value="add" data-catid="{{ trending_store.pk }}" class="followBtn btn btn-primary" action_type="add">Follow Store</a> {% endif %} jQuery {% block jquery %} $(".followBtn").click(function (event) { event.preventDefault(); var this_ = $(this); var storepk = this_.attr('data-catid'); var action_type = this_.attr('action_type'); $.ajax({ type: "POST", url: "{% url 'portal:store_change_connections' %}", data: { store_pk: storepk, action: action_type, csrfmiddlewaretoken: '{{ csrf_token }}', }, success: function (data) { $('.followBtn') console.log(data) } }); }); {% endblock jquery %} views.py def StoreChangeConnectionsAjax(request): if request.method == 'POST': store_pk = request.POST['store_pk'] action = request.POST['action'] print(store_pk) print(action) if action == 'add': store_connection_ajax = portal_models.Store.objects.get(pk=store_pk) portal_models.FollowStore.add_connection(request.user, store_connection_ajax) return HttpResponse('Success!') if action == 'remove': store_connection_ajax = portal_models.Store.objects.get(pk=store_pk) portal_models.FollowStore.remove_connection(request.user, store_connection_ajax) return HttpResponse('Success!') -
How to get object by ID and show it through the slug in the URL?
I have an application and I want to update users but in the URL the name of user should appear instead of the ID. If I search for the slug being the slug created from the name, many users will appear and I will not be able to send the object because it will present an error. In the model I have: slug = models.SlugField(max_length=40) def save(self, *args, **kwargs): self.slug = slugify(self.first_name) super(User, self).save(*args, **kwargs) And in the view I have: def update(request, id, slug): instance = get_object_or_404(User, id=id) form = MyForm(request.POST or None, instance=instance) if form.is_valid(): form.save() return redirect("local") return render(request, "update.html",{"form": form}) The template has: <a href="{% url 'update_user' user.id user.slug %}"> update </a> And urls.py has: path('update/<slug>', update, name='update_user') But I get the following error: Reverse for 'update_user' with arguments '(1, '1')' not found. 1 pattern(s) But in the URL it should appear with the slug, example: /update/Richard Instead of a combination of the two fields. How can I search for the id and show it in the URL by the slug? -
uWSGI "SIGNAL QUEUE IS FULL" errors
I have a Django application running with uWSGI. Sometimes, when restarting the uWSGI service, I get a bunch of *** SIGNAL QUEUE IS FULL: buffer size 212992 bytes (you can tune it with --signal-bufsize) *** errors. When that happens, I'm unable to access the Django app. Restarting uWSGI again usually works. Any ideas what happening here? On startup of my application, I have a bunch of crons and timers that are initialized, like: @uwsgidecorators.timer(30) def send_queued_mail(*args, **kwargs): ... The full output of the wsgi process is below: chdir() to /etc/uwsgi/vassals closing all non-uwsgi socket fds > 2 (max_fd = 1024)... found fd 3 mapped to socket 0 (/var/run/uwsgi/MY_APP.sock) running /usr/local/bin/uwsgi *** has_emperor mode detected (fd: 7) *** [uWSGI] getting INI configuration from MY_APP.ini *** Starting uWSGI 2.0.17.1 (64bit) on [Thu Feb 6 22:22:18 2020] *** compiled with version: 4.8.4 on 07 August 2018 17:29:43 os: Linux-4.2.0-42-generic #49~14.04.1-Ubuntu SMP Wed Jun 29 20:22:11 UTC 2016 nodename: spuzzum machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 4 current working directory: /etc/uwsgi/vassals detected binary path: /usr/local/bin/uwsgi uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) … -
Is there a simple way of passing FileObject urls in DJango to JavaScript function (JWplayer setup for videos)?
I am pretty new at using DJango and have been trying to build a simple site where users are able to upload videos for "best video contests". Under the contest page users will be able to play videos uploaded by other users. However, I am having trouble getting passing the video url to the JWPlayer setup function so it is able to play the video. The part of my template that is trying to accomplish this is: <table> <tr> <th>Video</th> <th>Descripcion</th> </tr> {% for video in videos %} <tr> <td> <div id="myPlayer" style="width:400px"></div> <script type="text/JavaScript"> jwplayer("myPlayer").setup({ file: "{{ video.Videos.url }}"", width: "100%", height: "100%",}); </script> </td> <td>{{ video.Texto }} </td> </tr> {%endfor%} </table> If instead of the ""{{...}}" I type in the file url the video can be played normally, but with the brackets it gives me "This video file cannot be played. (Error Code: 102630)" which I understand basically means that the file could not be found. So it is not getting the url from the "{{...}}"", I made sure that it did return the correct url outside of the javascript. Is there a simple way I can get/pass that url to the javascript? Ideally there will be different … -
How to adding column to a model for the user that created/updated a record?
from django.contrib.auth.models import User class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,blank=True) class Meta: abstract = True class Model1(UpdateInfo): feild1 = models.Charfeild(max_length=50) feild2 = models.CharField(max_length=50) class Model2(UpdateInfo): feild1 = models.ForeignKey(Model1, on_delete=models.CASCADE) feild2 = models.CharField(max_length=50) How to add user column to model1 and model2. User indicates person who created the model. -
Model there should only be one instance of
I'm not sure if this is the best way of doing this but I've been doing my 'About us' page as follows. models.py class AboutUs(models.Model): content = TextField() class Meta: verbose_name_plural = "About Us" def __str__(self): return "About Us" views.py def about_view(request): context = { "title": "About Us", "about": AboutUs.objects.first(), } return render(request=request, template_name='main/about.html', context=context) about.html <p>{{about.content}}</p> Since there should only be one about us page this makes me wonder if this is what other devs would do. Another good example is contact info.. If I make a model like this: class Contact(models.Model): facebook = models.CharField(max_length=100) instagram = models.CharField(max_length=100) youtube = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) address = models.CharField(max_length=100) .. I could still have several instances of the Contact model which doesn't make sense. -
how can i save and return to same record on django?
I would like to create a new order and when i save it i would like that it return me to a page with the same order id, not index as following. def order_create(request): print(request.POST) order_number = request.GET['order_number'] date = request.GET['date'] client = request.GET['client'] order_details = order(order_number=order_number, date=date, client=client) order_details.save() return redirect('/') -
why can't access to django admin , the server quit immediately
i currently work on a project , i want to build it with django 3.0.2 python version 3.7, but after running the server python manage.py runserver it will quit immediately when i try to access the admin url without raise any error , and even i havn't do any changes in my new app ,and also tried django version 2x it worked as i expected . i tried to remove and reinstall django , but still give the same output , thanks for advice -
Samsung Internet 10.2 sending incorrect cookies
I'm seeing a lot of sessions in my Django app where the session key is much longer than it should. Investigating, I saw sessions recorded as realsessionkey,anothercookie=itsvalue (instead of just realsessionkey). In every instance, the browser was Samsung Internet 10.2 on Android 9. No other browsers are affected, so I think it's probably something on the browser side. Is there anything I can do on the server side to ensure these cookies are parsed propertly? I'm using bog-standard Django sessions middleware -
Я не могу создать проект в Django, что делать?
Я установил django версии 3 но когда создаю проект у меня создается только папка и вылазит такая ошибка: Traceback (most recent call last): File "/usr/local/bin/django-admin", line 11, in sys.exit(execute_from_command_line()) File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/startproject.py", line 34, in handle super(Command, self).handle('project', project_name, target, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/templates.py", line 162, in handle if new_path.endswith(extensions) or filename in extra_files: UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 11: ordinal not in range(128) enter image description here -
one "Key" is missing when I get data from table which field is of JSON type Django + Sqlalchemy + Postgres
I have one JSON field in my table of PostgreSQL. Which looks like the below SS. I am using django 2.2.4 with sqlalchemy and get data from the database. But I am getting this below data from the same database, same table and same field. {'filterable': True, 'active': True, 'value': 'S'}, {'filterable': True, 'active': True, 'value': 'M'}] As you can see "code" is not in the JSON which I get from the DB. I didn't do any operation on this JSON. What should I do for to solve this, Please sugest. -
Django/React - Static Main.js file with AWS hosting staticfiles
I'm creating an app with Django as the backend and React as the front-end. I already have the back-end built out, and now I'm trying to build out the React components. My problem is this- right now I have my static files hosted on AWS. So every time I make a change to a component, I need to run collectstatic through django in order for my Django template to read the updated Main.js file. Has anyone encountered this issue before? I am new to React, so I may be missing a very simple solution. Thanks!! -
Limit options of Django ManytoManyField
I have an app that has 3 models: Podcasts, Episodes, and Categories. Categories have a ForeignKey for Podcast: class Category(models.Model): ... podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) ... So, a podcast can have a bunch of associated categories. Each episode can be associated with a podcast's category. I've added that as a ManyToManyField: class Episode(models.Model): podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) ... The problem is, in the admin, and modelforms, the categories field shows a list of every category for every podcast, not just the ones associated to this podcast. How can I use limit_choices_to to only limit categories with the foreign key of the same podcast the episode is related to? I've tried the following, but obviously doesn't work because 'self' is not defined. categories = models.ManyToManyField(Category, limit_choices_to={'podcast': self.podcast}) I'd like to do this at the model level if possible so I dont have to add additional logic around the rest of the app. Thanks for any help! -
Execute .py file inside Django dir
I have a Django website that render a Dash app (dash is similar to flask), and inside my Django project i have an app folder and inside app folder is my .py file that contain my Dash app that works with "application/json" response. This file .py contain all pandas logic and dash logic that manipulate data onces user upload new file. The problem is: This .py file run only when I start server "Python manage.py runserver". How I can do to this .py be executed using a Django view. I tried to include: execfile(path) Also: f = open('/paths/file.py', 'r') v = f.read() eval(str(v)) But this not worked. There are another way to execute a .py file that are inside some Django dir? -
How to retrive comment_replies from table in django
I am doing the comment part of the blog API. I can't derive replies, but I could derive the comments. Python module: Django: class Comment(models.Model): author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey( 'self', related_name='reply', null=True, blank=True, on_delete=models.CASCADE) Above is the table and shows the comments that are stored using the Django Comment model code. My task: I have the id of the parent comment. And I have to derive the rest of the RED box. Anything is welcome: Idea, SQL script, or Django Query -
Dynamic views in Django ORM - best approach?
Some background I am considering rebuilding an existing Laravel website with Django. It's a website that allows sharing benchmark data from drone/UAV propulsion components. Some benchmarks are done while testing multiple motors and propellers at the same time, which means a battery would be under the load of multiple motors, but it also means the airflow from one propeller has an impact on the data captured on the other propeller. This means the data is physically coupled. Here is an example. Right now I am trying to structure this project to allow upcoming features, and to see if Django ORM is a good fit. Simplified Django models class Benchmark(models.Model): title = models.CharField() private = models.BooleanField(default=False) class AbstractComponent(models.Model): brand = models.CharField() name = models.CharField() class Meta: abstract = True class Motor(AbstractComponent): shaft_diameter_mm = models.FloatField() class Propeller(AbstractComponent): diameter_in = models.FloatField() class Battery(AbstractComponent): capacity_kwh = models.FloatField() class Powertrain(models.Model): benchmark = models.ForeignKey(Benchmark, on_delete=models.CASCADE, related_name='powertrains') motor = models.ForeignKey(Motor, on_delete=models.CASCADE) propeller = models.ForeignKey(Propeller, on_delete=models.CASCADE) battery = models.ForeignKey(Motor, on_delete=models.CASCADE) class DerivedDataManager(models.Manager): def get_queryset(self): return super().get_queryset()\ .annotate(electrical_power_w=F('voltage_v') * F('current_a'))\ .annotate(mechanical_power_w=F('torque_nm') * F('rotation_speed_rad_per_s'))\ .annotate(motor_efficiency=F('mechanical_power_w') / F('electrical_power_w')) class DataSample(models.Model): powertrain = models.ForeignKey(Powertrain, on_delete=models.CASCADE, related_name='data') time_s = models.FloatField() voltage_v = models.FloatField(blank=True, null=True) current_a = models.FloatField(blank=True, null=True) rotation_speed_rad_per_s = models.FloatField(blank=True, null=True) torque_nm … -
redirecting in a single ajax post request
i have been facing a really tough issue raised here To resummarize , i am attempting to allow users to select a few instances of a model , and use xhtml2pdf to render only the selected model dynamically. To do that , i use javascript to keep track of the instances that were clicked by the user and save it to an array. When the user has clicked finish , he would click the generate button which will take the array and send it via an AJAX POST request to my view that will render the pdf. Here is some of my code: my views def BomPdf(request): if request.is_ajax(): listy = request.POST.getlist('arr[]') trials = FormulationTrial.objects.filter(pk__in = listy) print(trials) print(listy) pk = request.POST.get('pk') data = { 'product' : ProductFormulation.objects.filter(formulation_id = pk)[0], 'trials' : FormulationTrial.objects.filter(pk__in = listy), 'item' : TrialItems.objects.filter(formulationTrial__productFormulation__formulation_id__contains = pk), 'itemdetails' : ItemDetails.objects.filter(itemdetail_id__in = TrialItems.objects.filter(formulationTrial__productFormulation__formulation_id__contains = pk).values_list('itemdetail', flat=True).distinct().order_by()), } pdf = render_to_pdf('rnd/bom_pdf.html', data) return HttpResponse(pdf , content_type='application/pdf') else: return JsonResponse({'status':'Fail', 'is_read':'not changed'}) my javascript function ajaxsender(clicked_id){ var b = clicked_id $.ajax({ url : "{% url 'bom-pdf'%}", method : "POST", async: false, data : { 'csrfmiddlewaretoken' : "{{ csrf_token }}", 'arr[]' : arr , 'pk' : b }, success : function(result) … -
Erro no vinculo do ManytoManyField
criei uma rotina aonde se cadastra um centro de custo. Esse centro de custo sao vinculados por meio de um ManyToManyField quando vou cadastrar o Usuário. Abaixo os models.py desses cadastro: models do usuário: class Usuario(models.Model): primeiro_nome = models.CharField(max_length=70) ultimo_nome = models.CharField(max_length=70) email = models.EmailField(max_length=100) user = models.OneToOneField(User, on_delete=models.PROTECT) centrodecusto_usuario = models.ManyToManyField(CentroDeCusto, blank=True) perfil_usuario = models.ForeignKey(Perfil, on_delete=models.PROTECT, null=True, blank=True) permissao_usuario = models.ForeignKey(Permissao, on_delete=models.PROTECT, null=True, blank=True) def get_absolute_url(self): return reverse('list_usuario') def __str__(self): return self.primeiro_nome E esse é o model do centro de custo: class CentroDeCusto(models.Model): numero_centro = models.CharField(max_length=70) nome_centro = models.CharField(max_length=70) centro_de_custo = models.CharField(max_length=70) user_respon = models.OneToOneField(User, on_delete=models.PROTECT) vinculo_natureza = models.ManyToManyField(NaturezaOrcamentaria) def get_absolute_url(self): return reverse('list_centrodecusto') def __str__(self): return self.centro_de_custo Depois disso criei um models aonde será cadastrado um orçamento. Esse orçamento é cadastrado informando o centro de custo, uma natureza orçamentária, a data e o valor. Conforme o Model abaixo: class CadastroOrcamento(models.Model): cc_cadastro_orcamento = models.ForeignKey(CentroDeCusto, on_delete=models.PROTECT, null=True, blank=True) no_cadastro_orcamento = models.ForeignKey(NaturezaOrcamentaria, on_delete=models.PROTECT, null=True, blank=True) valor_cadastro_orcamento = models.DecimalField(max_digits=10, decimal_places=2) data_cadastro_orcamento = models.DateField(null=True, blank=True) obs_cadastro_orcamento = models.CharField(max_length=1000) def get_absolute_url(self): return reverse('list_cadastro_orcamento') def __str__(self): return self.obs_cadastro_orcamento O que eu quero fazer: quando o usuário entrar para cadastrar o orçamento, aonde ele vai informar o centro de custo, so vai aparecer os centros de custo … -
Django. Categories and subcategories
I want to make a navigation through categories and subcategories in Django. smth like this: Food Vegetables Carrot Broccoli Tomatoes Fruits Apple Pear Beverages my models.py: class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(unique=True) category = models.ForeignKey('Category', on_delete=models.CASCADE) description = models.TextField(blank=True,null=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Product,self).save(*args, **kwargs) def get_absolute_url(self): return self.slug class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) parent = models.ForeignKey('self',blank=True, null=True ,related_name='child', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) my urls.py path('', ProductList, name='product-list1'), path('<category_slug>/', products_by_category, name='product-categories'), views.py def ProductList(request): products = Product.objects.all() products = products.order_by('-publish') categories = Category.objects.filter(parent__isnull=True) context = { 'products':products, 'categories':categories, } template = 'products/product_list.html' return render(request, template ,context) now I have this: 127.0.0.1:8000/products/last subcategory/product slug and I want to make 127.0.0.1:8000/products/category/subcategory/subsubcategory/.../product slug And how can I display all products that are in one category. For example all food Food Vegetables Carrot Broccoli Tomatoes Fruits Apple Pear Beverages -
Why i get this AttributeError when form is submitted
I'm having an error when I submit a form. When it loads this is the error I'm getting: 'list' object has no attribute 'imageuploader_profile @login_required def upload(request): PostFormSet = modelformset_factory(Image, fields=('image',), extra=2) formset = PostFormSet(request.POST or None,request.FILES or None) if request.method == "POST": print(request.FILES) if formset.is_valid(): post = formset.save(commit=False) post.imageuploader_profile = request.user post.save() for f in formset: try: file = Image( imageuploader_profile=post, image=f.cleaned_data['image'], image_caption=f.cleaned_data['image_caption'], tag_someone=f.cleaned_data['tag_someone'], ) file.save() except: break else: formset = PostFormSet(queryset=Image.objects.none()) return render(request, 'upload.html', {"formset": formset}) <form action="{% url 'site:upload' %}" method="post" enctype="multipart/form-data"> {%csrf_token%} {{ formset }} <button type="submit">Post</button> </form> -
Using firebird with django
I have two SQL tables with related data in them, but no key value to link the data in table A to the data in table B. I'd like to -
How to bulk_create objects with Many to Many Relationship in Django?
How to bulk_create Filmlist? Models.py class Film(models.Model): film= models.CharField(max_length=250) producer = models.CharField(max_length=250) class Filmlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) film = models.ForeignKey(Film, on_delete=models.CASCADE) -
DJanjgo Winerror 995?
I'm taking the DJango tutorials and using Pycharm. All seems good except on occasion I'll get: print(q) 2What's new? Unhandled exception in event loop: File "C:\Python38\lib\asyncio\proactor_events.py", line 768, in _loop_self_reading f.result() # may raise File "C:\Python38\lib\asyncio\windows_events.py", line 808, in _poll value = callback(transferred, key, ov) File "C:\Python38\lib\asyncio\windows_events.py", line 457, in finish_recv raise ConnectionResetError(*exc.args) Exception [WinError 995] The I/O operation has been aborted because of either a thread exit or an application request Press ENTER to continue... print(q) 2What's new? I'm using Pycharm 2019.3.3 and Python 3.8 on Win10. To resolve I run the same command again and there's no error. -
need help to calculate retirement year of staff
I am building HR app using python with django frame work, I am having issue to calculation retirement year of an employee, for example if an employee enters his/her date of birth let the system calculate his/her retirement year or how many years remaining to retire. staff retire at 60 years Am jetting this error: TypeError at /staffprofile/profile_entry/ unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime' Request Method: POST Request URL: http://0.0.0.0:8080/staffprofile/profile_entry/ Django Version: 1.8 Exception Type: TypeError Exception Value: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime' Exception Location: /home/bakceesay/djangoapps/NAO/venv/src/staffprofile/views.py in profile_entry, line 57 this is my code in views.py from __future__ import unicode_literals from django.shortcuts import get_object_or_404, render, redirect from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect # HttpResponse allows the get_absolute_url to work ## and HttpresponseRedirect redirects page after a process from .models import * from .forms import * from django.contrib import messages from datetime import datetime, timedelta def profile_entry(request): title = 'ADD YOUR PROFILE INFORMATION' form = ProfileForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) date_of_birth = instance.date_of_birth age_days = (datetime.now().date() - date_of_birth) age = (age_days/365) rem_yrs = (60 - int(age)) instance.date_of_retirement = rem_yrs instance.save() messages.success(request, 'Successfully Saved') return redirect('/profile/profile_detail') context = … -
How to replace function call with json inside another function?
How can to replace api request to stripe with json - https://stripe.com/docs/api/events/object class StripeWebHook(APIView): permission_classes = (AllowAny,) authentication_classes = () def post(self, request, *args, **kwargs): payload = request.body event = None try: # Need to replace this request event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: return Response(status=400) if event.type == 'payment_intent.succeeded': payment_intent = event.data.object # contains a stripe.PaymentIntent # More logic I need to replace try/except block