Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have been getting this error when i open my django admin page
AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://localhost:55066/admin/ Django Version: 2.0.4 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' -
OperationalError at /bandlist/, no such table: polls_band
I am severely confused by this error. I have made migrations as I have seen that has been a running solution with a lot of other problems similar to mine. Here is the error. Traceback (most recent call last): File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: polls_band The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ethan\Envs\OnNote\mysite\polls\views.py", line 117, in bandlist print(query) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 226, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 250, in __iter__ self._fetch_all() File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\sql\compiler.py", line 900, in execute_sql raise original_exception File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\sql\compiler.py", line 890, in execute_sql cursor.execute(sql, params) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\utils\six.py", line 685, … -
serialize (write) when using an intermediate ManyToMany model
Can read/write when using a standard ManyToMany model (no extra fields). Can read when using an intermediate ManyToMany model (with extra fields). Cannot write when using an intermediate ManyToMany model (with extra fields). It fails due to DRF's lack of support for writable nested fields. However, DRF does support writing the nested pk's of the standard ManyToMany model; the extra fields should add no ambiguity to the operation. Reading/writing when using standard ManyToMany model works like this: models.py class Person(models.Model): person = models.CharField(max_length=64) class Group(models.Model): group = models.CharField(max_length=64) persons = models.ManyToManyField(Person) serializers.py class GroupSerializer(serializers.ModelSerializer): persons = serializers.PrimaryKeyRelatedField(many=True, queryset=Person.objects.all()) class Meta: model = Group fields = ('id', 'group', 'persons') Reading when using an intermediate ManyToMany model works like this: models.py class Person(models.Model): person = models.CharField(max_length=64) class Group(models.Model): group = models.CharField(max_length=64) persons = models.ManyToManyField(Person, through='Membership') class Membership date = DateField() group = models.ForeignKey(Person, on_delete=models.CASCADE) person = models.ForeignKey(Group, on_delete=models.CASCADE) serializers.py class MembershipSerializer(serializers.ModelSerializer): class Meta: model = Membership fields = ('id', 'date', 'group', 'person') class GroupSerializer(serializers.ModelSerializer): memberships = MembershipSerializer(source='membership_set', many=True) class Meta: model = Certificate fields = ('id', 'group', 'memberships') What would be the solution to write when using an intermediate ManyToMany model? Looking for something obvious that I've missed; I'd rather not implement … -
django- file upload on many to many field
I have a many to many field in models- class A(models.Model): file = models.ManyToManyField(B, blank=True) refering to another class in model class B(models.Model): filename = models.FileField(upload_to='files/') user = models.ForeignKey(User) forms.py class AForm(forms.ModelForm): file = forms.FileField(label='Select a file to upload', widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta: model = A fields = '__all__' How to get the file upload working over here? I had the basic views.py suggested over here- doesn't work https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html -
Get model objects from nested objects list having FK to self in django
I have list of dict like items=[{'id':1,'items':[items,items]},{'id':4, 'items':[]},{'id':5,'items':[items,items]}] The 'items':[items,items] in nested part is the same as second dict because i have FK to self model. Now i want list of all dict including nested items into final list. I tried def getlistdata(dl): result = [] for item in dl.__dict__.get('items', []): result.extend(item.getlistdata()) return set(result) But this is not working -
How to fill HTML form with javascript and then submitting it
I'm trying to build a website with Django. On the website, the user can fill in a list of ingredients by selecting from a library. This part works fine. Trouble starts when I want the list to be submitted. I've written the following form: <ul id="user_ing_list" class="content"> </ul> <div class="headline"> <form action="{% url 'opskriftssoegning:soegeresultat' %}" method="get" accept-charset="utf-8"> <button type="submit" name="ingsoegning" onclick="prepare_user_ing_list()">Find opskrifter</button> </form> </div> When clicking the button, the following JavaScript function should run: var user_ing_list = document.getElementById("user_ing_list"); function prepare_user_ing_list() { var result_list = []; for (ing in user_ing_list) { result_list.append(ing) }; return result_list; } I thought the form would receive the list of items from the function and submit it, but the resulting Django view tells me that nothing was submitted. What have I done wrong? -
Don't show items in a concrete one language when field is empty
I'm using django 1.11 and django-modeltranslation to translate text field, so I have text_en and text_fr. Sometimes is, that I don't have text_fr and then I want to have on list events only in English (text_en). Below is my solution but don't work, I mean I have still en and fr when I'm switching language. def get_queryset(self): q = super(EventListView, self).get_queryset().filter(date__gte=now().date()).exclude(text_fr__isnull=True) return q This is my model: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = RichTextField() In translation.py file, I am translating fields: class EventTranslationOptions(TranslationOptions): fields = ('title', 'text') -
Django insert: what does this error mean
can you please tell me, what does this error means : int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' here is the full traceback : Traceback: File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\version21\DjangoProj\tsite\appOne\views.py" in post 256. b.save() File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in save 806. force_update=force_update, update_fields=update_fields) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in save_base 836. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\users MGE\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in _save_table Exception Type: TypeError at /banque Exception Value: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' -
Show amount of reports for each profile,in Django Admin
I have two models, Report and Profile. Profile is connected to Report as a foreignKey. In my admin.py I am trying to show each Profile along with the amount(count) of times that the profile has been reported. But I keep recieving a TabError:TabError: inconsistent use of tabs and spaces in indentation So I can't even tell if this code work in showing the number of reports for each profile or not. from django.contrib import admin from .models import Profile,Report from django.db.models import Count class ProfileAdmin(admin.ModelAdmin): list_display = ('id', 'birth_date', 'sessions_played','user_report') def user_report(self, obj): total = Report.objects.count() amount = Profile.total return total admin.site.register(Profile, ProfileAdmin) class ReportAdmin(admin.ModelAdmin): list_display = ('report_reason','sent_by', 'session', 'user_reported') admin.site.register(Report,ReportAdmin) Models are Linked here as an image link,click to view: https://ibb.co/b9YwsH -
combine django model with csv file and loop
I finally manage to show csv file within html and also bind with django model but I am missing a for loop but couldn't make it work. if request.method == 'POST' and request.FILES['csv_file2']: myfile = request.FILES['csv_file2'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) data = csv.reader(fs.open(filename, mode='r')) lines=[] for row in data: line = row[0] lines.append(line) query = line instances = fp.objects.filter(fp_Item=query) context = {'lines': lines, 'instances': instances, } return render(request, 'check_fp.html', context) return render(request, 'check_fp.html', {}) When I use; instances = fp.objects.filter(fp_Item=query) It works but I get only last line information from database and missing previous lines but I need loop this "query" or is there any method like append useable with queryset filter? -
How to run a django project without manage.py
Basically I downloaded django project from SCM, Usually I run the project with with these steps git clone repository extract change directory to project folder python manage.py runserver But this project does not contains manage.py , how to run this project in my local machine??? br -
Customising Django formset
I have currently an issue with my Django form set. The way the form is generated is that the tickets are shown in a select/option field. However I don't need the user to 'select'. I just want to list them one after another. Here an example: Anyone who can help me with this? This question here is a follow up to this question here Django: Combining forms & models to generate form I am using the code, Nayan posted there which is also marked as "best answer". If I should rather post the code here as well, please let me know and I will do so. -
Template extension blocks staticfiles, django
When I'm trying to load static files in template which extends base.html it doesn't work. There is no error but nothing happens. When i comment extension and run server, then it's working. How to solve this, so i can inherit after base.html and also add some css to the template. Why if template extends base.html it's blocking static files ? My base.html: <head> <title> {% block head_title %}BetterTwitter.com{% endblock head_title %} </title> {% include 'snippets/css.html' %} </head> <body> <h1>Tweet yourself</h1> <div class="container"> {% block content %}{% endblock %} </div> {% include 'snippets/js.html' %} </body> </html> My inherited template: {% extends 'MyTwitter/base.html' %} {% load staticfiles %} <head> {% block head_title %}{{ block.super }}{% endblock head_title %} {% block references %} <link rel="stylesheet" type="text/css" href="{% static 'MyTwitter/style.css' %}" /> {% endblock %} </head> <body> {% block content %} <h1>Tweets</h1> <table> <tr> <th>User</th> <th>Tweet</th> </tr> <tr> {% for tweet in tweets %} <td>{{ user.username }}</td> <td>{{ tweet.content }} {% endfor %} </tr> </table> <body> {% endblock content%} -
Django Front End User App
can any one recommend any apps that allows the user via the frontend to send templated emails. the user needs to be able to amend elements of the message and attached multiple attachments that have already been uploaded. ideally the user should have a selector to pick which attachments to include for that email. in principle, the functionality is close to an invoicing sending app but more complex. Thanks -
Django ListView not using join sql statements on foreign key
I am quite new to Django and am still learning the basics. I have been playing around with the generic ListView and I am confused about the sql queries behind the list content generation. Here's a simple example to illustrate: My model: class Member(models.Model): def __str__(self): return self.name name = models.CharField() class Phone(models.Model): phone = models.CharField() member = models.ForeignKey(Member) My views: from django.views.generic import ListView class PhoneList(ListView): models=Phone My template: {% for obj in object_list %} <tr><td>{{ obj.member }}</td><td>{{ obj.phone }}</td><td></tr> {% endfor %} Now, suppose I have put in some records into the Phone table: 1 - member_id=1, phone='123425' 2 - member_id=2, phone='234234' 3 - member_id=5, phone='9043234' ... So I run this ListView and everything displays as expected. The phone numbers are listed alongside members' names. However, when I use debug_toolbar to look at the underlying sql statements, I see that Django is not using a JOIN statement between the member and phone tables. Instead, for each phone record, it does a separate query to the member table to get the corresponding member record. This seems very inefficient. If I pull up 1000 phone records, it would then do 1000 queries into the database? Why isn't it using a … -
django -- conditional branch in view.py based on the value obtain by ajax
Currently, I made simple application using django and ajax. Although the code of the structure as below is written, the value sending with ajax is able to receive in view.py. However, When used the value in a conditional branch after that, I cannot it. what is the cause of problem? ajax.html var slot_id = 1; $.ajax({ type:"POST", data:{ 'slot_id':slot_id, }, views.py if request.method == 'POST': slot_id = request._post['slot_id'] print(slot_id) ** it can display 1** if slot_id == 1: print(slot_id) **it cannot display 1** -
Django Admin Custom Action not being executed
I have a Django Admin application and a custom action. The custom action is assigned to a specific ModelAdmin. class AlertsAdmin(admin.ModelAdmin): ... actions = [my_action] Mostly of the time it works fine. But once in a while it starts to completelly refuse to execute, and it does it until I restart the application server. Looking into the network I saw that it seems that the POST request is redirected (302) and then it loses the body I though it might be related to Django adding '/' in the end of the url, but I have changed it to: APPEND_SLASH = False And it still doesn't work. The error happens also in the development server, adding breakpoint to the actions just show me that the action is not being executed and never hits the breakpoint. Any idea what else can I try or how to fix it? -
How can i submit an Imagefile using ajax in django
I have my jquery and ajax as follows . IT works pretty good in submitting normal data but not imagefiles. What i my suppose to do to rectify this problem and make it work to submit image files of my django model form . $('#my-form').submit(function(e)){ e.preventDefault(); var formaurl=$(this).attr("data-url")||window.locate.href; var formdata=$(this).serialize(); $.ajax({ url:formurl, type:'POST', data:formdata, success:SuccessFunction, error:ErrorFuntion, django model form class Post(forms.ModelForm): class Meta: field=('image1','image2','productname','productdetail') productname and productdetail is submited successfully to the data base except image1 and image2 . Please help me . I have search the internet but yet i can not find a solution . -
Django, jQuery $.post: request elements have extra "[]" added
I'm trying to do a post request to my Django view using jQuery's $.post. The elements I'm trying to get to Python are lists (arrays) that I build off of multiple IDs. Here is my jQuery code: var newBaseline = function () { // Initialize arrays each time the function is run var timeArray = []; var parametersArray = []; var runsArray = []; // Cycle through some input elements and get their values, push to array timeRangeInputs.each(function() { timeArray.push($(this).val()); }); // Cycle through some checkboxes and get their data-id values, push to array parameterContainer.find("input:checked").each(function() { parametersArray.push($(this).data("parameter_id")); }); // Cycle through some checkboxes and get their data-id values, push to array runContainer.find("input:checked").each(function() { runsArray.push($(this).data("run_id")); }); // Just a flag for my view so I can do if-else cases in python, as the view handles several forms in the same page var flag = "new-baseline"; $.post("{% url 'my_view %}", { csrfmiddlewaretoken: "{{csrf_token}}", timeArray: timeArray, parametersArray: parametersArray, runsArray: runsArray, flag: flag }, function(data) { // check valid or errors, etc }).done(); }; The problem arises when I go to my Python view. The request.POST QueryDict object comes in fine, but the arrays have additional []'s appended. print(request.POST) >>> <QueryDict: {'runsArray[]': ['3, 7'], … -
dose Django allow to define different set of fields for each document
Django and MongoDB Supporting a different set of fields for each document in a collection is one of MongoDB's features. It allows you to store similar data, but with different properties in the same collection. for example: { _id: ObjectId("51156a1e056d6f966f268f81"), type: "Article", author: "Derick Rethans", title: "Introduction to Document Databases with MongoDB", date: ISODate("2013-04-24T16:26:31.911Z"), body: "This arti…" }, { _id: ObjectId("51156a1e056d6f966f268f82"), type: "Book", author: "Derick Rethans", title: "php|architect's Guide to Date and Time Programming with PHP", isbn: "978-0-9738621-5-7" } Django dose not support Non-Relational data base like mongodb by default, but there are some lib's for this purpose. for example Django MongoDB Engine is a MongoDB backend for Django. MongoDB allow to use different set of fields for each document in a collection, but in django you have to define models.py: from django.db import models from djangotoolbox.fields import ListField class Post(models.Model): title = models.CharField() text = models.TextField() tags = ListField() comments = ListField() the Question is: is there any way to define different set of fields for each document in a collection in MongoDB, when using Django ? -
DRF: How to password protect the DefaultRouter
How would you go about protecting DefaultRouter() so the user can not view API Root unless they are logged in? router = routers.DefaultRouter() router.register(r'orders', views.OrderViewSet) class OrderViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = (permissions.IsAuthenticated) queryset = Order.objects.all() serializer_class = OrderSerializer -
when and why do we have to implement websockets?
I have a Django rest api running at an instance and now i want a browser add on to communicate to the rest api , I want this communication to be based on web sockets not HTTP , but i want the handshake of web socket connection to be done via http . Is this a correct approach can I use web sockets in this senario . -
application = DjangoWhiteNoise(application) NameError: name 'application' is not defined
I was working on deploying my site to heroku.com and while i was doing so i followed all the steps they said and i thought of justr making a localhost server before deploying and i got a error: Performing system checks... System check identified no issues (0 silenced). April 11, 2018 - 15:45:13 Django version 2.0.4, using settings 'portfolio.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x034FD540> Traceback (most recent call last): File "C:\Users\Kiran\Desktop\myvenv\lib\site-packages\django\utils\autoreload. py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Kiran\Desktop\myvenv\lib\site-packages\django\core\management\c ommands\runserver.py", line 140, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Kiran\Desktop\myvenv\lib\site-packages\django\contrib\staticfil es\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\Kiran\Desktop\myvenv\lib\site-packages\django\core\management\c ommands\runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "C:\Users\Kiran\Desktop\myvenv\lib\site-packages\django\core\servers\base http.py", line 44, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Kiran\Desktop\myvenv\lib\site-packages\django\utils\module_load ing.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Kiran\Desktop\myvenv\lib\importlib\__init__.py", line 104, in i mport_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2231, in _gcd_import File "<frozen importlib._bootstrap>", line 2214, in _find_and_load File "<frozen importlib._bootstrap>", line 2203, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1448, in exec_module File "<frozen importlib._bootstrap>", line … -
Which Django Form Field can provide me a HTML output of <input type="range" />?
I've got a html form with this input: <input id="duration_slider" type="range" min="1" max="168" value="48" /> However I'd now like to convert this slider to a django form field, so I can use it in a Django form. The field name is duration so I'll change the id to id=id_duration. What would my models.py and forms.py looks like for this field? Currently it's just: class AdvertisePost(Post): ... duration = models.IntegerField(default=48) def __str__(self): return self.title class AdvertisePostForm(forms.ModelForm): duration = ? class Meta: model = AdvertisePost fields = [ ... #'duration' ] -
ImportError: cannot import name 'RedactorTextField'
Hey folks here am facing issue while running Django project I installed Django-WYSIWYG-redactor added redactor into INSTALLED_APPS = ( ... 'redactor', ... ) Add url(r’^redactor/’, include(‘redactor.urls’)), to urls.py Add default config in settings.py # .... REDACTOR_OPTIONS = {'lang': 'en'} REDACTOR_UPLOAD = 'uploads/' # .... In models.py from django.db import models from redactor.fields import RedactorTextField class Entry(models.Model): title = models.CharField(max_length=250, verbose_name=u'Title') short_text = RedactorTextField(verbose_name=u'Text')