Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add extra data from unrelated table in Django Rest?
I have this serializer: class RatingSerializer(serializers.Serializer): username = serializers.CharField(source='usersceneobj.user.username') image = serializers.SerializerMethodField(source='get_image') crystals = serializers.FloatField(source='propertyValue') energy = serializers.SerializerMethodField(source='get_energy') def get_image(self, obj): return obj.usersceneobj.user.extendeduser.get_big_img() def get_energy(self, obj): return obj.get_energy(obj) class Meta: model = UserSceneObjectParameter fields = '__all__' I wand to add extra column - reward for for the first 5 rows, which is fetching from another table with 2 columns: position(1 - 5) and reward for this position. How can i do this? Or may be i need to make 2 queries: to fetch Rating data and then, fetch reward data for the first 5 rows? -
Where to use which class based views in django ?
So far, I used function based views. After switching to class based views, I found there are many type of class based views available.I also found, these class based views have specific purpose. But some time, our need does not satisfy its purpose. Example: I have form, where a post is created. But its form elements are custom (rather than general form) like, sub category will be populated by selection of main category, selection of custom check box will populate new kind of fields. So in this case, my form is not only model fields dependent. In this case which Class based view should be used and how to pass data from view to templates ? It will be good to me if all class based views purpose is answered. -
how to implement search form and post create form in single class based view
i'm trying to implement both searching posts and create a post in single view. views.py class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): post_list = None form = HomeForm(self.request.GET or None) form1 = CommentForm(self.request.GET or None) posts = Post.objects.filter(user = request.user).order_by('-created') comments = Comment.objects.all() users = User.objects.exclude(id=request.user.id) query = request.GET.get('q') if query: post_list = Post.objects.filter( Q(post__icontains=query) ) context = { 'posts_list': post_list, } print(post_list) args = { 'form': form, 'posts': posts, 'users': users, 'form1':form1, 'comments':comments,'post_list':post_list, } return render(request, self.template_name, args) def post(self, request): form1 = CommentForm() text = '' if request.method=='GET' and 'btn1' in request.POST: post_list = Post.published.all() query = request.GET.get('q') if query: post_list = Post.objects.filter( Q(post__icontains=query) ) context = { 'posts_list': posts_list, } return redirect('home:home') if request.method=='POST' and 'btn' in request.POST: form = HomeForm(request.POST,request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = HomeForm() form1 = CommentForm() return redirect('home:home') html code <form enctype="multipart/form-data" class="form-inline my-2 my-lg-0" action="."> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name='q'> <button class="btn btn-outline-success my-2 my-sm-0" name="btn1" type="submit">Search</button> {% block body %} <div class="container"> <div class="col-md-8"> <h2>Home</h2> <form method="POST" enctype="multipart/form-data" type = 'file'> {% csrf_token %} {{ form.post }} {{ form.image }} <br> <button name="btn" type="submit">Submit</button> </form> <h2>{{ text }}</h2> {% … -
Django Rest Framework + React - token vs session authentication
Although there are many posts about this topic (or closely related) on SO, I did not find what I am looking for. As the title suggests I am using Django Rest Framework as a backend, and React as a frontend. Now I implemented token authentication, and it works perfeclty. The only problem is that the token is stored in React's state, and if the user refreshes the page, he is no longer logged in (the token is lost). So, now I want to switch to session authentication, since the problem is solved then. But that will require me to do some research, and before I go there I'd like to know if that is the best choice. My question: Do I need to use session authentication to have users stay logged in, even when the React's state changes. Or can I also achieve the same thing with token authentication (in a safe responsible way?) I figure I can safe the token in a cookie, but that doesn't seem safe to me. -
ImportError: No module named 'django.core.urlresolvers'. Django version incorrectly determined in third party django app (AutoSlug)
I am using Django 2.0.8 and Python 3.5 I am using a django-podcasting which imports AutoSlug. The following exception is raised by Django when I run python manage runserver: ImportError: No module named 'django.core.urlresolvers' I tracked down the error in the source code to see it was being caused by this code fragment: from django.conf import settings from django import VERSION if VERSION >= (2, 0): from django.urls import get_callable else: from django.core.urlresolvers import get_callable Quick test in my virtualenv >>> from django import VERSION >>> VERSION (2, 0, 8, 'final', 0) >>> VERSION >= (2,0) True >>> Since my django version is 2.0.8 (see above), why is the wrong statement being executed? How do I fix this (short of modifying the source code of AutoSlug?) -
How to store array in mysql database using django model?
1.I have array of products and want to store it in mysql database using django model.I tried with 'ListTextField' in models.py as below, products = ListTextField( base_field=models.CharField(max_length=255), size=100, # Maximum of 100 products in list ) and I am using serializer to save data.But it is not working. 2.If I want to save data manually from views.py.How should I pass array of products in model object.for example, obj=ContactDeatils(name='abc',products=['aa','bb']) This gives me 'invalid syntax error' near products. please help. -
How to access the OneToOne Field in template while submitting the form through CreateView class
Models.py class LeadReminder(models.Model): first_reminder = models.DateField(blank=True, null=True) second_reminder = models.DateField(blank=True, null=True) third_reminder = models.DateField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) class LeadAdmin(models.Model): admin_supporter_club_name = models.CharField(max_length=240, blank=True, null=True) leadreminder = models.OneToOneField(LeadReminder, on_delete=models.CASCADE) Views.py class AdminCreateView(CreateView): fields=('admin_name_of_supporter_club') model = LeadAdmin template_name="Business_Dev/Business-admin-create.html" success_url='/business-admin/home/' (templates) Business-admin-create.html <form method="post"> {% csrf_token %} {{form.as_p}} </form> How can i access the LeadReminder model fields in template while submitting the form via CreateView class in views. I am defining the LeadAdmin in the CreateView and LeadAdmin is connected to the LeadReminder through the OneToOneField. As simply defining the fields of the LeadReminder in CreateView gives error as I have defined the model LeadAdmin. -
Why Django REST Framework nested serializer self.instance always returns None?
I have model, class Profile(models.Model) user = models.OneToOneField(User) And my serializer classes are, class UserSerializer(serializers.ModelSerializer): def validate(self, attrs): print(self.instance) # Always prints None print(self.parent.instance.user) # Prints User instance return attrs class Meta: model = User class ProfileSerializer(serializer.ModelSerializer): user = UserSerializer() class Meta: Model = User Why self.instance inside validate() method in nested serializer always returns none? -
Dynamically update fields in django
I am creating a result management system using django. What I want to do is to create a session (it is done) then automatically, all the courses from course model will be in the session model ( I don't need to add individually) and then show a page that enables to add batch to the added courses. After submission all the students of the corresponding batch will be added to the course and thus session and redirect to somewhere to enable user to assign each course to a specific teacher each of the students have several marks fields to cover by the assigned teacher the result will be calculated and saved in the database after input from a table (better as an imported excel file) so far, I have made this: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Course(models.Model): cid = models.AutoField(primary_key=True) cnam = models.CharField(max_length=200) cidn = models.IntegerField() cred = models.IntegerField() def __str__(self): return 'IT-' + str(self.cidn) + ' - ' + self.cnam class Student(models.Model): snam = models.CharField(max_length=200) sid = models.AutoField(primary_key=True) sroll = models.IntegerField() sreg = models.IntegerField() sbtc = models.IntegerField() sses = models.CharField(max_length=10) def __str__(self): return self.snam class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name … -
Django how to pass bulk values in html via for loop and array?
Views.py def cartdata(request): emailid = request.session['emailid'] dressid = cart_details.objects.values_list('dressid').filter(emailid=emailid) cartdress = array.array('i',[dress_details.objects.all().filter(dress_id=dressid)]) for i in cartdress: cartdetails = dress_details.objects.all().filter(dress_id=i) return render(request, 'project/shop.html', {'cartdetails':cartdetails}) shop.html <div class="single-cart-item">{% for i in cartdetails %} <a href="#" class="product-image"> <img src="{{ i.dress_image1 }}" class="cart-thumb" alt=""> <!-- Cart Item Desc --> <div class="cart-item-desc"> <span class="product-remove"><i class="fa fa-close" aria-hidden="true"></i></span> <span class="badge">{{ i.dress_name }}</span> <h6>{{ i.dress_type }}</h6> <p class="size">Size:{{ i.dress_size }}</p> <p class="color">Color: {{ i.dress_color }}</p> <p class="price">RS.{{ i.dress_price }}</p> </div> </a>{% endfor %} </div> database in database 2 tables are there. 1st Cart table where 3 columns 1)cartid(primarykey) 2)email(session variable) 3)dressid(fetching from dress table) 2nd Dress table where all the data of dress available. My main question is I'm not able to fetch whole data how can I fetch in djano.? -
Django Pagination(ordering objects by likes)
I have a forum where people can ask and answer questions. So, people who can answer, also can add likes to the posts. I decided to order objects with the number of likes. And of course, I have a pagination My views.py def all_questions_max_likes(request): all_subjects = Subject.objects.all() posts = Post.objects.all().order_by('-likes') paginator = Paginator(posts, 4 ) page = request.GET.get('page') posts_ = paginator.get_page(page) args = { 'all_subjects' : all_subjects, 'posts' : posts, } return render(request, 'ask/questions.html', args) This is how it looks like Why does Django take an object 3 times, with 3 likes? How can I solve it? -
local time for datetime field
I have a model, that has a Datetime field class MyModel(models.Model): ... created_at = models.DatetimeField(auto_now_add=True) the settings.py for timezone configuration: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I have two questions: first, how can I display local time, when I want to display created_at in admin second, also, when I use it in serializer: class MySerializer(ModelSerializer): class Meta: model = MyModel fields = (..., 'created_at',) Note: My app have users from different countries. -
Django inline model formset with 2 models
First of all, please forgive for my newbie questions. I did copy most of the code, and try to understand from Django documents. Code as below: models.py class Order(models.Model): ORDER_CHOICES = ( ('import', 'IMPORT'), ('export', 'EXPORT') ) storage = models.ForeignKey(Storage, on_delete=models.PROTECT) order_type = models.CharField(max_length=6, choices=ORDER_CHOICES) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) class Item(models.Model): def random_barcode(): return str(random.randint(10000000, 99999999)) type = models.ForeignKey(Type, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) item_name = models.CharField(max_length=50, help_text='Name of goods, max 50 characters') barcode = models.CharField(max_length=8, default=random_barcode, unique=True) production_date = models.DateField() expired_date = models.DateField() def __str__(self): return self.item_type forms.py class ItemForm(ModelForm): class Meta: model = Item exclude = ['order',] fields = ['type', 'brand', 'item_name', 'production_date', 'expired_date'] ItemFormSet = inlineformset_factory(Order, Item, form=ItemForm, extra=1) views.py class CreatePO(CreateView): model = Order context_object_name = 'orders' template_name = 'storages/create_po.html' fields = ['order_type', 'storage',] *#dun't know how to write below code....* 1st question: how to use inline formset to write the CreatePO view? 2nd question: I need my create PO template as below picture, how to add a "Quantity" field? This kind of template need Javascript, right? Any alternative solution? I have no knowledge with javascript. -
Django messages does not work
I also checked this question; django messages not showing However, I already applied what is written there. My settings.py; from django.contrib.messages import constants as messages # some other codes # MESSAGE_TAGS = { messages.DEBUG: 'alert-info', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } # some other codes # INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', . . # other apps ] # some other codes # MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_pdb.middleware.PdbMiddleware', ] # some other codes # TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My products/views.py; def oxford(request): search_result = {} if 'word' in request.GET: form = DictionaryForm(request.GET) if form.is_valid(): search_result = form.search() messages.success(request, 'Your query is successful!') else: form = DictionaryForm() messages.warning(request, 'Please correct the error.') return render(request, 'products/oxford.html', {'form': form, 'search_result': search_result}) My products/urls.py; # some imports here # app_name = 'products' urlpatterns = [ path('', views.IndexView.as_view(), name='base'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('oxford/', views.oxford, name='oxford'), # some other urls here # ] myproject/templates/dashboard.html (not in the app folder); {% load static %} <html lang="en"> <head> # some code here # </head> <body> … -
Django - App crashing when using pandas2ri
I am implementing rpy2 code in Django and when I convert pandas dataframe into r dataframe my app starts crashing and giving error: Error: C stack usage 60820464 is too close to the limit otherwise app works fine as long as i don't convert. Is there any problem/mistake in my code? My code snippet: from .models import Values import pandas as pd from rpy2.robjects import pandas2ri pandas2ri.activate() def rpyset(request): filterdata = pd.DataFrame(list(Values.objects.all().values('val1','val2', 'val3', 'val4', 'val5', 'val6'))) r_dataframe = pandas2ri.py2ri(filterdata) # I want to pass r_dataframe to an rpy2 function but unable to proceed because of error return HttpResponse(filterdataahp.to_html()) -
I am getting an error while running python manage.py runserver
This is the error what I am getting This is the remaining part of the error -
Django Admin (1.11.14) showing 404 error after login (www.mysite/admin/login/?next=/admin/)
i'm using a2hosing passenger_wsgi.py My django version is 1.11.14 , the frontend looks good even i can see the django admin login page. But when i try to login as superuser ( of course with valid credentials ) its taking me to www.mysite/admin/login/?next=/admin/ , with 404 error The error msg : Page not found (404) Request Method: POST Request URL: mysite/admin/login/?next=/admin/ Raised by: django.contrib.admin.sites.login Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ The current path, login/, didn't match any of these. Last thing , when test django-admin check from console (ssh) , i'm also getting : ModuleNotFoundError: No module named 'mysite' -
Create custom admin in django
How can I create a custom admin who can access only certain users data based on some conditions and also access data of certain registered models. -
Django: How to wait unitl a field changes from front-end and respond back
I am working on a Django project for account data sync purpose. I have a desktop app created on VB. When I click the sync button in Django web application it opens VB desktop application. At the time I update sync started in DB when sync completed I update sync completed in DB after that desktop app closes. At the time i need to navigate to the new page in the web application For this, how can I wait in API until flag change and respond back after the sync completed in desktop application? -
Can't runserver, ModuleNotFoundError[Django]
I'm trying to work with django, but I can't runserver it shows an error like this "ModuleNotFoundError: No module named 'music.apps. MusicConfig'; 'music.apps' is not a package" Note: I'm using python3. -
Django CMS 3.5.2 Internalization - translate template text
I have a couple of questions about Django CMS 3.5.2 translation. 1) My website is in three languages. I want to translate my template text into all three languages. I have tried using the {% trans 'my text' %} tag, but, when I write the python manage.py makemessages -l all command, my terminal indicates the following error message instead of creating a .po file: RuntimeWarning, Traceback (most recent call last): File "manage.py", line 7, in <module> startup.manage(path=os.path.dirname(os.path.abspath(__file__))) File "/usr/local/lib/python2.7/site-packages/aldryn_django/startup.py", line 12, in manage utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command commands = get_commands() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 107, in get_commands apps = settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 54, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 49, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 132, in __init__ % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'settings' (Is it on sys.path? Is there an import error in the settings file?): No module named deconstruct I am just wondering if there's another way to translate texts in Django CMS. 2) Is there a way to add the option to translate texts for non-developers? Something like the following (but not only for page names): Thank you! -
How to POST Javascript file in Django form?
I've been struggling with this for a whole day. I have used this gist to compress an image file client-side, before uploading my image to the server. So far so good,image has been compressed and the file(?) "blob" has been created. That "blob" is what I want to upload to my view, but I cannot set it to a hidden file input inside the form because it is not allowed (security reasons). Before compressing I would just add an input field, submit the form and retrieve it in my view from request.FILES. How would I go about posting this blob? I've heard about Ajax and XHR but I am new to programming and know nothing about it. #basic_upload.html <input type="file" id="select"> <img id="preview"> <script src="/static/assets/js/ImageTools.js" type="text/javascript"></script> <script> document.getElementById('select').onchange = function(evt) { ImageTools.resize(this.files[0], { width: 320, // maximum width height: 240 // maximum height }, function(blob, didItResize) { // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob') document.getElementById('preview').src = window.URL.createObjectURL(blob); // you can also now upload this blob using an XHR. }); }; </script> Any hints and examples on what I should do from here? Thanks a lot in … -
Celery 4.2 Django RecursionError: maximum recursion depth exceeded
My __init__.py file from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) My celery.py file from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ajicachuchastore.settings') app = Celery('ajicachuchastore') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() my /etc/supervisor/conf.d/celery.conf file: [program:] command=/home/user/venv/bin/celery -A myproject worker --loglevel=INFO environment=PYTHONPATH=/home/user/project-folder user=user numprocs=1 autostart=true autorestart=true stdout_logfile=/home/user/logs/celery.log stderr_logfile=/home/user/logs/celery.log startssecs=10 stopwaitsecs = 600 stopasgroup=true priority=100 and this is the last section of the error message in celery.log File "/home/user/venv/lib/python3.6/site-packages/celery/loaders/base.py", line 131, in config_from_object self._conf = force_mapping(obj) File "/home/user/venv/lib/python3.6/site-packages/celery/utils/collections.py", line 48, in force_mapping return DictAttribute(m) if not isinstance(m, Mapping) else m File "/home/user/venv/lib/python3.6/abc.py", line 183, in __instancecheck__ subclass = instance.__class__ File "/home/user/venv/lib/python3.6/site- packages/django/utils/functional.py", line 215, in inner self._setup() File "/home/user/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/user/venv/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/user/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 951, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 894, in _find_spec File "<frozen importlib._bootstrap_external>", line 1157, in find_spec File "<frozen importlib._bootstrap_external>", line 1129, in _get_spec File "<frozen importlib._bootstrap_external>", line 1273, in find_spec File "<frozen importlib._bootstrap_external>", line 1231, in _get_spec File "<frozen importlib._bootstrap_external>", … -
Django website's backend can be used for Android and Ios app
I'm going to design a platform and I need mature suggestions for that. Can I use the backend of Django website, developed by me, as backend of Android and IOS apps? If yes, How? If No, why? -
"django.db.utils.ProgrammingError: x field does not exist" showing up after I delete model field
I deleted the field total_comments from my Post model. I performed migrate and makemigrations on my local server, pushed the migration files to my remote server, and then performed migrate and makemigrations there aswell. However I'm now seeing this error in my remote server terminal: Traceback (most recent call last): File "/home/james/postr/env/lib/python3.5/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/james/postr/env/lib/python3.5/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/james/postr/post/tasks.py", line 18, in arrange_ads for ad in ads: File "/home/james/postr/env/lib/python3.5/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/home/james/postr/env/lib/python3.5/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/james/postr/env/lib/python3.5/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/home/james/postr/env/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 899, in execute_sql raise original_exception File "/home/james/postr/env/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 889, in execute_sql cursor.execute(sql, params) File "/home/james/postr/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/james/postr/env/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/james/postr/env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/james/postr/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column post_post.total_comments does not exist I've checked my migration folder in myapp/post/migrations and it shows that the migration file is definitely there: class Migration(migrations.Migration): dependencies = [ ('post', '0031_auto_20180804_0724'), ] operations = [ migrations.RemoveField( model_name='post', name='total_comments', ), ] So why am I …