Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stop task A, run task B, continue task A in Celery / Redis
I have two tasks in Celery. Let's call them A and B, because their code is meaningless in our scenario. What I want to do, is: Run taskA each 5 mins. This to complete takes from 3-6 minuts. If task is still running, wait until it ends. (don't run parallel) Run taskB each 1 min. This to complete takes 5-15 seconds. Running this task should temporary pause taskA After this task is done, continue taskA This can be easily done by setting some semaphors. What I need help with is; can I solve it somehow with celery worker / beat properties? I did read about concurrency and autoscale, but it doesn't seems to match my case. -
How to clone a Select2 control loaded with Django and Python?
I'm trying to clone a select inside a div. But when i clone the element, the Select2 element doesn't have the loaded values by the Django code. How can i clone my div with all the Select2 element values? When i clone, it clones, but the selects are not showing the values. Thank you so much. <script> counter = 0 function addTopic(){ $( "#select" ).clone().appendTo( "#trying" ); } </script> </head> <body> <button onclick="addTopic()">Add Topic</button> <form action="{% url 'testing_show' %}"> <div id="trying"> <div id="select"> <select class="js-example-basic-multiple" multiple="multiple"> {% for taf_doc in taf_documents %} <option value="{{ taf_doc.id }}">{{ taf_doc.taf.nom }}</option> {% endfor %} </select> <select class="js-example-basic-multiple" multiple="multiple"> {% for ue_doc in ue_documents %} <option value="{{ ue_doc.id }}">{{ ue_doc.ue.nom}}</option> {% endfor %} This is the header : <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script> <script> $(document).ready(function(){ $(".js-example-basic-multiple").select2(); });//document ready </script> -
How to add SPAN container in Django CKEDITOR
I'm trying to add span container to my ckeditor in my django project, currently my Ckeditor have just DIV container, but I need to add SPAN container just like the Div container to able me add some span container. my django settings has: CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'full' , 'width': '100%', }, } -
error: Could not find suitable distribution for Requirement.parse('rest_framework>=3.6.3')
i am trying to build a python package and my following is my setup.py setup( name='django-sso_consumer', version='0.1', packages=find_packages(), include_package_data=True, license='BSD License', # example license description='A simple Django app for sso_consumenr and hooks', long_description=README, url='https://www.example.com/', author='Paksign', author_email='shoaib@wukla.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.5', # replace "X.Y" as appropriate 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', # example license 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], install_requires=[ 'wukla_utils', 'rest_framework>=3.6.3', 'django>=1.11.3' ] ) but upon running sudo python setup.py develop i am unable to install it because install requires fails to install rest_framework and exits with following error messages Reading https://pypi.org/simple/ No local packages or working download links found for rest_framework>=3.6.3 error: Could not find suitable distribution for Requirement.parse('rest_framework>=3.6.3') anyone knowing whats wrong here please help me out.Thanks in advance. -
How to get foreign key relation array in django
I have country table and its translation table with foreign key country_id, and city table with foreign key country_id, and city translation table with foreign key city_id. So my model.py like this. from django.db import models # Create your models here. class Country(models.Model): #id = models.IntegerField(primary_key=True) iso_code = models.CharField(max_length=2, unique=True) slug = models.CharField(max_length=255, unique=True) is_featured = models.IntegerField(max_length=1) class Meta: db_table = 'rh_countries' class CountryTranslation(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) locale = models.CharField(max_length=2) class Meta: db_table = 'rh_countries_translations' class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) class Meta: db_table = 'rh_cities' class CityTranslation(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) locale = models.CharField(max_length=2) class Meta: db_table = 'rh_city_translations' And my views.py file like this. from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.template import loader from home.models import Country, CountryTranslation, City, CityTranslation from django.db.models import F, Count def index(request): #return HttpResponse("Hello, world. You're at the polls index.") template = loader.get_template('home/index.html') context = { "countries" : Country.objects.filter( is_featured=1, countrytranslation__locale='en' ).annotate( name=F('countrytranslation__name'), totalCities=Count('city', distinct=True) ) } return render(request, 'home/index.html', context) This way I have got total cities of the country. But I want list of 3 cities name of … -
Failed to execute 'importStylesheet' in django project
I have django project and there is a strange thing on the test environment I have no problem with that, it only appears on the live environment. The problem is the following message appears: jquery.xslt.js:238 Uncaught TypeError: Failed to execute 'importStylesheet' on 'XSLTProcessor': parameter 1 is not of type 'Node'. The requirements are the same for both environments. Can someone tell me where and how to debug, look for a solution? -
NoReverse Match Error while extending user model in Django.
I'm trying to add additional fields to Django user model. It's a website where companies can create their profile, add bio, description etc. Only logged in companies can add/edit additional fields (These fields are not available during signup). What's the best way to do it? I tried to do it by creating another app. Here is my code. models.py from django.urls import reverse from django.shortcuts import get_object_or_404 from django.contrib.auth import get_user_model User = get_user_model() class ProfileInfo(models.Model): short_description = models.CharField(max_length=255, unique=True) long_description = models.TextField(blank=True, default='') user = models.ForeignKey(User, related_name='company_profile', on_delete=models.CASCADE) def __str__(self): return self.user def get_absolute_url(self): return reverse("employerprofile:edit_profile", kwargs={"username": self.user, "pk": self.pk}) views.py from django.shortcuts import render from django.views import generic from django.urls import reverse from .models import ProfileInfo from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin class EditProfileInfo(LoginRequiredMixin, generic.UpdateView): fields = ('short_description', 'long_description') model = ProfileInfo urls.py from django.urls import path from employerprofile import views app_name = 'employerprofile' urlpatterns = [ path('edit_profile/<slug>/', views.EditProfileInfo.as_view(), name="edit_profile"), ] navigation bar html code <a class="nav-link" href="{% url 'employerprofile:edit_profile' %}">Edit Company</a> profile_info.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h4>Add Details</h4> <form action="{% url 'employerprofile:edit_profile' %}" method="post"> {% csrf_token %} <input type="submit" class='btn btn-primary btn-large' value="Create"> </body> </html> I'm getting this error NoReverseMatch at / … -
How to get the abstract class name from child class
I have few models as below, class FooBarAbstract(models.Model): foobar = models.IntegerField() class Meta: abstract = True class Foo(FooBarAbstract): foo = models.IntegerField() class Bar(FooBarAbstract): bar = models.IntegerField() How can I get the abstract class name (FooBarAbstract) by using child classes (Foo or Bar ) or their objects? -
Django admin returns 403 Forbidden error on Microsoft EDGE after multiple savings or editings
I'm having 403 Forbidden error after saving or editing elements from Django admin, on Microsoft Edge. I'm logged in as super user, so I have all the permissions for adding/editing elements through the admin. Infact, the problem is presenting when I successfully add a new element and then I decide to "save and continue editing" or "save and add another". The second modification/creation will always fail with the 403 error. It works well on all the other browsers, just Microsoft Edge fails. Any ideas? -
Argument must be strinng in django rast_framework?
Watch this my filteration And please give me solution of this and why this showing this type of error? def create(self,request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): data = serializer.data sub = data['subject_id'] sub_id = Subject.objects.filter(id=sub) sec = data['section_id'] sec_id = Section.objects.filter(id=sec) teacher = data['teacher_id'] teacher_id = Teacher.objects.filter(id=teacher) if sub_id and sec_id and teacher_id: TeacherSection.objects.get_or_create(section_id = sec_id.first(), defaults={ 'subject_id':sub_id.first(), 'teacher_id':teacher_id.first() }) return Response(data) else: raise serializers.ValidationError({ 'Detail':['Either Section Or Teacher Or Subject Not Exist'] }) else: raise serializers.ValidationError({ 'Detail':[serializer.errors] }) error is like This. And cound u explain what type of error is this return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Subject' -
How to solve ReverseNoMatch error django?
urls.py from django.urls import path from . import views app_name = 'infos' urlpatterns = [ path('', views.home_page, name='index_view'), path('members/', views.list_members, name='list_members'), path('members/<int:id>/', views.view_member, name='view_member'), path('members/<int:id>/photos/', views.show_photos, name='show_photos'), ] views.py def show_photos(request, id): member = BandMembers.objects.get(pk=id) member_id = member.pk print(member_id) photos = Photos.objects.get(band_member=member) return render(request, 'infos/photos.html', { 'photos': photos, 'member': member_id}) html template photos.html {% extends 'base.html' %} {% block title %} Στοιχεία {% endblock %} {% block body %} <div class="container"> {{ form.as_p }} <a href="{% url 'infos:show_photos' id %}" class="btn btn-primary"> Φωτογραφίες </a> </div> {% endblock %} I get a 'NoReserveMatch'error . What am i doing wrong ? I've been searching for hours and hours at stackoverflow , youtube , .... ,... and it seems as if i'm doing it right .But surely I DON'T !!!!!! where is my mistake ??????? Thank you guys . -
boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials
I have installed the existing project with docker but I face an error above. Please everyone kindly help...thanks in advance. -
Django ModelForm: Huge ManyToMany field leads to crash when loading form
Basically, I have two models: User and Event. An event is always associated with one user. class User(models.Model): user_id = models.AutoField(primary_key=True) username = models.CharField(max_length=255, unique=True) hashed_password = models.CharField(max_length=255) class Event(models.Model): event_id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) description = models.TextField(max_length=255, blank=True, default='') user = models.ForeignKey(User) And then I have the following form for Event. class EventForm(forms.ModelForm): class Meta: model = Event fields = ['title', 'description', 'user'] I can succesfully show this form in my template to create an event. I can also associate a user to a form successfully with Select field when the users number are still few. Now the problem is, when I have 1M users in database, my browser crashes when loading the template. Any idea how to solve this one? I was thinking about using AJAX and then search user that matches the username, but I'd like to hear other better approaches. Thanks! -
How to set up django channels?
I have a problem with WebSocket. I create an object in the admin panel, and the frontend calls for getting the JSON object to the server. I need to eventually get a real-time update on the front after creating the object. consumers.py @receiver(post_save, sender=Factory) def send_update(sender, instance, **kwargs): Group("liveblog").send({ "text": json.dumps({ "id": instance.id, "titile": instance.title, "choice": instance.choice, "address": instance.address }) }) class MyConsumer(JsonWebsocketConsumer): strict_ordering = False def connection_groups(self, **kwargs): return ["liveblog"] def ws_connect(self, message): Group("liveblog").add(message.reply_channel) message.reply_channel.send({"accept": True}) def receive(self, content, **kwargs): multiplexer = kwargs['multiplexer'] response = { "id": self.id, "title": self.title, "choice":self.choice, "address":self.address } multiplexer.send({"response":"OK"}) multiplexer.group_send("liveblog", response) def ws_disconnect(self, message): Group("liveblog").discard(message.reply_channel) routing.py channel_routing = [ route_class(MyConsumer) ] .js var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var ws_path = ws_scheme + '://' + window.location.host; var socket = new WebSocket("ws://localhost:8000"); socket.onopen = function () { console.log("Connected to socket"); }; socket.onclose = function () { console.log("Disconnected from socket"); } What am I doing wrong? -
How to translate query with sub query into Django ORM (mysql engine)
I have 2 models Driver and Representative joined with third entity "driver_assignment". Please find the attached picture for demonstration. I want to fetch the record of driver assigned to representative (only last entries of each assignment). I have written a mysql query which works fine and giving perfect result. But I'm new to Django and I have no idea how to translate this complex query to Django ORM. I hope someone out there will help me. MySQL Query SELECT * FROM cars_driver c JOIN cars_driverassignment cd ON cd.id = (SELECT max(m.id) as m_id FROM cars_driverassignment m WHERE m.target_driver_id = c.id) WHERE cd.representative_id = 1716 (Sorry for my english. I'm not a native English). -
Django NoReverseMatch Reverse for 'cart-add' with arguments '('',)' not found
I am getting the following error after I added href="{% url 'cart-add' product.id %}" to the add to cart button on my product.html file: NoReverseMatch at /3/ Reverse for 'cart-add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[0-9]+)\\/$'] I believe that it's a urls pathing problem or settings, but I'm not sure how to resolve it. In case there are relevant files I missed displaying here, here is my github: https://github.com/sebapaik/django-shop My product.html file looks like this: {% extends "shop/base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-4"> <img class="img-thumbnail" src="{{ object.imageurl }}" alt=""> </div> <div class="col-lg-8"> <h2>{{ object.brand }} {{ object.pname }}</h2> <p>${{ object.price }}</p> <p>{{ object.description }}</p> Add to cart {% endblock content %} My Project/urls.py (main) looks like this: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls')), path('cart/', include('cart.urls')), ] My shop/urls.py looks like this: from django.urls import path from . import views urlpatterns = [ path('add/<int:product_id>/', views.add_cart, name='cart-add'), path('', views.cart_detail, name='cart-detail'), ] My cart/urls.py looks like this: from django.urls import path from . import views urlpatterns = [ path('add/<int:product_id>/', views.add_cart, name='cart-add'), path('', views.cart_detail, name='cart-detail'), ] My … -
I am trying to make a custom user model in django, but its giving me a lot of errors
I am developing a Django project, so I have the scheduling app, the real function on the app, and I created an "accounts" app to modify the base User Model, so I can make the user log in with his/her email. If you can help me with this problem, I would really appreciate since I am kind of stuck. However, now that I modified the models.py(in the "accounts" app) and modified the settings.py on the main website folder, I am getting the following errors(the last including an installed apps settings error, which I don't understand.: Traceback (most recent call last): File "C:/PythonProjects/tutorTrip/manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 70, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf__init__.py", line 56, in getattr self._setup(name) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Alienware\AppData\Local\Programs\Python\Python36\lib\site-packages\django\conf__init__.py", line 120, in init raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting) django.core.exceptions.ImproperlyConfigured: The INSTALLED_APPS setting must be … -
django-import-export line number.1- 'id'
I trying to import excel into django via django-import-export package but I'm getting an error that says; Errors Line number: 1 - 'id' None, 100, None, Western Province, 5465, 864546, 56954, 4456, 45, 1.2, 2.1 Traceback (most recent call last): File "C:\Users\Billy Somers\AppData\Local\Programs\Python\Python37\lib\site-packages\import_export\resources.py", line 453, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\Billy Somers\AppData\Local\Programs\Python\Python37\lib\site-packages\import_export\resources.py", line 267, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\Billy Somers\AppData\Local\Programs\Python\Python37\lib\site-packages\import_export\resources.py", line 261, in get_instance return instance_loader.get_instance(row) File "C:\Users\Billy Somers\AppData\Local\Programs\Python\Python37\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: 'id' -
Ugettext_lazy as dictionary key in django
Why the following code doesn't work? Is it possible to use proxy objects as keys? from django.utils.translation import ugettext_lazy as _ ABBREVIATIONS = { _('tr.'): 'transitive' } -
Fetch API leads to CSRF error in Django, but not cURL?
I'm running across a really weird error where the fetch API (in a React-Native project) leads to a CSRF error but cURL doesn't lead to the same error. Here's the notable code: Fetch code: _signup = () => { fetch('http://localhost/users/', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { return response.json(); }).then(jsonResponse => { console.log(jsonResponse); }).catch (error => { console.log(error) }) } which gives the following response Object { "detail": "CSRF Failed: CSRF token missing or incorrect.", } and the cURL code is: curl -X POST -d '{"username":"a", "email":"", "password":"a"}' -H "Content-Type: application/json" http://localhost/users/ where the response is {"url":"http://localhost/users/13/","username":"a7","email":""} the relevant Django view is just a viewset: Django View: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer. Is there any reason this should be happening? As far as I know, fetch and curl should be doing the same thing? -
Django admin custom form doesn't reflect in server
In django admin I need to upload multiple file. So customise change_form.html. This changes working nice in my local environment. But do not work in server. in change_form.html {% extends "admin/change_form.html" %} {% block inline_field_sets %} {% for inline_admin_formset in inline_admin_formsets %} {% include inline_admin_formset.opts.template %} {% endfor %} <fieldset class="module"> <h2>Upload Photos</h2> <input name="bundle_images" type="file" multiple /> </fieldset> {% endblock %} in admin.py class ImageBundleAdmin(admin.ModelAdmin): change_form = 'templates/admin/imagebundles/ImageBundle/change_form.html' ..... ..... The output in my local But output in my server Please advice what I miss? In server I used nginx and gunicorn Thanks -
how to implement logging in django restframework?
When i called a post call if there are any errors then the errors should be saved in a file and that should be done by using logging how to do that. Can anyone help me -
using filter with foreignkey property, what is _?
my understanding is this I have class Season(models.Model): drama = models.ForeignKey('Drama', on_delete=models.CASCADE) so in my views.py def seasons(request, slug): drama = Drama.objects.get(name=drama_name) seasons = Season.objects.filter(drama) because I have drama as foreignkey for seasons, I can use drama.name with seasons in views.py using _ underbar? but it says 'drama_name' is not defined What am I missing? -
Set AUTH_USER_MODEL from apps inside folder from settings.py
I'm new to django and I'm trying to extend the user class in one of my apps but I'm having trouble redirecting from setting.py to the model that contains my AbstractUser My Nproject: -apps: --profile: ---__init__.py ---apps.py ---forms.py ---models.py ---urls.py ---views.py --apps1 -media -static -templates -Nproject: --__init__.py --settings.py --urls.py --wsgi.py model in apps.profile.models from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): address = models.CharField(max_length=255) def __str__(self): return '%s %s' % (self.email, self.username) setting.py and here I think this is my mistake AUTH_USER_MODEL = 'apps.User' #not working I think the error is in AUTH_USER_MODEL that I do not know how to properly reference the model User Research some sites and tell me that you should use the init.py file but it is not working init in apps.profile from .models import User Error: Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/projects/.virtualenvs/Nproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/projects/.virtualenvs/Nproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/projects/.virtualenvs/Nproject/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/projects/.virtualenvs/Nproject/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/projects/.virtualenvs/Nproject/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/projects/.virtualenvs/Nproject/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in … -
djangorestframework-jwt or djangorestframework-simplejwt?
What's the difference between djangorestframework-jwt and djangorestframework-simplejwt? Which one should I use?