Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django random object and use in template
First, I'm newbie in Django. My first project is a movie web app, with model as below: class Movie(models.Model): ### movie database ### def __str__(self): return self.name def get_random(self): max_id = Movie.objects.all().aggregate(max_id=Max('id'))['max_id'] while True: pk = random.randint(1, max_id) movie = Movie.objects.filter(pk=pk).first() if movie: return movie This "get_random" func only give me 1 return. May I get more than that, let say 10? I used this model in my "movies_index" template. : {% for movie in movies %} <a href="{% url 'movies_detail' movie.get_random.pk %}"> <img src="{{ movie.get_random.poster }}" class="img-fluid"> {% endfor %} Webpage can show a movie poster with hyperlink. But when I click to, it go to another movie. Yes, because of I did "random" two time, and get 2 different results. My question is: how can I choose a set of random and use it consistency in my scenario? BTW, I'm using CBV as below: class MoviesIndex(ListView): model = Movie context_object_name = 'movies' template_name = 'movies/movies_index.html' -
Optimizing Django Text Field Lookup
I have a simple model for storing text objects: class Text(models.Model): content = models.TextField() I need content field to be unique. So, I created a custom unique index on it: CREATE UNIQUE INDEX text_md5 ON text_table (md5(content)); Now, I query for selecting specific rows: Text.objects.get(content='sample text.') Text.objects.filter(content__in=['text1', 'text2']) And it is very slow. I want postgres to find text object using its content md5. What is the most elegant way for doing this in Django. Also, I want to query this field with contains filter that is LIKE query: Text.objects.get(content__contains='text') What is the best indexing solution for optimizing these queries? I know that full text search is another option. But, I don't need complicated search features. -
(2013, 'Lost connection to MySQL server during query') django
I got thid error: (2013, 'Lost connection to MySQL server during query') I have read that I can increase database timeout. What do I do? Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'c9', 'USER': ddd, 'PASSWORD': '', 'HOST': ddd, 'PORT': '3306', 'ATOMIC_REQUESTS': True }, 'OPTIONS': { 'timeout': 99999999, 'net_read_timeout': 9999999 } -
Customizing Django 2 authentication and authorisation system
I am trying something that I believe must be so simple but nothing has worked. I have added the auth by adding into my urls.py: path('accounts/', include('django.contrib.auth.urls'), {'template_name': 'login.html', 'authentication_form': forms.LoginForm}), This is my urls.py: from django.contrib import admin from django.urls import path, include from reports import views, forms urlpatterns = [ path('', views.IndexView.as_view(), name='home'), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls'), {'template_name': 'login.html', 'authentication_form': forms.LoginForm}), ] My project has an app called reports, in here i have my templates folder and i have added my registration folder with login.html and all the relevant files. I have also created in my project (reports) a file forms.py and added from django.contrib.auth.forms import AuthenticationForm # from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput( attrs={ 'class':'form-control', 'placeholder':'Username' } )) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class':'form-control', 'placeholder':'Password' } )) My form is displayed but the class and placeholder is not been added any suggestion of what i need to add or change? my current login.html <form class="form-signin" method="post"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> <p class="mt-5 mb-3 text-muted"> <a href="{% url 'password_reset' %}">Lost password?</a> </p> </form> -
how to make wsgi work for python?
I am a new django developer and its only 20 days since I started to learn django. I have a full functioning django app in my local machine. But I am not able to make it run on my hosting. I think this has something to do with wsgi. below is my passenger_wsgi.py file import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'new_test_folder/theGoodNews/theGoodNews/wsgi.py') application = wsgi.application I have a shared hosting,which runs a cpanel on it. http://thegoodnews.anshumanpatel.in/ above link points to the app, it shows a passenger error, but I am, also not able to find its logs. Can someone suggest some resources to refer or some solution. Thanks for the help. -
django template tag not comparing properly
In my template I am using if tag but it is not working as I excepted, my template is code is : {% if request.GET.addressbook == address.pk %} checked {%else%} unchecked {{request.GET.addressbook}}, {{address.pk}} {% endif %} my url : http://127.0.0.1:8000/carts/checkout/?addressbook=2 What I am getting : unchecked 2, 2 It is showing same values of both but not comparing correctly. I already tried: {% if request.GET.addressbook|stringformat:"i" == address.pk|stringformat:"i" %} checked {%else%} unchecked {{request.GET.addressbook}}, {{address.pk}} {% endif %} and {% ifequal address.pk request.GET.addressbook %} checked {% endifequal %} All are giving same result, I am unable to figure out the problem. If anyone help me out ? -
Django REST API as backend and ReactJS as frontend integration
I'm learning ReactJS and I already have experience with Django and DRF. My aim right now is to build a rather simple web application based on a Django backend and a ReactJS frontend. (Later on, when the web app is done, I'll tackle React Native). I've been reading tons of documentation but nothing has sorted out the question: What is the best approach to integrate a Django backend with a ReactJS frontend? Should I keep them separate and connect them or should I mount ReactJS inside the Django application? Which one is the best-suited approach, taking into account maintenance and further development? Thank you very much! Any opinion/hint will be appreciated. -
django-MPTT drilldown template
I am having some trouble getting a drilldown for mptt in my template. I have the following model. models.py class Dimension_value(MPTTModel): name = models.CharField(max_length = 200, null=True, blank = True, default = '') parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name views.py def show_dimensions(request): return render(request, "accounts/dimension_detail.html", {'dimensions': Dimension_value.objects.all()}) template.py {% extends 'base.html' %} {% block head %} {% endblock %} {%block body%} <div class="container-fluid"> <div class="card"> <div class="card-body"> <h2>My dimensions</h2> {% load mptt_tags %} {% drilldown_tree_for_node dimensions as drilldown cumulative count accounts.Dimension_value.name in game_count %} {% for node,structure in drilldown|tree_info %} {% if structure.new_level %}<ul><li>{% else %}</li><li>{% endif %} {% if node == dimension %} <strong>{{ node.name }}</strong> {% else %} <a href="{{ node.get_absolute_url }}">{{ node.name }}</a> {% if node.parent_id == dimension.pk %}({{ node.game_count }}){% endif %} {% endif %} {% for level in structure.closed_levels %}</li></ul>{% endfor %} {% endfor %} </div> </div> <br> <br> <a class="btn btn-primary" href="{% url 'add_plan' %}" role="button">Add a plan</a> <button onclick="goBack()" class = "btn btn-secondary">Go Back</button><br><br><a class="btn btn-primary" href="{% url 'subscribeusertoplan' %}" role="button">Add a user to plan</a> </div> {%endblock%} I have added the view according to the documentation found here: https://django-mptt.readthedocs.io/en/latest/templates.html?highlight=examples#examples However I get the … -
When uploading an image in admin, get error: File extension 'jpg' is not allowed. Allowed extensions are: ''
I have the following model to upload images: class Image(models.Model): title = models.CharField(max_length=20) upload = models.ImageField(upload_to='uploads/img/') page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.SET_NULL) description = models.CharField(max_length=140) def __str__(self): return self.title In development I could use the admin page to upload without any issues, but for some reason in production it gives me the error: https://i.imgur.com/OhyvPzw.png I'm stumped, especially because I am able to upload it using the following model without any issues in production: class Document(models.Model): title = models.CharField(max_length=20) upload = models.FileField(upload_to='uploads/docs/') page = models.ForeignKey(Page, blank=True, null=True, on_delete=models.SET_NULL) description = models.CharField(max_length=140) def __str__(self): return self.title I've tried googling the error with no results, and the best I could find was file validation, which I thought was the purpose of using an ImageField in the first place! -
Stream Framework object is not JSON serialisable
I am facing serialisation issues when using RedisFeed with Stream-Framework and Django. Even though I explicitly defined in the celery settings to use pickle as the data interchange format, I am still facing the following error. Reference: https://clbin.com/eV19t feeds.py from stream_framework.feeds.redis import RedisFeed class PostFeed(RedisFeed): key_format = 'feed:normal:%(user_id)s' class UserPostFeed(PostFeed): key_format = 'feed:user:%(user_id)s' managers.py from stream_framework.feed_managers.base import FanoutPriority, Manager from stream_feed.feeds import PostFeed, UserPostFeed from stream_feed.models import Follow, Post class PostManager(Manager): feed_classes = {'normal': PostFeed} user_feed_class = UserPostFeed def add_post(self, post: Post): activity = post.create_activity() # add user activity adds it to the user feed, and starts the fanout self.add_user_activity(post.user.id, activity) def get_user_follower_ids(self, user_id: int): ids = Follow.objects.filter( target=user_id).values_list('user_id', flat=True) return {FanoutPriority.HIGH: ids} post_manager = PostManager() models.py class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) heading = models.CharField(max_length=160, null=True) text = models.TextField(null=False) created_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to=get_file_path, null=True, blank=True) tags = models.ManyToManyField(Tag) likes = GenericRelation('Like', related_query_name='post') def save(self, *args, **kwargs): self.text = html_clean(self.text) super(Post, self).save(*args, **kwargs) @classmethod def activity_related_models(cls): return ['user'] @property def activity_object_attr(self): return self def create_activity(self): return Activity(actor=self.user.id, verb=PostVerb, object=self.pk, time=datetime.utcnow()) settings.py BROKER_URL = 'redis://{}:{}'.format(REDIS_ADDRESS, REDIS_PORT) CELERY_ACCEPT_CONTENT = ['pickle'] CELERY_RESULT_BACKEND = 'amqp' CELERY_TASK_SERIALIZER = 'pickle' CELERY_EVENT_SERIALIZER = 'pickle' CELERY_RESULT_SERIALIZER = 'pickle' BROKER_POOL_LIMIT = None -
How do I attach a field from a related object to a Django queryset?
We are on Django 1.5 (for now, until the boss can be convinced otherwise...) The app has multiple objects that reference each other as foreign keys: class Result(models.Model): quiz = models.ForeignKey(Quiz) user = models.ForeignKey(User) class Quiz(models.Model): quiz_type = models.CharField(max_length=1, choices=TYPE_CHOICES, default=TYPE_POST) name = models.CharField(max_length=200) lesson = models.ForeignKey(Lesson, blank=True, null=True, db_index=True) class Lesson(models.Model): title = models.CharField(max_length=200) unit = models.ForeignKey(Unit) class LessonStatus(models.Model): user = models.ForeignKey(User) lesson = models.ForeignKey(Lesson) attempts_remaining = models.IntegerField(default=1) passed = models.PositiveIntegerField(default=0) For reporting, I need to get all Results for a specified user (or users), apply some filters based on user input, and then display a table with data that includes fields from User, Quiz, Lesson, and Unit. (It also checks LessonStatus for some display options.) Right now, most of the foreign key queries are being done in a loop in the template, which is.. bad. I tried using select_related - my query log shows that it is successfully doing the table joins, but doesn't actually assign the fields to anything, so it seems that when I reference a related field, it's still causing a new query. I have found similar questions, where the answers suggested using annotate, but that's not working for me. I have tried: r = … -
Pre-populating a field from Key Field in Django CreateView
I am using Django 2.0 on Python 3.6. I am trying to create a record in a table using CreateView (and able to create records as expected). I am now trying to populate the key field in the form being called by following a link with a primary key value. I searched extensively on the net (including of course this site) but something close I came across was on the this query. (ref. comments from @keshav-agrawal) My work flow goes something like this: 1. Generate a list of properties in a real estate 2. Click on one of the hyperlinked lists when the form called by CreateView opens. 3. My model is: class complaint(models.Model): complaint_number = models.AutoField(primary_key=True) complaint_date = models.DateField(auto_now=True, editable=False, verbose_name='Complaint Date') unit_number = models.ForeignKey(Res_Units, on_delete=models.SET_NULL, null=True) job_type = models.ForeignKey(job_type, on_delete=models.SET_NULL, null=True) complaint_short_desc = models.CharField(max_length=200, help_text='Enter a short description') complaint_long_text = models.TextField(max_length=1000, help_text='Enter detailed description of the job (max 1000 chars)') 4. The template: {% extends "base_pl.html" %} {% block content %} <h1>Create New Complaint</h1> <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit" /> </form> {% endblock %} 5. views.py class ComplntCrea(PermissionRequiredMixin, CreateView): model = complaint fields = '__all__' permission_required = 'maint.can_create_complaint' template_name … -
Set ModelForm related objects to existing instances
I'm trying to create a form with pre-set related objects that can't be editable. I've tried many things (and have googled a lot about) but I can't seem to find a nice/clear way to do this. Here's is a minimal example. The relevant models are (some fields, such as PKs, are omitted for brevity): class Book(models.Model): title = models.CharField() class Label(models.Model): name = models.CharField() class Comment(models.Model): book = models.ForeignKey(Book) label = models.ForeignKey(Label) user = models.ForeignKey(settings.AUTH_USER_MODEL) comment = models.TextField() I'd like to present a Form (or ideally a FormSet) to a user, so he/she can create a new comment for a given (book, label) pair. The user must not be allowed to choose the (book, label) pair; this pair is determined by the application, from already existing. To achieve that I create the following form: class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['comment'] # fields = ['comment', 'book', 'label', 'user'] Given a book and a list of labels, I want for create a FormSet with as many forms as labels. Each form should have a pre-set book, label and user, so the user should only be allowed to specify the comment and a new entry should be created when … -
Django static files served in docker found with findstatic but 404 from server
I am running a Django/Angular/Docker build in development mode mounting the Angular build in the Django container to serve as static content. However, I am getting a 404 for all static files. The weird thing is that running python3 manage.py findstatic index.html correctly finds the file. docker-compose -f docker-compose.yml run backend python3 manage.py findstatic index.html Found 'index.html' here: /django/static/index.html My settings are pretty straight forward. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/') ] My urls -- from django.contrib.staticfiles.views import serve # root is served by angular index url(r'^$', serve, kwargs={'path': 'index.html'}), I am wondering how it can be found with findstatic but not found when performing an HTTP request? This returns a 404 with the following message 'index.html' could not be found -
Heroku/Git Push Dependancy Error
I am trying to push my Django website up to Heroku. When it comes to this dependancy, I get this error: remote: Downloading https://files.pythonhosted.org/packages/2e/83/89b5adbc37d1bbf7b486a2c1c00e8037e6f801e8c053c4897bb82d9510c6/PyAutoGUI-0.9.36.tar.gz (46kB) remote: Complete output from command python setup.py egg_info: remote: Traceback (most recent call last): remote: File "<string>", line 1, in <module> remote: File "/tmp/pip-build-pfkxr3gz/PyAutoGUI/setup.py", line 6, in <module> remote: version=__import__('pyautogui').__version__, remote: File "/tmp/pip-build-pfkxr3gz/PyAutoGUI/pyautogui/__init__.py", line 115, in <module> remote: from . import _pyautogui_x11 as platformModule remote: File "/tmp/pip-build-pfkxr3gz/PyAutoGUI/pyautogui/_pyautogui_x11.py", line 7, in <module> remote: from Xlib.display import Display remote: ModuleNotFoundError: No module named 'Xlib' remote: remote: ---------------------------------------- remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-pfkxr3gz/PyAutoGUI/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to aaronmaziewebsite. remote: To https://git.heroku.com/aaronmaziewebsite.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/aaronmaziewebsite.git' I already have PyAutoGUI and Xlib installed on my machine. I'm following this tutorial: https://www.youtube.com/watch?v=4DggiEkbCTg https://www.codingforentrepreneurs.com/blog/go-live-with-django-project-and-heroku/ Any advice? -
Set django model instance field like dictionary
In django, we can update model instance field like: from .models import Credentials current_cre=Credentials.object.get(user=request.user) current_cre.fb_name='Name' current_cre.fb_pass='****' current_cre.save() Is there any way that I can do it like dictionary item: current_cre['fb_name']='Name' current_cre['fb_pass']='Pass' So I can iterate the process like: for field_name in List_Fields: current_cre[field_name]=request.POST[field_name] thanks in advance. -
how to pass multiple parameters to an FBV Django
I am having a very hard time figuring this out on my own. I want to create a function that works something like a Detail View, this function needs to get all items that are filtered by three parameters carrito_id herramienta_id transaction_id I want to create something like this : items = Transaccion.objects.filter(carrito_id=pk, herramienta_id=???, id=???? activo =True) that is exactly what I'm looking for. The issue behind all this, is the way the view that will trigger this call, gets its data. The objective is to have a inventory of tools in a cart like system, where carts can be created, assigned to a employee and tools can be added or removed from the cart. also i wanted to keep a record of all tools that got damaged. so my models are as follows: Item : this model has all common field that define a tool. toolmodel : Is not the real name, since every tool has unique attributes that define the tool, I create a model for every tool type that I own, and the Item class gets inherited by all classes of this type. i.e.( class Cutters(Item):). Empleados: this table hold employee information Carritos: this table has a … -
Why Django is not filtering many-to-many relationship?
I am working on Django website and I am trying to fetch data using Django ORM. My database classes that I am working with are, class Websites(models.Model): domain_name = models.TextField() is_verified = models.BooleanField(default=False) class APIData(models.Model): api_key = models.CharField(max_length=50) websites = models.ManyToManyField(to=Websites) So when I try to get all APIData and exclude that where websites is_verified is false, it returns me all the data. I am using this query, APIData.objects.all().exclude(websites__is_verified=False) Which is returning me all APIData objects. What I want is that all APIData objects that have one or more websites object and all of them are verified. Can anyone tell me what am I doing wrong here? Thanks. -
Pandas to_html show data types, how to display only values?
I have read on here and search the internet, but nobody has the same problem. When I used to_html, I get output like below for my website with Django. How can I show values only? And not have the data types as shown. I have a list below: l1 = [] l2 = [] l3 = [] l4 = [] l5 = [] amorttable = pd.DataFrame.from_records(list(zip(l1, l2, l3, l4,l5)), columns=['Monthly_Payment', 'Interest', 'Principal', 'Remaining_Balance','Payment_Number']) mortgageresult = amorttable.to_html(index=False) result from pandas to_html -
django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]
I using Django version 2.0.7 and I tried to make a Date Module Field Until I faced this error : Date = models.DateField(blank=True, default='', null=True, help_text='today date.') I used this code before and it worked but now after python manage.py makemigrations that I use python manage.py migrate I faced to this error. full logs: Operations to perform: Apply all migrations: Blog, Portfolio, admin, auth, contenttypes, sessions Running migrations: Applying Blog.0002_auto_20180728_0218...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "D:\Learn\Projects\Django\myvenv\lib\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 "D:\Learn\Projects\Django\myvenv\lib\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 "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\db\migrations\operations\fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\db\backends\base\schema.py", line 525, in alter_field old_db_params, new_db_params, strict) File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\db\backends\postgresql\schema.py", line 122, in _alter_field new_db_params, strict, File "D:\Learn\Projects\Django\myvenv\lib\site-packages\django\db\backends\base\schema.py", line 629, in _alter_field old_default = self.effective_default(old_field) … -
Get all checked checkboxes javascript or jquery
I would like to get dynamically in an array all of the checked checkboxes every time the user clicks on one of them using Jquery or javascript. PS: I'm using Django + Python to generate the options and Bootstrap to style them Here is my code : {% for option in options %} <div class="input-group" style="margin-bottom: 7px;"> <div class="input-group-prepend"> <div class="input-group-text"> <input type="checkbox" name="checks[]" aria-label="Radio button for following text input" id="option_choice" class="ipad_pro" value="{{ option.name }}" onclick="getCheckedCheckboxes('option_choice')"> </div> </div> <input style="background-color: #fff;" type="text" class="form-control" disabled=True value="{{ option.name }} {{ option.price }}€" aria-label="Text input with radio button"> </div> {% endfor %} So far, I've tried to do it like this : function getCheckedBoxes(chkboxId) { var checkboxes = document.querySelectorAll('#' + chkboxId); var checkboxesChecked = []; for (var i=0; i<checkboxes.length; i++) { if (checkboxes[i].checked) { checkboxesChecked.push(checkboxes[i]); } } return checkboxesChecked.length > 0 ? checkboxesChecked : null; } var checkedBoxes = getCheckedBoxes("option_choice"); But that hasn't worked out for me. Please help me if you know the answer to my problem. -
How to assign existing objects into a Many-to-One relationship using Django-Rest-Framework?
I have a Many-To-One foreign key relationship between Users and a Company. In order to add users to a company, I need to use reverse relations. Each Company has many users. Using the python shell, I can add existing users to a company by doing: company.user_set.add(user) I'm stuck on how to perform the same operation on a serializer. I'm able to PATCH a list of users, and it will save the relationship, but I want to append a user instead of overwriting all of them every time. I've seen suggestions such as getting the current list of users and appending a new user, and then saving the new list. I don't know how to implement that function though. class Company(models.Model): company_name = models.CharField(max_length=255) address = models.CharField(max_length=255) state = models.CharField(max_length=255) city = models.CharField(max_length=255) class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) USERNAME_FIELD = 'email' is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) objects = UserManager() class CompanyUpdateSerializer(serializers.ModelSerializer): user_set = UserSerializer(many=True) class Meta: model = Company fields = ('company_name', 'user_set',) def to_internal_value(self, data): self.fields['user_set'] = serializers.SlugRelatedField( queryset=User.objects.all(), many=True, slug_field='email') return super(CompanyUpdateSerializer, self).to_internal_value(data) -
ImportError: cannot import name 'get_default_renderer'
Im installing the ckeditor app in my django, follow the instructions from ckeditor documentation at the moment of run the runserver, doesn't works, well,I get the error when add the from ckeditor.fields import RichTextField in the models.py This is my settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'suj4$h^8p&x#p_#i$_p&z@&d^46=#7kf6a#_tkqh68er^)872s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'ckeditor', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Django Suit configuration example SUIT_CONFIG … -
Django - runserver in "test-mode" with test databases
I'm trying to create tests for my Django application but I'm having some trouble creating a test database. I'd like to keep the existing structure while entering new curated test-information, creating test users, uploading test content, etc. Which I can then populate a test database with so that I have curated data on which I can test edge-cases. Creating a test database seems simple, just run python manage.py test --keepdb. Getting entries into it seems more difficult. Is it possible to run django in "test mode" with the test database being used so that I can use the website UI to enter all the data, or is there some other better way to do it entirely? -
Issue while adding inline user profile form with Django admin user form
I got stuck with small issue in django project, I hope I can get some good answers here. I have added user profile inline form with django User form by doing code like this: from django.core.exceptions import ValidationError from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.contrib.auth.models import User from djangocalendar.models import UserProfile from tableapp.models import * from djangocalendar.models import * from django import forms class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = True verbose_name_plural = 'profile' class MyUserChangeForm(UserChangeForm): def clean_first_name(self): if self.cleaned_data["first_name"].strip() == '': raise ValidationError("First name is required.") return self.cleaned_data["first_name"] def clean_last_name(self): if self.cleaned_data["last_name"].strip() == '': raise ValidationError("Last name is required.") return self.cleaned_data["last_name"] # Define a new User admin class MyUserAdmin(UserAdmin): form = MyUserChangeForm inlines = UserProfileInline, # Register your models here admin.site.unregister(User) admin.site.register(User, MyUserAdmin) Issue I am facing with this, This inline appears with User Add form and with Change user form too. I don't want it to display while adding user. Like In this screenshot: Inline form appears with add User form! I don't want this to add inline form here. But I want to display inline form while editing user with other forms like personal form, information form.