Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django running in Docker container: makemigrations and migrate do not see app's model on launch
I have Django running in a Docker container. The CMD of my Docker file simply runs a script, launch.sh, which inter alia has the following commands: python manage.py makemigrations --no-input --verbosity 1 python manage.py migrate --no-input --verbosity 1 So, these commands make migrations on my Django project, and then perform the migrations (if any), whenever my container launches. This works as intended for the specifically project-level migrations. However, inevitably, only the project-level migrations are made — that is, the app-level migrations are never made and so are never performed. But if I log into the container (with docker exec -it ... bash) and execute the same migration commands manually, the app-level migrations are made and performed. Googling and numerous variations to my code haven't turned up any explanations for this behavior or any fix, so I'm stumped. Any ideas? -
How to change 'None' in admin to ''
How can I do in order to disable None in my table, the table AUTORDOCUMENT only have foreign keys. I tried in admin.py: from django.contrib.admin.views import main class MyModelAdmin(admin.ModelAdmin): def __init__(self,*args,**kwargs): super(MyModelAdmin, self).__init__(*args, **kwargs) main.EMPTY_CHANGELIST_VALUE = '' but I'm still getting None -
Django Unit Testing - Client login does not seem to work
I have been referring to the tutorial in https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing when working on my own unit testing. My unit test codes are below: from django.core.urlresolvers import reverse from django.test import Client, TestCase from django.contrib.auth.models import User from companies.models import Company class ContactViewTest(TestCase): def setUp(self): self.client = Client(HTTP_HOST='localhost:8000') company = Company(name='Test') company.save() user = User.objects.create(username='test_user1', email='test_user1@test.com') user.set_password('password') user.save() self.user = user self.company = company def test_logged_in_all_contacts_correct_template(self): c = self.client user_login = c.login(username=self.user.username, password=self.user.password) self.assertTrue(user_login) resp = c.get(reverse('all-contacts'), follow=True) # Check if user is logged in self.assertEquals(str(resp.context['user']), 'test_user1') # Check if response is "success" self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp, 'all_contacts.html') Upon running python manage.py test contacts.tests, I ran into a few errors. The first being self.assertTrue(user_login) which returns AssertionError: False is not true The second being self.assertEquals(str(resp.context['user']), 'test_user1') which returns AssertionError: 'AnonymousUser' != 'test_user1' when I removed self.assertTrue(user_login) I am not really sure what went wrong other than the client.login() did not work as I expected so thanks in advance to whoever can help. -
Django Correct Media Settings
I have these settings for my django project hosted on a virtual server, but not Heroku etc. I require some assistance, as it seems that the tool is not able to find the pictures i save while i create a blogpost. I followed the right steps from the documentations and still i can't find where the issue is. My settings are: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "static_root") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static_in_pro", "our_static"),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root") And this is the folder structure. I would owe you a lot for your help! -
Update database field with multiple buttons
I'm working on a small project using Django and I have a detail page of a digital product. The user should have the avability to update the status of this product through 3 Buttons. This status represents one ChoiceField in the database. The choices are: Dismiss, In Review and Approve My question is, what is the best way to solve that (without Ajax)? My first idea was to add 3 forms and every form has another action url. I'm still fairly new to Django and don't know if my approach is the best solution. -
Details not displaying on template page
I'm trying to get details of a single record to display on a template page with Django, but I can't see anything My urls.py from django.contrib import admin from django.urls import path from calendarapp import views urlpatterns = [ path('', views.index, name='index'), path('flight/<int:pk>', views.details, name='details'), path('admin/', admin.site.urls), ] My views.py from django.shortcuts import render from .models import Flight def index(request): flights = Flight.objects.all()[:5] return render(request, 'calendarapp/index.html', {'flights': flights}) def details(request, pk): flight = Flight.objects.get(id=pk) return render(request, 'calendarapp/index.html', {'flight': flight}) My template page {% extends 'calendarapp/base.html' %} <div class='container'> {% block content %} <p>departure time - {{ id.dep_time }}</p> <p>departure delay - {{ flight.dep_delay }}</p> <p>arrival time - {{ flight.arr_time }}</p> <p>arrival delay - {{ flight.arr_delay }}</p> <p>cancelled - {{ flight.cancelled }}</p> <p>carrier - {{ flight.carrier }}</p> <p>tail number - {{ flight.tailnum }}</p> <p>flight - {{ flight.flight }}</p> <p>origin - {{ flight.origin }}</p> <p>destination - {{ flight.dest }}</p> <p>air time - {{ flight.air_time }}</p> <p>distance - {{ flight.distance }} km</p> <p>duration - {{ flight.duration }}</p> {% endblock %} </div> I'm not sure why my details are not displaying? -
Django: Updating foreign key relation; custom form save or model function?
I have two approaches here to update the foreign key relation in my model and I really struggle to decide which one to choose. Do you have any tips or best practice which one is 'the better one'? Version 1: views.py def checkout_page(request): session_order_id = request.session['order_id'] o = Order.objects.get(order_id=session_order_id) if request.POST: transaction_profile = TransactionProfileModelForm(request.POST) if transaction_profile.is_valid(): # Save method transaction_profile.save(o) forms.py [...] def save(self, o, commit=True): obj = super(TransactionProfileModelForm, self).save(commit=False) if commit: obj.save() o.transaction_profile = obj o.save() return obj Version 2: views.py def checkout_page(request): session_order_id = request.session['order_id'] o = Order.objects.get(order_id=session_order_id) if request.POST: transaction_profile = TransactionProfileModelForm(request.POST) if transaction_profile.is_valid(): t = transaction_profile.save(commit=False) t.save() o.update_order_model_with_transaction_profile(t) model.py class Order(models.Model): [...] def update_order_model_with_transaction_profile(self, t): self.transaction_profile = t self.save() -
Django - Getting values from Model
I want to get post type value in my template .html from Model OUTSIDE loop. I can get value inside loop. My Model looks like: models.py: class Post(models.Model): TYPE = ( ("test", "test"), ) ... type = models.CharField(max_length=13, choices=TYPE, default="") views.py: def post_type(request, type): posts = Post.objects.filter(type=type) return render(request, 'blog/post_type.html', {'posts': posts}) .html: {% block some_block %} {{ posts.type}} # DOES NOT WORK - (Getting QuerySet[] only, but cannot call to {{posts.type}} or, let's say, {{ post.type[0] }} to just get that type. {% for post in posts %} {{ post.type }} # This works fine in Loop, cos Im inside set... (I can call even to post.title if defined in Model) {% endfor %} {% endblock %} :( -
Huey using 100% CPU
I recently implemented the python Huey package to handle some long asynchronous http requests on our Django server. These Huey tasks make multiple requests to an external api using python's request library and store the resulting json in redis. Everything works great except that after running for several days Huey starts using larger and larger amounts of the CPU until I am forced to reboot the instance. Here is my Huey config: pool = ConnectionPool(host="bot-redis.srzclv.0001.use1.cache.amazonaws.com", port=6379, max_connections=100, db=0) HUEY = { 'name': 'bot-huey', 'result_store': False, 'always_eager': False, 'connection': {'connection_pool': pool}, 'consumer': { 'workers': 10, 'worker_type': 'thread', }, } The huey tasks are like this: @periodic_task(crontab(minute='*/10')) def pull_from api(): result = requests.get(url) deserialized = json.loads(result.text) cache.set(CACHE_TAG, deserialized, 30 * 60) About 30 huey tasks are executed ever 10 minutes. My first thoughts is that there is something wrong with my config (number of workers, or number of connections to my connection pool. This program runs on an aws t2.small instance. Which has 1 vCPU and 2GIB of virtual memory. -
How to use myapp in dockerfiles/django-uwsgi-nginx?
I'm trying to use dockerfiles/django-uwsgi-nginx. https://github.com/dockerfiles/django-uwsgi-nginx 1.I replace app folder by my app folder. 2.Comment out this line form Dockerfile #RUN django-admin.py startproject mailzon /home/docker/code/app/ 3.docker build -t my_app_name . 4.docker run -d -p 80:80 my_app_name Then I opened http://127.0.0.1/ I got error message. [ Internal Server Error ] last line of the manual. uWSGI chdirs to /app so in uwsgi.ini you will need to make sure the python path to the wsgi.py file is relative to that. I think I need this setting. but I'm not sure about uWSGI and this setting. What should I do next...? Please tell me how to resoleve this problem. -
Django settings.AUTH_USER_MODEL error: No installed app with label 'myapp'
I have the following set: Folder structure: --- backend ----- api -------- models ----------- user.py user.py lies within models folder in settings.py: AUTH_USER_MODEL = 'myapp.User' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'api', ] The model: class User: class Meta: app_label = "myapp" And when I run any manage.py command, for example python manage.py showmigrations I get this error: LookupError: No installed app with label 'myapp'. The problem solution would be rename api folder to myapp, which I cannot do due to some restrictions on model names Data table names starting with 'myapp_' should remain the same What is the proper way to say what is my AUTH_USER_MODEL? -
Django - validate unique for a calculated field in the Model and also in the ModelForm
TL;DR both my model and my form calculate the value of the field number_as_char. Can I avoid the double work, but still check uniqueness when using the model without the form? I use Python 3 and Django 1.11 My model looks as follows: class Account(models.Model): parent_account = models.ForeignKey( to='self', on_delete=models.PROTECT, null=True, blank=True) number_suffix = models.PositiveIntegerField() number_as_char = models.CharField( max_length=100, blank=True, default='', unique=True) @classmethod def get_number_as_char(cls, parent_account, number_suffix): # iterate over all parents suffix_list = [str(number_suffix), ] parent = parent_account while parent is not None: suffix_list.insert(0, str(parent.number_suffix)) parent = parent.parent_account return '-'.join(suffix_list) def save(self, *args, **kwargs): self.number_as_char = self.get_number_as_char( self.parent_account, self.number_suffix) super().save(*args, **kwargs) The field number_as_char is not supposed to be set by the user because it is calculated based on the selected parent_account: it is obtained by chaining the values of the field number_suffix of all the parent accounts and the current instance. Here is an example with three accounts: ac1 = Account() ac1.parent_account = None ac1.number_suffix = 2 ac1.save() # ac1.number_as_char is '2' ac2 = Account() ac2.parent_account = ac1 ac2.number_suffix = 5 ac2.save() # ac2.number_as_char is '2-5' ac3 = Account() ac3.parent_account = ac2 ac3.number_suffix = 1 ac3.save() # ac3.number_as_char is '2-5-1' It is NOT an option to drop the … -
Django database file storage
I have a Django project in which files are stored in DataBase by django-db-file-storage. Contents of this files are encoded by base64. Documentation for django-db-file-storage is clear about how to download stored files using views. But I would like to download files from command line. How do I do that in handle method in Command class? -
Serialization through the Django Rest Framework - how to deserialize?
I have an array of the objects and then try to serialize it using the following statement: serializer = MovieWithDescriptionSerializer(movies, many=True) data = serializer.data The class and the serializer are as below: class MovieWithDescription(object): id = 0 name = '' description = '' rating = '' year = 0 def __init__(self, uid, name, description): self.id = uid self.name = name self.description = description class MovieWithDescriptionSerializer(serializers.Serializer): class Meta: model = MovieWithDescription fields = ('id', 'name', 'description') id = serializers.IntegerField() name = serializers.StringRelatedField() description = serializers.StringRelatedField() The data is saved to session: request.session['movies'] = data And read on the other page: movies = request.session['movies'] However when I tried to deserialize it I learned that the movies variable contains list. So it looks like I don't need to deserialize and just need to iterate through the list to process the data. What I'm doing wrong with this serialization? Is there any more simple way to serialize data than to use Django Rest Framework? -
Django: the information is not processed for a given condition if
Template tag {% if %} {% endif %} does't work correctly. I need to make the search results on the page appear only after the search query. But for some reason, when the page loads, all existing content appears at once. But after get request filter works correctly. views.py def search(request): place_list = Places.objects.all() place_filter = PlaceFilter(request.GET, queryset=place_list) return render(request, 'search/user_list.html', {'filter': place_filter}) html {% if filter.qs %} <div class="row"> {% for obj in filter.qs %} <div class="col-md-3 admin__block"> <div class="cover__wrapper"> <img src="{{ obj.main_photo.url }}" alt=""> <a href="#"><span>#</span>{{ obj.name }}</a> <p>{{ obj.description }}</p> </div> </div> {% endfor %} </div> {% endif %} filters.py class PlaceFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput(attrs={ 'placeholder': 'Search place', 'class': 'input__search'})) class Meta: model = Places fields = ['name'] -
When i open terminal, it always print these error code
When i open terminal, it always print these code. How can i delete these? It is python3 [https://i.stack.imgur.com/WCJgM.png][1] -bash: expert: command not found -bash: souce/usr/local/bin/virtualenvwrapper.sh: No such file or directory sorry I am Japanese ,not good at english. but I love to learn english and programming. so...please tell me what to do. -
Django unit test with pyodbc and SQL Server
I'm trying to create a unit test with Django 2.0 on a database object, but this is somehow failing. I can see the database gets created (not only by the logging statement in the console, but also in Microsoft SQL Server Management Studio, both in the log and within the databases from the Object Explorer when breaking the code on creating an object in the database. It seems to me that the tables do not get created. So, the settings I`m using are: DATABASES = { 'default': { 'NAME': 'BDP.Zoe', 'ENGINE': 'sql_server.pyodbc', 'HOST': '(LocalDB)\MSSQLLocalDB', 'USER': '', 'PASSWORD': '', 'PORT': '', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', 'MARS_Connection': 'True', } } } The relevant part of the test I'm trying to execute is: client = Clients.objects.create(firstName="John", lastName="Doe", clientId=1, policyLabel="policy1") Clients is a model within an app called api. When I try to run this test, I'm getting the following exception: Traceback (most recent call last): File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\sql_server\pyodbc\base.py", line 520, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'api_clients'. (208) (SQLExecDirectW); [42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)") … -
DJANGO development server using TestCase database
GOAL: Run the DJANGO development server, using the TestCase database. Case: DJANGO produces this database when running a TestCase. Now I'm filling the database using DJANGO-autofixture. It would be really nice to start the DJANGO testserver using this database, so I can checkout how the website presents it. Unfortunately, I can't find anywhere how to do this. Writing the test database to sqlite would make sense, but I don't see an options for this. Any hints are appreciated! Thanks! -
Working with django-pagedown
I am following the instructions on the official Django-pagedown repo pip install django-pagedown - installed without errors Add pagedown to your INSTALLED_APPS - error thrown is "ModuleNotFoundError: No module named 'pagedown' 3.Collectstatic run smoothly. When I check the modules currently in my virtual env using help('modules'), pagedown was not present, but in my global installation of python, it was present, so my question is, why can't my project work/use the present installed django-pagedown installation? what am I missing here? python - 3.6.4 django version - (2, 0, 4, 'final', 0) pip version - 10.0.1 os - windows -
Overrriding Django REST Frameworks update method to save the nested serializers
I am new to DRF and I have been stuck with how to override update method in the serializers.py file. Here are my models. class Quiz(models.Model): quiz_name = models.CharField(max_length=200) module_referred = models.ForeignKey(Course_Module, related_name="quiz") class Course_Module(models.Model): name = models.CharField(max_length=200) The serializers that have been created for these models are as below:- class QuizSerializer(serializers.HyperlinkedModelSerializer): questions = Quiz_QuestionSerializer(many=True) class Meta: model = Quiz fields = ('url', 'quiz_name', 'module_referred') class Course_ModuleSerializer(serializers.HyperlinkedModelSerializer): quiz = QuizSerializer(many=True, required=False) class Meta: model = Course_Module fields = ('url', 'name', 'quiz') def create(self, validated_data): quiz_data = validated_data.pop('quiz') module = Course_Module.objects.create(**validated_data) for qd in quiz_data: Quiz.objects.create(module_referred = module, **qd) return module def update(self, instance, validated_data): # Somehow save instance with new quiz_data return instance A typical JSON representation for the above schema is like this:- { "url": "http://localhost:8080/api/registration_courses_modules/51/", "name": "cdcsdc", "quiz": [{ "url": "http://localhost:8080/api/registration_quiz/1/", "quiz_name": "Shash", "module_referred": "http://localhost:8080/api/registration_courses_modules/19/" }] } Any help is much appreciated. Thank you. -
django build_absolute_uri without query params
request.build_absolute_uri() returns me url/path/?q1=v1&q2=v2... BUT, I need the same absolute uri without query params q1=v1&q2=v2 -
Django ORM object id
I suppose that the object IDs are auto created. Although, I encounter an Attribute error saying "'list' object has no attribute 'id'" Below is my code module: client = Client.objects.bulk_create([Client(name='WaltDisnep', created_at=timezone.now(), updated_at=timezone.now()), Client(name='Google', created_at=timezone.now(), updated_at=timezone.now()), Client(name='JetAirways', created_at=timezone.now(), updated_at=timezone.now())]) building = Building.objects.create(description='TestBuilding', is_active=1, client_id=client.id, country_code='NL') -
Images from media folder is not displaying django template
I am having images in my media folder and I want to display them but Django is not displaying images other than static folder. In my setting STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),] MEDIA_ROOT = BASE_DIR MEDIA_URL = '/media/' In my urls.py after url pattern I added this + static(MEDIA_URL, document_root=MEDIA_ROOT) In my templates <img class="card-img-top" style="" src="{{result.object.thumbnail.url}}" alt=""></a> <p>{{result.object.thumbnail.url}}</p> It is showing the correct path but not showing the image, I am unable to figure out the problem. Thanks -
nothing happens when submitting django form
I have a problem with django forms, when submitting a form nothing seems to happen, even the server didn't get any response except GET request to view the form template. here is my code for the forms.py : from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = [ "title", "content", "category" ] and here is my post_form.html : {% extends 'base.html' %} {% block content %} <h1>form</h1> <form method="POST" action="."> {% csrf_token %} {{ form.as_p }} </form> <button type="submit">Create Post</button> {% endblock content %} and here is my handling for the form in views.py : def post_create(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect("posts:detail", pk=post.pk) else : form = PostForm() context = { "form":form, } return render(request,"post_form.html", context) -
django: Taking user input from form and performing operation based on input
New to Django. I am trying to take user input from a form and perform an operation based on the content of the form. Specifically, comparing the user input (string) with a list. I have working code to replicate this in a python file, but I am confused how to implement this into django. Note 'userinput' is not actually input from the user. See below: import nltk from nltk.tokenize import word_tokenize userinput = "hello, how are you?" sCV = userinput.replace(",",'') cv = nltk.word_tokenize(sCV) blist = ['hello', 'hi', 'hey'] def words(): #How many words from input are in the list b_words = set(word for word in cv if word in blist) print ("Number of similar words: ", len(b_words)) #What words are missing mwords = set(word for word in blist if word not in cv) print("Missing words from list are: " , mwords) words() I don't want to store the the data from the user, so I do not want to retrieve it from a table. I have a form to take user input: <div class = "container"> <form action="#" method ="post"> <div> <label for="cv">Enter details: </label> <textarea name="cv" id='cv' rows="10" cols="30" maxlength="20000"></textarea> </div> <div> <button>Submit</button> </div> </form> </div> In summary: I …