Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a superuser in my own User Form?
I am creating my own form to register users, but how can I make possible to create superusers in it, and also I know django allows you, call user in the views like this:reques.user.username. I can only use that using django forms or I can also use that with my forms I creating my own form because I don´t want the restriccion django password have, is there a way to change that, in oder to not create my own form -
Python runserver not working
Error: I am getting this error when I am using python run server . I am using python runserver but getting this error Cpython@python:/var/python/picologic$ python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x7fd17f8bdaa0> Traceback (most recent call last): File "/opt/conda/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/opt/conda/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/opt/conda/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/opt/conda/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/opt/conda/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/conda/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/opt/conda/lib/python2.7/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/opt/conda/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named theme File "/opt/conda/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() -
Django: Add a list to a QuerySet
I am new to django so apologies if this is not possible or easy. I have a view that takes a subset of a model data = Terms.objects.filter(language = language_id) The subset is one language. The set has a number of concepts for a language. Some languages might use the same word for multiple concepts, and I want to colour these the same in an SVG image. So I do this next: for d in data: if d.term is None: d.colour = "#D3D3D3" else: d.colour = termColours[d.term] Where termColours is a dictionary with keys as the unique terms and values as the hexadecimal colour I want. I thought this would add a new colour attribute to my queryset. However, when I convert the queryset to json (in order to pass it to JS) the colour object is not there. terms_json = serializers.serialize('json', data) How can I add a new colour element to my queryset? -
Celery + Django on Elastic Beanstalk causing error: <class 'xmlrpclib.Fault'>, <Fault 6: 'SHUTDOWN_STATE'>
I've a Django 2 application deployed on AWS Elastic Beanstalk. I configured Celery in order to exec async tasks on the same machine. Since I added Celery, every time I redeploy my application eb deploy myapp-env I get the following error: ERROR: [Instance: i-0bfa590abfb9c4878] Command failed on instance. Return code: 2 Output: (TRUNCATED)... ERROR: already shutting down error: <class 'xmlrpclib.Fault'>, <Fault 6: 'SHUTDOWN_STATE'>: file: /usr/lib64/python2.7/xmlrpclib.py line: 800 error: <class 'xmlrpclib.Fault'>, <Fault 6: 'SHUTDOWN_STATE'>: file: /usr/lib64/python2.7/xmlrpclib.py line: 800. Hook /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. INFO: Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. ERROR: Unsuccessful command execution on instance id(s) 'i-0bfa590abfb9c4878'. Aborting the operation. ERROR: Failed to deploy application. To be able to update my application code, I have to re-create a new environment by doing the following: $ eb terminate myapp-env # terminate the environment $ eb create myapp-env # re-create it The Celery config file that I'm using is the following: files: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh": mode: "000755" owner: root group: root content: | #!/usr/bin/env bash # Create required directories sudo mkdir -p /var/log/celery/ sudo mkdir -p /var/run/celery/ # Create group called 'celery' sudo groupadd -f celery # add the user 'celery' … -
Reverse for `view` with arguments '('',)' not found. 1 pattern(s) tried: `[u'bms/update/(?P<id>[0-9]+)/$']`
This is my update view which i'm using to get pre-populated form. Although this is also not working. def update(request, id): item = get_object_or_404(BookEntry, id=id) if request.method=="POST": form = UpdateForm(request.POST, instance=item) if form.is_valid(): post=form.save(commit=False) post.save() return HttpResponseRedirect(reverse('bms:index'), id) else: form=EntryForm(instance=item) return HttpResponseRedirect(reverse('bms:index'), id) return render(request, 'index.html', {'form':form}) This is my urls.py url(r'^update/(?P<id>[0-9]+)/$', views.update, name='update'), This is the error that I'm getting again and again: NoReverseMatch at /bms/ Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: [u'bms/update/(?P[0-9]+)/$'] I'm not sure if passing the url in right way. This is what i'm doing: <form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST"> When I look at traceback, it's showing something's wrong in above line and this line: return render(request, "bms/index.html", context) This is my index view: def index(request): context = {} book_detail = BookEntry.objects.all() context.update({ 'book_detail': book_detail }) response = {"status": False, "errors": []} if request.is_ajax(): id = request.POST['id'] csrf_token = request.POST['csrfmiddlewaretoken'] response = {} response['status'] = False book = BookEntry.objects.filter(id=id).first() context = { "book": book, "csrf_token": csrf_token } template = render_to_string("bms/index.html", context) response['template'] = template response['status'] = True return HttpResponse(json.dumps(response), content_type="applicaton/json") return render(request, "bms/index.html", context) Help please. -
Implement field wise searching in Django Admin
I'm using Django 2.0 I have to add functionality to search for fields from model with different input fields for different columns. I'm following this tutorial from medium.com and have implemented it like models.py class WallmartRecord(models.Model): name = models.CharField(max_length=250) upc = models.CharField(max_length=100) price = models.CharField(max_length=100) category = models.CharField(max_length=250) class Meta: db_table = 'wallmart_records' def __str__(self): return self.name admin.py class InputFilter(admin.SimpleListFilter): template = 'admin/input_filter.html' def queryset(self, request, queryset): pass def lookups(self, request, model_admin): return ((),) def choices(self, changelist): # Grab only the "all" option. all_choice = next(super().choices(changelist)) all_choice['query_parts'] = ( (k, v) for k, v in changelist.get_filters_params().items() if k != self.parameter_name ) yield all_choice class WallmartNameFilter(InputFilter): parameter_name = 'name' title = _('Name') def queryset(self, request, queryset): if self.value() is not None: name = self.value() return queryset.filter( name=name ) @admin.register(WallmartRecord) class WallmartRecordAdmin(admin.ModelAdmin): list_filter = [ 'WallmartNameFilter', 'not_exists_in_amazon', 'arbitrase_generated' ] But this is giving error as SystemCheckError: System check identified some issues: ERRORS: <class 'arbitrase.admin.WallmartRecordAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'WallmartNameFilter', which does not refer to a Field. -
How to add second level inline in Django without changes to models
I have these models: class TopLevel(models.Model): #irrelevant class MiddleLevel(models.Model): top = models.ForeignKey(TopLevel) class BottomLevel(models.Model): middle = models.OneToOneField(MiddleLevel) now, I want to have a BottomLevelInline in my TopLevelAdmin. I tried django-nested-admin, however there I can't get rid of the MiddleLevel fields. I want the inline to show only BottomLevel.objects.filter(middle__top=current_top) queryset, where current_top is the TopLevel object I have opened in Admin. -
Elastic Beanstalk Django migrate issue
I'm deploying Django app to the AWS EB using CLI and noticed that EB doesn't see new migrations files for the first time. So, when I have new migrations I need to deploy twice. I looked at logs and indeed migrations were not found for the first time and found for the second time. Here is my code for migrations: container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "python ras-server/manage.py collectstatic --noinput" Am I need to change commands order? Also, I think that issue could be with Jenkins as I deploy from Jenkins. Any suggestions? -
Closing Django window
I am using Datatable for displaying some data wherein I need to provide edit functionality. So, I have created hyperlinks to each entry which lead to the record in the Django database in a new window. But, after I edit the record and save it, the window stays open. How to close the Django database window on its 'save'? -
Django urls.py is not a py file in PyCharm
enter image description here as picture above , why does my urls.py look different from others and it doesn't interact with PyCharm coding assists but if I create another file with other names instead of urls , it works. why ? -
Django: No Error is being thrown, But 'leave group' functionality isn't working
I have a groups model, and I want users to be able to join and leave a group. joining a group is working, and this is the code for it: def join(request, group_id): group = get_object_or_404(Group, pk= group_id) if request.method == 'POST': group.members.add(request.user) # group.save() return redirect('/groups/' + str(group_id) ) else: return render(request, '/groups/detail.html', {'group': group}) However, leaving a group doesn't work, although the code doesnt seem like it should be very different: def leave(request, group_id): group = get_object_or_404(Group, pk= group_id) if request.method == 'POST': group.members.remove(request.user) # group.save() return redirect('/groups/index/') else: return render(request, '/groups/index.html') THere is not error thrown, but pressing the leave button isnt doing anything at the moment. Any help would be really appreciated! -
Django: transfer instance across inline form to template
I have related model EntertainmentCollage with image fields and did't now how to transfer instance models to the editing form. I need to display the existing images in the editing form and have the ability to add new ones. models.py class Entertainment(models.Model): main_photo = models.ImageField(upload_to = 'where/') place = models.CharField(max_length=200) description = models.CharField(max_length=200) event_date = models.DateTimeField(auto_now_add=False, blank=True, null = True) class EntertainmentCollage(models.Model): img = models.ImageField(upload_to = 'entertainment/portfolio', blank = True) album = models.ForeignKey(Entertainment, blank = True, null = True) views.py def edit_where(request, pk): place = Entertainment.objects.get(id=pk) FormSet2 = inlineformset_factory(Entertainment, EntertainmentCollage, fields =['img',], extra=6) form = WhereCreateForm(instance=place) form2 = FormSet2() if request.user.is_authenticated(): if request.method == "POST": form = WhereCreateForm(request.POST, request.FILES, instance=place) if form.is_valid(): form2 = FormSet2(request.POST or None, request.FILES) if form2.is_valid(): form.save() form2.save() return redirect('entertainment:where_list') else: form = WhereCreateForm() form2 = FormSet2() return render(request, "entertainment/where_edit.html", {'form': form, 'form2': form2}) html <section> <div class="container"> <div class="row"> <div class="col-md-3"> <h2>Editing Where</h2> <br> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.eventname }}</p> <p>{{ form.place }}</p> <p>{{ form.event_date }}</p> </div> <div class="col-md-9"> <section class="admin-section"> {{ form2.management_form }} <div class="row"> {% for frm in form2 %} <div class="col-md-4 admin__block" is-cover="false"> <div class="cover__wrapper edit__wrapper"> <a class="delete-button">Delete</a> <a class="make-cover-button">Cover</a> <img src="{{ frm.url }}" alt=""> </div> </div> … -
How can I have multiple post request handling methods in a Class Based View
The docs suggest that I can have one get, post, put method in a Class Based View. How can I implement something like this? class Test(APIView): def post_modelA(request): # code to create instances for model A def post_modelB(request): # code to create instances for model B -
What changes are needed for use abstractuser concept in model
how can i use abstractuser concept in model. class Register(models.Model): name = models.CharField(max_length=100) rollno = models.CharField(max_length=100) sid=models.CharField(max_length=8) -
How to make Django store datetimes in UTC but show them in local time in Admin?
What the title says. For simplicity and standardization, I want to store datetimes in UTC timezone, but I want to display them in Admin's local timezone. No matter the settings (TIME_ZONE and USE_TZ), I still have Note: You are x hours ahead of server time when editing my datetimes. I want this note to go away, and the flow to be like: Type time in local time and click save Datetime created will be saved in UTC timezone When I get it from DB by request, it will still be in UTC. Conversion is handled by front end. If I look at it from admin, it will be in local timezone. -
Django Returning german date with strftime
I have this code: date = program.last_registration_date.strftime('%d %B %Y, %H:%M') Program is my model and last_registration_date is a normal value from a DateTimeField Now my problem is that date returns an english date, which I don't want. In my default.py I've set my TIME_ZONE correctly ('Europe/Berlin'), my LANGUAGE_CODE ('de') and ofc USE_L1ON is set on True. But it still not german. I tried to import locale and use a setlocale after my imports, but that also won't work (just shows me an error that locale is an unsupported setting). So yeah, anyone can help me how to turn this date german? -
multi-tenant-schemas:dynamic api routing using django restframework
I am newbie to Multi-Tenant architecture, developing SaaS product using django-tenant-schema my requirement was something like clients would register for product. For every registered client, I was creating new schema by following single database and isolated schemas approach. Whenever client requested from a browser I was able to identify them by using subdomain and giving privilege to acces their specfic schema. While I was starting coding lot of questions were popup in my head. I am really sorry for asking here but stackoverflow is only my last hope. Database was like below Database Public_Schema auth_user Clients_List_Table ClientA_Schema auth_user ClientA_User_List ClientB_Schema auth_user ClientB_User_List Q1.What kind of admin actions we can perform on every client? I have rest api for example http://client.example.com/api/user_list/ here client maybe ClientA or ClientB Q2. How can we implement api routing which gets client name dynamically when user requested at browser which let us to use corresponding schema to display current client's user_list. Any reply can be helpful. Thanks in advance. -
"Cannot assign must be a instance" while assigning that specific instance
There are many related questions on SO about this topic, but they all seem to deal with cases where the element being assigned is actually the instance.id or a string with the instance name. I have two models, one called Photo, the other called Material. class Photo(models.Model): mat = models.ForeignKey( Material, related_name='photos',null=True, blank=True) In the shell, I get a Photo object, and I create a Material object. [in : 1]p = Photo.objects.all()[0] [in : 2]m = Material.objects.get_or_create(id=1)[0] [in : 3]p [out:1] <Photo: Photo object> [in : 4]m [out:2] <Material:Material object> [in : 5]p.mat = m --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-60-836d23304359> in <module>() ----> 1 p.mat = m /home/rootadmin/opensurfaces/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.pyc in __set__(self, instance, value) 595 instance._meta.object_name, 596 self.field.name, --> 597 self.field.rel.to._meta.object_name, 598 ) 599 ) ValueError: Cannot assign "<Material: Material object>": "Photo.mat" must be a "Material" instance. As far as I can tell, m is a Material instance. What is going wrong? -
Django get class from a string variable
I have a variable initialised with class name. But, when I use this variable for accessing the class based view, it show the error 'str' object has no attribute 'as_view'. How to get the class from a string variable ..? classname = "GetAjaxView" return classname.as_view()(request) -
Django, manager: where does self.model get set?
Hello and thank you for your time! I cannot seem to figure out where self.model, as well as the other attributes set within the __ init __() of BaseManager, get their values from. Suppose I would create a custom manager class. In this case, that manager class inherits from BaseUserManager, which in turn inherits from the BaseManager class. When I instantiate an object of that manager class, the __ new __() class defined in the BaseManager() class gets called: class BaseManager(object): ...some lines... def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial obj = super(BaseManager, cls).__new__(cls) obj._constructor_args = (args, kwargs) return obj This seems to call the __ new __() class belonging to the object base class which the BaseManager class inherits from. After this, the __ init __() also defined within the BaseManager() class is called. This is where I think I get lost: def __init__(self): super(BaseManager, self).__init__() self._set_creation_counter() self.model = None self.name = None self._db = None self._hints = {} def __str__(self): """ Return "app_label.model_label.manager_name". """ return '%s.%s' % (self.model._meta.label, self.name) What happens here? It seems as if __ init __() just sets self.model to None, but accessing self.model still returns the class … -
Django Gives The Same Response With Even Different Input-Values
I started using Django recently. I've integrated MongoDB using PyMongo module [pip3 install pymongo]. My Problem: Django gives me the same data even after the database gets updated. Whenever I run some manipulations; like comparing the email entered by the user with that of existing email IDs in the database, I get the same result every time. Looks like the result is getting cached. Urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.homepage), path('register/', views.register), ] Views.py from django.shortcuts import render from pymongo import MongoClient from django import http def homepage(request): return (render(request, 'index.html')) def register(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] client = MongoClient('mongodb://my_ip:27017/') db = client.trainingdb collection = db.data emailCheck = str(collection.find({"Email":email})) if emailCheck == "": dbData = { 'Name': name, 'Email': email, 'Password': password } collection.insert_one(dbData) return http.HttpResponse("Success!") else: return http.HttpResponse("Email exists in database!") else: return render(request, 'register.html') The homepage method is for index page or main page. The register method is for the registration page. Here, I'm trying to check whether the email ID entered by the user pre-exists in the database or not. Test Cases: For the first time, I've entered an email … -
Django Admin Sortable 2 Not Saving Order
I have installed Django Admin Sortable 2 in to my Django project. I can see the drag and drop order system in the admin but when I move around some objects the order doesn't get saved. I cannot see any error in my terminal log either when moving objects around. Here is my Model and Admin python files. Do I need to do anything extra to get the order to save? Model.py class QuickLink(models.Model): title = models.CharField(max_length=20) image = models.FileField(null=True, blank=False,upload_to='media/quick_links') link = models.CharField(max_length=200) order = models.PositiveIntegerField(default=0, blank=False, null=False) def __str__(self): return self.title class Meta(object): ordering = ['order'] Admin.py from django.contrib import admin from adminsortable2.admin import SortableAdminMixin from .models import QuickLink @admin.register(QuickLink) class QuickLinksAdmin(SortableAdminMixin, admin.ModelAdmin): pass My versions are as follows: Django 2.0.4 Python 3.6.1 Django Admin Sortable 2 0.6.19 -
Search ISBN number using typeahead and go that particular book by clicking the number
I'm making a crud app using django 1.11 and python. I want to use a typeahead to perform a search for isbn number of a particular book. When i'll click that particular isbn number it should automatically go to that book. I'm entering the details of the book using the django admin panel. Any suggestions how to do this? -
Django model form admin
I'm doing some unit tests for a Django's app and I want to test a form filling in admin. Which mean that I don't have a specific form for that model. Here is my code : response = self.client.post(self.url, {"title_fr" : 'titre', "status" : 2, "email" :'email@email.com'}) here is my model class JobOffer(Displayable, RichText): email = models.EmailField(max_length=255, null=False,verbose_name=_('Email to forward response')) And here is the error : django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] I really filled all need fields, and also tried to add data additional data like mentioned in django doc like adding in data : 'form-TOTAL_FORMS': '1', Sorry about this post, pretty sure the answer is really simple. Thanks ! -
How do you connect to Google Cloud Postgresql via Django framework?
This is the default configuration one would have for a local postgresql connection using Django framework in setting.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'LOCAL_DB_NAME', 'USER': 'LOCAL_DB_USER', 'PASSWORD': 'LOCAL_DB_PASS', 'HOST': '127.0.0.1', 'PORT': '5432', } } How to configure it to work with Google Cloud Postgresql managed database?