Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why should I use Django model Manager?
Please someone give me an answer necessary to use django model manager. I've finished some project earlier. But i don't use model manager. Is it must need in project ? -
Div on base template doesn't appear in the extension
I am extending a template , and the two divs before the content block of container doesn't show in any of the ways, the only solution i found is to put this 2 divs in the child , but of course it will lose the sense using extend then. Someone can tell me what I am missing? Thanks in advance. I have the following base template : <!doctype html> <html lang="es"> <head> <title>{% block head_title %}{% endblock %}</title> {% block extra_head %} {% endblock %} <!-- Required meta tags --> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <!-- Fonts and icons --> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css"/> {% load static %} {% block extra_css %} {% endblock %} </head> <body {% block body_attributes %} {% endblock %} > {% block body %} {% if messages %} <div> <strong>Messages:</strong> <ul> {% for message in messages %} <li>{{message}}</li> {% endfor %} </ul> </div> {% endif %} <!-- THIS 2 HERE DOESN'T APPEAR --> <div class="page-header header-filter" style="background-image: url({% static "material/img/pic.jpg" %}); background-size: cover; background-position: top center;"> <div class="container"> {% block content %} {% endblock %} </div> </div> {% endblock %} {% block extra_body %} {% endblock … -
Associating Django user with another user
How should I go about associating a Django user with another user of the same type? are foreign keys still applicable to be used in this situation? -
MemoryError with too large cursor in PyMongo with Pagination
I have a cursor of objects that I'm trying Paginate. The total items I want is 25, but the way Pagination with Django works, it requires the whole cursor. In private testing, presumably because my home box has more RAM and the like, I do not have these issues. However, when pushing to the production machine, which has only 2GB of memory, I get a MemoryError, presumably because the cursor is too big. I can use .limit(25) and .skip() in order to only retrieve 25 things at a time, however in order for Pagination to work, I need the total number of objects. Unfortunately, .count() seems to require getting the entire data of the cursor. Ideally, I can make this work if I can somehow get the size of a lookup and only 25 actual objects out of the cursor. So I suppose the question is, is there a way to get a cursor's size that's not via .count() (which gets the whole cursor's data). lookup = players.find({field: {'$exists': True}}).sort(field, DESCENDING) //This returns a MemoryError lookup = players.find({field: {'$exists': True}}).limit(25).skip(25).sort(field, DESCENDING) //This does NOT return a Memory Error. However, when I do the following: lookup.count() //This also has a MemoryError. … -
Django Rest Framework - object of type 'type' is not json serializable error
I am creating rest api using Django Rest Framework. I am using Djanfo 2.0.5 and python 3. I am getting error "Object of type 'type' is not JSON serializable." at the time of submitting form in browser. I tried with POSTMAN and also getting same error. I have attached snaps of my code of model, serializers and view classes. -
How to auto generate slug from my Album model in django 2.0.4
I have an Album field with a list of Songs class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=250) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000,blank=True) slug = models.SlugField(unique=True) def __str__(self): return self.album_title class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) artist = models.CharField(max_length=250, blank=True) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=100) def __str__(self): return self.artist I would like to know how to generate slugs from the album title. I am following a tutorial which is using django 1.8 which uses regular expressions to implement this task. But from looking through the documentation they have introduced a more simpler approach (''). So can you help explain how I can implement it for a beginner to understand not only in this context but if possible across board. Thanks in advance. -
How to remove the 'tests' app from my django project migrations?
I have a failure in the tests app migrations, I don't use tests directly and what app is using it. Is there a way to ignore its migrations or drop it? Applying tests.0001_initial... OK Applying tests.0002_auto_20160310_1052...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/app/.heroku/python/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1170, "BLOB/TEXT column 'name' used in key specification without a key length") -
Django UserAdmin's add_fieldsets?
I'm following a tutorial on making a custom User for authentication purposes. The tutorial used a certain property add_fieldsets within UserAdmin. What does this mean? I can't seem to find any documentation on this. Here is the snippet: class UserAdmin(UserAdmin): """Define admin model for custom User model with no email field.""" fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ('Contact info', {'fields': ('contact_no',)}),) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'),}),) list_display = ('email', 'first_name', 'last_name', 'is_staff') search_fields = ('email', 'first_name', 'last_name') ordering = ('email',) Here is the tutorial I was following: How to use email as username for Django authentication (removing the username) -
left join in Django
Assume u have two models. Let's name them model 1 and model 2. I want to make a join so that a always display all model1 objects, but if there is a related model2 object it is also added to the query result. Which is the best way to achieve this? Sorry for my beginner question, I'm new to Django. following simplified models as an example: Model 1: computer id computer name mac address Model 2: log file id mac address text file required query: list of all computers and the log file if there is any in the database. The join is made by the value of the mac address. Thank you! -
Render template with context after creating objects
Consider a textarea input to enter emails. The view has a forloop: for each email the view tries to create a user. Then, if the user is created, I append it to my array "newUers", if the user already exists, I append it to the "alreadyUsers" array. When the loop ends, I want to render a view with these arrays. But it does not work... The users are correctly created but the view does not render the template. Any idea? invitations.html: a textarea with an an ajax call on submit <div id="invitations"> <label>Enter your clients email</label> <textarea v-model="invitations" class="textarea" id="invitations" name="invitations"></textarea> </div> <div> <input id="send" type="submit" value="Save" @click="submit()"> </div> user_invitation.js: the ajax call (based on Vue) var vue = new Vue({ el: '#invitations', data: { invitations: '', }, methods: { submit: function () { var self = this; $.ajax({ type: 'POST', url: '/accounts/invitations/create/', data: { invitations: this.invitations, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, context: this, success: function () { console.log("ajax success"); }, error: function () { console.log("ajax error"); } }) } } }); views.py def InvitationCreateView(request): newUsers = [] alreadyUsers = [] for client in request.POST['invitations'].split('\n'): try: # Get informations for creating the User user = User.objects.create( username=client, email=client, ) user.groups.add(Group.objects.get(name='Clients')) user.save() newUsers.append(client) … -
django - how to save(update) datetime field to database
I've got some problems with Django DateTimeField. I want my script to add 7 days to expiration_date field in database when some conditions occur. models.py class TrainingPlan(models.Model): user = models.OneToOneField(User, on_delete='CASCADE') exercise_list = models.ManyToManyField(Exercise) expiration_date = models.DateTimeField(default=datetime.now(timezone.utc)) reps = models.PositiveIntegerField(default=10) views.py def check_plan_expiration_date(): user_exp_date = user_trainingplan.expiration_date now = datetime.now(timezone.utc) if user_exp_date <= now: user_exp_date = datetime.now(timezone.utc)+timedelta(days=7) user_exp_date.save() else: return user_exp_date Error I get: 'datetime.datetime' object has no attribute 'save' -
Django AJAX requests: create and delete a course. deleting a course not working.
In my app, I want to create and delete instances of Course using ajax. I have finished my create functionality, and it is as follows: urls.py app_name = 'courses' urlpatterns = [ path('index/', views.index, name='index'), path('create/', views.create, name='create'), path('delete/<int:course_id>/', views.delete, name='delete'), ] views.py from django.shortcuts import render, redirect from courses.models import Course from django.http import JsonResponse from django.forms.models import model_to_dict # Create your views here. def index(request): context = { 'courses':Course.objects.all(), } return render(request, 'courses/index.html', context) def create(request): if request.method == 'POST': course = Course.objects.create(name=request.POST['name'], description=request.POST['description']) # return redirect('courses:index') # course is a queryset, we need to change it to a dictionary return JsonResponse(model_to_dict(course)) else: return render(request, 'courses/index.html') def delete(request, course_id): course = Course.objects.get(pk=course_id) if request.method == 'POST': course.delete() courses = Course.objects.all() return JsonResponse((courses)) # return JsonResponse(model_to_dict(course)) else: return render(request, 'courses/index.html', {'courses':Course.objects.all()}) here is the jquery for it: $(document).ready(function(){ $('.course_form').submit(function(event){ console.log(event); event.preventDefault(); $.ajax({ url: '/courses/create/', method: 'post', data: $(this).serialize(), success: function(response){ console.log(response); $('.courses').append(`<p>Name: ${response.name}, Description: ${response.description}</p> <form class="delete_form" action="/courses/delete/${response.id}/" method="post"> <input type="submit" value="delete"> </form> `) $('.course_form')[0].reset(); } }); }) $('delete_form').submit(function(event){ console.log(event); event.preventDefault(); $.ajax({ url: '/courses/delete/', method: 'post', success: function(response){ console.log(response); } }) }) }) once I create a course, I append a delete button under it. the problem is that … -
return Database.Cursor.execute(self, query, params) IntegrityError: NOT NULL constraint failed:
I'm currently working on a small project using Python's Django framework technology. I tried to extend the native user model to create 2 types of users And I did it like so: class User(AbstractUser): is_student = models.BooleanField(default = False,) is_teacher = models.BooleanField(default = False,) #Particularly for Teacher: class Teacher(User): is_teacher = True user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True,) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' or 'username' REQUIRED_FIELD = ['username'] #Particularly for Student: class Student(User): is_employer = True user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True,) reg_num = models.CharField(max_length = 45) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' or 'username' REQUIRED_FIELD = ['username'] whenever I try to create and save either of the users like so from my shell from django.db import models from hire.models import Teacher j = Employee(username = 'teacherAubrey', email = 'learn@aubrey.com', password = 'squarerootof69is8sum') j.save() return Database.Cursor.execute(self, query, params) IntegrityError: NOT NULL constraint failed: hire_teacher.email What do you figure to be the problems here ? I intentionally did not declare username, password and email instances in my Teacher and Student classes because I'm inheriting them from the User class -
Celery Beat doesn't work with Django
I configured Celery to work with Django but whenever I start Celery Beat it never gets past this stage > LocalTime -> 2018-05-20 16:55:50 Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%DEBUG . maxinterval -> 5.00 minutes (300s) No tasks scheduled. I'm using Celery 4.1.0 -
How to know the app responsible for the error when running migration?
I have the error below when I run "Heroku run manage.py migrate", strangely it didnt happen for me locally or in heroku before. My guess is that one used library is upgraded and introduced the bug. Traceback (most recent call last): File "/app/.heroku/python/bin/manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/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 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.6/site-packages/tests/models.py", line 6, in <module> class Place(models.Model): File "/app/.heroku/python/lib/python3.6/site-packages/tests/models.py", line 7, in Place parent_place = models.ForeignKey('self', blank=True, null=True) TypeError: __init__() missing 1 required positional argument: 'on_delete' How to get over this error? -
Django finding URLs for templates
I'm trying to figure out a way to build a list of URLs for my content in my django app. I have the Models and Views setup properly, and I already figured out how to access this data in the Templates, but I'm not quite sure how I can start making URLs for them. The data I have is continents and the countries of these continents. The template should render a list of the continents, but as links. Here's an example with one continent: <ul id="continentMenu"> <li><a href="insert-path-to-continent-using-the-template">Scandinavia</a></li> </ul> My urls.py looks like from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('countrydata.urls')), url(r'^', include('selectui.urls')), ] and my index.html looks like {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">logout</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %} My continentmenu.html, which I'm trying to have the links for the continents in, looks like {% extends "base.html" %} {% load staticfiles %} {% block content %} <div class="container-fluid"> <div class="l"> {% for continent in all_continents %} … -
django save() reports no errors but changes are not been saved to a specific record
I am trying to make changes to a record but so far failed. It doesn't generate any errors but no change is saved to the selected record. I am on django 1.11: arrival_invoice=Arrival.objects.get(pk=invoice_id) if invoice_editable(arrival_invoice.processedon): serializer=ArrivalSerializer(data=data,current_id=invoice_id,only_invoice=1) if serializer.is_valid(): content=serializer.validated_data arrival_invoice.provider_id=content['provider'] arrival_invoice.processedon=content['processedon'] arrival_invoice.provider_reference=content['provider_reference'] arrival_invoice.internal_reference=content['internal_reference'] arrival_invoice.save(update_fields=['provider_id','processedon','provider_reference','internal_reference']) status=200 reply['detail']='Saved' else: reply['detail']=create_error_json(serializer.errors) else: reply['detail']='Too old to be edited' The serializer does proper checking of the data and all but so far, I failed to make changes. I tried one field at a time for testing but still nothing changes. I added update_fields to save() to try. content variable does contain the desired data as well. What am I doing wrong? -
A django field for select and add tags
In django model.ManyToManyField has a ModelMultipleChoiceField that show related model item in the form. With this we can select from previous item that saved to database. For example for tagging, corresponding field must be add new item list to database. But when new item send to it key error occured. I found that this new item must be key/value pair that key is Id and value is name of tag. How to create such field with models.ManyToManyfield, ModelMultipleChoiceField, SelectMultipleField. Below link is an example. https://stackoverflow.com/questions/ask -
django queryset how to add otherfield not in models
Using django2.0.2 python3.4 models.py class Userinfo(models.Model): useruid = models.BigAutoField(db_column='UserUID', primary_key=True) useremail = models.CharField( db_column='UserEmail', unique=True, max_length=100) userpassword = models.CharField(db_column='UserPassword', max_length=128) passwordsalt = models.CharField(db_column='PasswordSalt', max_length=128) class Meta: managed = False db_table = 'userinfo' i want result like this sql query selecet useruid,useremail,userpassword,passwordsalt,0 AS Dummy1,0 AS Dummy2 from Userinfo how to add django queryset add extra field i tried this userinfos = Userinfo.objects.all().annotate(dummy1=Value(0, output_field=IntegerField()), dummy2=Value(0, output_field=IntegerField()) and print(model_to_dict(userinfos[0])) dummy is not in dict -
Django admin in microservice architecture
I have a large Django project which is basically a monolith containing apps. I need to break it to microservices. I have 2 questions that I couldn't find a clear answers to: Currently we're using Django admin extensively and I wonder if it's possible to continue using it once the monolith is broken. It means reading and manipulating data from all the microservices in a "used to work on" UI. It will also would be helpful for this process to be done more smoothly. Authentication and authorization - Would we still be able to use this built in "app" in a microservice architecture? Is it possible to take this pare only to another service and communicate with it over HTTP? -
Javascript doesn't work in django template
I have a template which inherits from a base template in javascript. Here is the base template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>{% block title %}{% endblock %}</title> {% include 'base/css.html' %} {% block head %}{% endblock %} </head> <body id="page-top"> {% include 'base/navbar.html' %} {% block content %}{% endblock %} {% include 'base/js.html' %} {% block js %}{% endblock %} </body> </html> Here is the template where the javascript doesn't work: {% extends 'base.html' %} {% load static %} {% block head %} <link href="{% static 'css/card.css' %}" rel="stylesheet"></link> {% endblock %} {% block content %} <div class="card-wrapper"> {% for account in object_list %} <div id="make-3D-space"> <div id="product-card"> <div id="product-front"> <div class="shadow"></div> <img src="" alt="" /> <div class="image_overlay"></div> <div id="view_details"><a href="{{ account.get_absolute_url }}">View details</a></div> <div class="stats"> <div class="stats-container"> <span class="product_price">{{ account.price }}</span> <span class="product_name">{{ account.get_arena_readable }}</span> <p>King level {{ account.king_tower }}</p> <div class="product-options"> <strong>SIZES</strong> <span>XS, S, M, L, XL, XXL</span> <strong>COLORS</strong> <div class="colors"> <div class="c-blue"><span></span></div> <div class="c-red"><span></span></div> <div class="c-white"><span></span></div> <div class="c-green"><span></span></div> </div> </div> </div> </div> </div> </div> </div> {% endfor %} </div> {% endblock %} {% block js %} <script src="{% static … -
Very simple django wysiwyg with no dependencies
I need a very simple wysiwyg editor that I would integrate with Django. I need just to have paragraphs, and lists, and not to be dependent on any library like React,jquery etc, and may have a chracter counter just pure javascript. I know that are packages for Ckeditor, Tinymce, but I didn't found how to config them to have only what I need. Also if is possible, to integrated myself, instead of using a full package, because I want to have the possibility to modify the widget rendering. -
django categorizing model instances
When I run python3 manage.py makemigrations after saving the below code, it shows error: todo.Task.status: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. from django.db import models STATUS_CHOICES = ('complete', 'incomplete', 'todo') class Task(models.Model): name = models.CharField(max_length = 128) due = models.DateTimeField(blank = True, null = True) status = models.CharField(max_length = 16, choices = STATUS_CHOICES) def __str__(self): return (f"{self.name}") I want to categorize every Task instance according to todo, complete or incomplete. This property is to be specified while creating every Task instance. The tasks are to be shown on different columns on HTML page. The above code doesn't work. Please Help. -
Django rest PUT method to update foreign key data
DRF doc's say's i need to override serializers create and update methods to update and/or create nested data. But when i am trying to edit existing descriptions my code creates a new one. Is there a simple way to detect which descriptions was edit and update only it? class TaskSerializer(ModelSerializer): url = HyperlinkedIdentityField( view_name='tasks:tasks-detail', lookup_field='pk', ) author = SlugField(source='author.username') executor = SlugField(source='executor.username') descriptions = DescriptionSerializer(many=True) class Meta: model = Task fields = ( 'pk', 'url', 'title', 'project', 'status', 'author', 'executor', 'descriptions' ) def create(self, validated_data): descriptions_data = validated_data.pop('descriptions', None) author = validated_data.pop('author', None) executor = validated_data.pop('executor', None) try: task_author = User.objects.get(username=author['username']) task_executor = User.objects.get(username=executor['username']) except User.DoesNotExist: raise ValidationError( _("Такого пользователя не сущетсвует!")) task = Task.objects.create(author=task_author, executor=task_executor, **validated_data) if descriptions_data: for description in descriptions_data: description, created = Description.objects.get_or_create( text=description['text'], task=task ) task.descriptions.add(description) return task def update(self, instance, validated_data): descriptions_data = validated_data.pop('descriptions', None) instance.title = validated_data.get('title', instance.title) instance.project = validated_data.get('project', instance.project) instance.status = validated_data.get('status', instance.status) author = validated_data.pop('author', None) executor = validated_data.pop('executor', None) try: if author: task_author = User.objects.get(username=author['username']) instance.author = task_author if executor: task_executor = User.objects.get(username=executor['username']) instance.executor = task_executor except User.DoesNotExist: raise ValidationError( _("Такого пользователя не сущетсвует!")) descriptions_list = [] if descriptions_data: for description in descriptions_data: description, created = Description.objects.get_or_create( text=description["text"], … -
Django get updated items
There is a queue of tasks for humans. I want to take one unfulfilled task from the queue and assign an executor. I use update() and nested query to prevent a race condition. sliced_queryset = Tasks.objects.filter(done=False, executor__isnull=True)[:1] task = Tasks.objects.filter(id__in=sliced_queryset).update(executor=request.user) update() returns the number of rows matched. I want to have updated object in task variable. Any ideas?