Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
migrate error in python mysql django
on running python manage.py migrate arises this error, if I delete already existing table this command still show this type of error Apply all migrations: admin, auth, bridge, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1050, "Table 'django_content_type' already exists") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle fake_initial=fake_initial, File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/share/nginx/html/django_env/lib/python3.4/site-packages/django/db/migrations/executor.py", … -
Create and use new variable containing a context variable in template in Django
I need to search a keyword in multiple forums. For this I have multiple QuerySets like this: context["abc_list"] = Users.objects.using("db1").filter(...) context["xyz_list"] = Members.objects.using("db2").filter(...) with abc, xyz etc. being the different forums. I then chained them together... context["user_list"] = list(chain( context["abc_list"], context["xyz_list"], )) ... in order to count the number of items found and show them in my template: <p>Found <strong>{{ user_list|length }}</strong> items.</p> I now want to display the items found in every user list. While I'm able to do it like this: {% if abc_list|length > 0 %} <p> <a href="#results-abc"><strong>Abc:</strong> {{ abc_list|length }} result{{ abc_list|length|pluralize:"s" }}</a> </p> {% endif %} ... I would now like to make this a bit more dynamic. Since I already created a context variable with all the forums (I need these elsewhere in my template) like this: context["forum_list"] = Forum.objects.all().order_by("name") ... I thought about creating a context variable for each forum which counts the containing elements: context["abc_count"] = context["abc_list"].count() ... ... and changing the loop to something like this: {% for forum in forum_list %} {% with "#results-"|add:forum.name as result and forum.name|add:"_count" as forumCount %} <p> <a href="{{ result }}"><strong>{{ forum.name|capfirst }}:</strong> {{ forumCount }} result{{ forumCount|pluralize:"s" }}</a> </p> {% endwith %} {% … -
Django rest framework directory structure
I'm new to Django rest frameworks and am using them for one of our projects.My current directory structure looks like project app __init__.py migrations utils __init__.py helpers.py utils.py core datastructures.py apps.py models.py serializers.py views.py project __init__.py settings.py urls.py wsgi.py manage.py The utils directory above contains custom code to access and modify database so it needs to use models in models.py. The core directory contains logic of app which would use the functions defined in utils.py and helpers.py. So I need to import a file from parent directory in helpers.py.I try this in following ways- from ..models import model1,model2..... Expectedly this gives the classic import error in python 3 as ImportError: attempted relative import with no known parent package I also tried- from project.app.models import model1,model2,... this also throws an error- django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Given everything above (utils need to use models and core needs to use utils),I feel that I'm in lot of mess! What is the appropriate directory structure that I should follow?And how would these imports work? -
Django ListView settting variable to model instance element
In my views.py class for a ListView I'm trying to add a formula that uses a specific element from an object in the get_context_data() method. Here is what I've tried. Models.py Class MyModel(models.Model): foo = models.FloatField() bar = models.FloatField() views.py class MyView(generic.ListView): template_name = "my_item_list.html" model = MyModel def get_context_data(self, **kwargs): obj = MyModel.objects.get(pk=this_object_id) var_a = obj['foo'] var_b = obj['bar'] result = var_a * var_b context = { 'result': result, } return context This throws an object does not support indexing error. I've tried several different methods of accessing the specific object element without luck. I'm not trying to annotate (which is the vast majority of SO Q&A), just use the value from the specified object field. As a side note, if I pass obj into the context data I can easily iterate to the element value in the template - so i know that the .get() method is working correctly - it's just the "simple" math in the view I can't get to work. I did find this (model_to_dict()), but it is turning the obj into a dictionary - I think this could work, but seems much more wordy than I would expect. Thoughts? -
supervisor: couldn't chdir to /path/to/project: ENOENT
I'm trying to daemonize celery worker using supervisor, but getting error child process was not spawned. I followed this. Here's my configuration file [program:learn360] command=/media/rofi/Personals/ROFI/Projects/Learn360/venv/bin/celery worker -A learn360_backend --loglevel=DEBUG directory=/media/rofi/Personals/ROFI/Projects/Learn360/learn360_exam stdout_logfile=/var/log/celery.log stderr_logfile=/var/log/celery.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq is supervised, it will start first. priority=1000 And celery log file shows these errors. supervisor: couldn't chdir to /media/rofi/Personals/ROFI/Projects/Learn360/learn360_exam: ENOENT supervisor: child process was not spawned My directory structure /media/../Learn360/ -learn360_exam -venv What I'm doing wrong here? -
Custom error_messages during the form validation when using generic edit UpdateView
The solution I currently use for custom error_messages during the form validation when using generic edit UpdateView is as follows models.py from django.db import models class Employee(models.Model): first_name = models.CharField(max_length=100, verbose_name="Name") last_name = models.CharField(max_length=100, verbose_name="Surname") date_of_birth = models.DateField(blank=True, null=True, verbose_name="Birthday") forms.py from django import forms from .models import Employee class ModelFormWithCustomErrorMessages(forms.ModelForm): class Meta: model = Employee fields = '__all__' error_messages = {'date_of_birth': {'invalid': 'Custom invalid error message'}} views.py: from .models import Employee from .forms import ModelFormWithCustomErrorMessages class EmployeeUpdateView(UpdateView): model = Employee form_class = ModelFormWithCustomErrorMessages The thing I don't really like here is that you have to create separate ModelForm (ModelFormWithCustomErrorMessages) for every model where you want to cusomize error_messages. Just adding an argument error_messages for the model field doesn't work for the forms: class Employee(models.Model): date_of_birth = models.DateField(blank=True, null=True, error_messages={'invalid': 'Custom invalid error message'}) Is there a better way to customize error_messages when using generic edit views? -
What is example of Django projects that I can learn app tesing from it?
I would be happy to see the Django project with well thought and well-written test suite. Can you point me to some examples of such projects? -
'Loging in' error, in Django framework
when i insert username and password, it doesnt redirect to home page and stays in login page, and its url displays such messages http://localhost:8000/login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24 in Powershell it shows like this System check identified no issues (0 silenced). May 25, 2018 - 11:50:07 Django version 2.0.5, using settings 'a.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [25/May/2018 11:50:10] "GET /login/?csrfmiddlewaretoken=B6RMXDzgZjnk2QzbmbcesMqsRUOtVH3Q1FBaS1HCB6CXXujpbOziiHLH8VR1oLzC&username=admin&password=laughonloud24 HTTP/1.1" 200 446 Performing system checks... there is no error though, but it doesn't behave the way i want it to.. models.py from django.db import models # Create your models here. class login_model(models.Model): username = models.CharField(max_length=200) password = models.CharField(max_length=200) forms.py from django import forms from .models import login_model class LoginForm(forms.ModelForm): class Meta: model = login_model fields = ['username','password'] urls.py from django.urls import path from . import views urlpatterns = [ path('login/',views.login_view,name = 'login_url' ), path('',views.home, name = 'home_url'), ] views.py from django.shortcuts import render,redirect from .forms import LoginForm from django.contrib.auth import authenticate,login # Create your views here. def home(request): return render(request,'home.html') def login_view(request): if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): uusername = form.cleaned_data.get('username') ppassword = form.cleaned_data.get('password') user = authenticate(request,username=uusername,password=ppassword) if user is None: login(request,user) return redirect('home url') else: print('Error') else: form = LoginForm() return … -
ripple rpc method account_tx attribue 'date' issue
The ripple rpc method account_tx method retrieves a list of transactions that involved the specified account. while using account_tx it retuen attribute date as - 'date': 580452520 (unix date format).its date is 1998 may 25 .but actually transaction done date is 2018 may 25 .How can solve this issue. -
Django autocomplete and DRF Viewset
There is a lot of entries in db which are ForeignKey and displayed as select widget in the admin site, so it makes heavy the page to load and so on. The solution was to use ready autocomplete-* libraries involving select2, but all of them use their own views. Is there a way to combine it with a Viewset of DRF? Tried django-autocomplete-light and managed to load first 10 results, but it didn't load the rest as I scroll. -
Add id to element with javascript using django field
I have a problem creating id's for my elements. We use django as framework and I create element id's from the field name as this: <tr class="issueRow" id="{{field.auto_id}}"> However, some field.auto_id's have blank spaces in them, this causes problems later on when looping through elements with document.getElementById. So, my question is, how can I trim away those blank spaces from my new id? I have a function that simply removes the blank spaces but I can't seem to find the correct way to call the function with a django field as parameter since id="{{TrimID({{field.auto_id}})}}" gives a parsing error -
Django cannot access dictionary using a variable in the template
I am learning Django by making a newsfeed website for practice. In my newsfeed page I want to display the number of likes on a post on the like button. See the two code blocks below - views.py - Here I have put all my posts in all_posts and then has looped through the posts to get the count of total likes on this post from a Likes table in the model (If there is a better way please suggest) into the likes dictionary. all_posts = NewsFeed.objects.all().order_by('time').reverse() likes = {} for post in all_posts: likes_count = Likes.objects.filter(newsfeed = post).count() likes[post.id] = likes_count form = StatusForm() context = { 'name': name, 'all_posts': all_posts, 'statusForm': form, 'likes': likes, } index.html - Here I want to display all the posts and a like button for each post which would also display the number of likes on the post. When I am manually trying to access the likes count {{ likes.4 }} it is displaying correct count for the fourth status Like(1) but when I try to access it like {{ likes.post_id }} it displays nothing Like(). Please help me out as I am new to this and also provide with the suggestions to … -
How to create log column for each django model?
How to create log column for each django model? (Log column will maintained all the database tracking information.) Thanks in advance! -
How to calculate DateTime fields in django
Suppose I have the following Date time fields and I would like to calculate the total time between them. Which is the best approach? session_end_time = models.DateTimeField(null=True, blank=True) discharged_at = models.DateTimeField(null=True, blank=True) checked_in_at = models.DateTimeField(null=True, blank=True) -
Remove authentication from Django one URL/View
I want to remove authentication from one of the URLs of my Django project. I basically want to call that URL from an external app, without authentication. How can I achieve that? -
python Django calcuation balance brought forward
I am working on an accounting app and i needed direction on how to go about calculating the balance brought for a particular day. What i want to accomplish is being able to display the balance brought forward when the user select a date. i want to be able to display the transaction that happen in a particular date and the balance brought forward from the previous day. currently i just sum up all the transaction that was done in and then minus the total sum to get the opening balance. However when ever there is a movement in the account the brought forward balance on different dates also change. dailytransaction =Sum(dailytransactions) openingbalance=totalsum balancebroughforward=openingbalance-dailytransaction how to i keep the balance brought forward for each day unchange whenever there is movement on an account each day. -
How do I get all the questions answered by a learner by using django queryset?
I have a model named Quiz. Each Quiz has a set of related questions in the model Quiz_Question. Quiz Model:- class Quiz(models.Model): quiz_name = models.CharField(max_length=200) Quiz_Question Model:- class Quiz_Question(models.Model): quiz = models.ForeignKey(Quiz, related_name='questions') text = models.CharField(max_length=200) Now I can get all the questions for a particular quiz using the related_name attribute as follows:- all_quizes = Quiz.objects.all() A particular quiz:- quiz = all_quizes[0] All the questions related to this quiz as follows:- all_related_questions = quiz.questions.all() I have another model as a LearnerQuestionAnswer where learner is a normal django user:- class LearnerQuestionAnswer(models.Model): quiz_question = models.ForeignKey(Quiz_Question) learner = models.ForeignKey(User) What I want to do is find out all the questions that are related to the particular quiz by that user. -
Django custom field method does not create enum field in mysql
My code is as shown below: class CharMaxlength25Field(models.Field): def db_type(self, connection): return 'enum(android,ios)' class search(models.Model): class Meta: db_table = 'search' city_name = CharMaxlength25Field() Through this code, I am trying to create enum field in mysql. Now when I try to run this schema with python manage.py makemigrations step,I get the following error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'android,ios) NULL' at line 1") -
How to convert content of InMemoryUploadedFile to string
Does anyone know how to convert content of uploaded file (InMemoryUploadedFile) in Django2 to string? I want to know how to write the following convert2string(): uploaded_file = request.FILES['file'] my_xml = convert2string(uploaded_file) # TODO write method(convert to xml string) obj = MyObject() parser = MyContentHandler(obj) xml.sax.parseString(my_xml, parser) # or xml.sax.parse(convertType(uploaded_file), parser) -
Creating a navigation tree with Django ListView
I'm working on my navigation for a django project and can't figure this one out. I have the context being returned from a single ListView class, but I want to arrange the returned queryset by a category. If I have multiple categories in the same model, how can I split the returned view objects in order to display them separately on the page? I tried using this in views.py: class ServiceView(ListView): model = Service template_name = "services/services.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['health'] = Service.objects.all().filter(service_type__icontains='health') context['life'] = Service.objects.all().filter(service_type__icontains='life') return context under the impression I could call the modified contexts from a template, but i could only call one context. Is it possible to create multiple contexts from a single model? I was trying to use a template like the following, maybe that was my problem... services.html: <ul class="sidebar-nav animated fadeIn"> <li> <a data-toggle="collapse" href="#coll-css" class="collapsed"><i class="fa fa-heart"></i> Health</a> <ul id="coll-css" class="menu-submenu list-unstyled collapse"> {% for service in health %} <li><a href="{% url "services" %}{{ service.slug }}"><i class="fa {{ service.icon }}"></i>{{ service.title }}</a></li> {% endfor %} </ul> <a data-toggle="collapse" href="#coll-css" class="collapsed"><i class="fa fa-heart"></i> Life</a> <ul id="coll-css" class="menu-submenu list-unstyled collapse"> {% for service in life %} <li><a href="{% url "services" %}{{ … -
Django static page not found 404
Django css file not found error, loading css file failed, getting 404 file not found error also i am getting another error: "Not allowed to load local resources. Yes, I've tried c:/path/chrome.e xe -, all it does is launch a browser, doesn't navigate me to any url/website. What you guys suggest, this is my code. Ill be posting only the code which i think is to be relevant. My Django version is the latest one,2. Browser Chrome GET http://127.0.0.1:8000/static/care/style.css 404 (Not Found) settings.py # Application definition INSTALLED_APPS = [ 'care.apps.CareConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' style.css is present inside the directory Care which is present inside another directory called static. I tried with relative and 'absolute path', when i tried with absolute path, i am getting a different error "Not allowed to load local resources". Just to be through, i actually copied the link from HTML source code and paste it in the browser and it does take me to the style.css file.Nothing is wrong with the path. why Django not detecting css … -
Saving a proper timestamp in database django 2+/python 3.5
I have a table: class TSForm(models.Model): sBegin = models.DateTimeField(null=True) sEnd = models.DateTimeField(null=True) FKToUser = models.ForeignKey(User,default=None, on_delete=models.PROTECT) When I go to save this in my python file like: tfh = TSForm(sBegin=scan_start,FKToUser=historyUser) It properly saves the other fields, but it is saving the sBegin as: 2018-05-25 00:00:00.000000 instead of say: 2018-05-25 10:05:23.321231 How can I fix this? Thanks -
Django Custom User Admin Panel won't log in
I just started a new Django project and I wanted to create my own customer user model instead of using the default. I pretty much followed the one in the documentation for 2.1 (my version of Django) except I added more fields and date_of_birth is called 'dob' and isn't required. But then when I create the superuser account, I can't log into the admin panel. It says, "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive." Here is my code: users/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.utils.translation import gettext_lazy as _ # Create your models here. class UserManager(BaseUserManager): # python manage.py createuser def create_user(self, email: str, password: str=None) -> 'User': if not email: raise ValueError('Users must have a valid email address.') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user # python manage.py createsuperuser def create_superuser(self, email, password) -> 'User': user = self.create_user( email=email, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( _('email address'), help_text=_('An email address'), max_length=127, unique=True, null=False, blank=False ) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) first_name = models.CharField(_('first name'), help_text=_('The user\'s given name'), blank=False, max_length=32) last_name = … -
Django IIS Server Run Website
I'm currently using IIS 9 along with python 3.4 & django 2.0.5 I followed a youtube video and i tried uploading the website. What i did was: I put the website i built into C:\inetpub\wwwroot\ and in wwwroot, i put my websiteBugTracker I went onto my IIS: Turned my CGI on, went onto the server's FAST CGI SETTINGS and created a new application with path to my main python.exe link i.e. C:\Python34\python.exe Arguments: C:\inetpub\wwwroot\BugTracker\fcgi.py Environment variables : DJANGO_SETTINGS_MODULE BugTracker.settings PYTHONPATH C:\inetpub\wwwroot\BugTracker WSGI_HANDLER django.core.wsgi.get_wsgi_application() Then i added a new website to my sites list and named it BugTracker I created a new handler, but then when i tried to run it, it showed error 500. Then i read somewhere that if i remove the Module Mapping, it should work.. It does technically run, but it doesnt run the way its supposed to... THIS IS WHAT IT LOOKS LIKE enter image description here THESE ARE THE FILES IN MY BugTracker FOLDER enter image description here -
How does django take queryset without database hitting?
There are so many answers and articles to say queryset in django is lazy, it isn't evaluated until you actually do something with queryset. My question is how is it possible? How does the methods, filter(), all() or order_by() etc, work not knowing what data the objects have? I assume that hitting a database and knowing data in model objects is different. But, it doesn't make sense for me. Cheers!