Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 + py.test: Fix ConnectionDoesNotExist when test functions need access to unmanaged external tables/DB
We use py.test to test our Django system. We use unmanaged DBs in our system: class Example(models.Model): class Meta: managed = False When we run tests that need access to the existing DBs with existing data, they fail with ConnectionDoesNotExist: The connection my_connection_name doesn't exist This is how our tests look like: @pytest.mark.django_db def test_example_access(): from example.models import Example Example.objects.count() We've tried to add the following to conftest.py as described in the top answer on Django test tables are not being created, but it did not change the matter (despite being executed). @pytest.fixture(autouse=True, scope='session') def __make_unmanaged_managed(): from django.apps import apps unmanaged_models = [m for m in apps.get_models() if not m._meta.managed] for m in unmanaged_models: m._meta.managed = True Thanks a lot for your ideas! -
How to change location of templates?
I'm trying to organize my files, which includes changing the location of some template files. However, I can't seem to get the server to pick up these changes. Restarting the server doesn't do it, nor does makemigrations pick up the change. I'm going from: class Meta: template='base/panel.html' to: class Meta: template='blocks/panel.html' But keep getting a TemplateDoesNotExist error. Exception Type: TemplateDoesNotExist Exception Value: base/panel.html -
Edit form not displaying the previous content Django
I am trying to let the users edit their answer, but the problem I am facing is that the pre added answer is not showing in the form. Can anyone please point out where I did mistake and how it can be fixed? Thank You. views.py # update answer def update_answer(request, slug): # test user login here if request.user.is_authenticated(): quest = Question.objects.get(slug=slug) answer = Answer.objects.get(user=request.user, question_id=quest.id) new = (answer.answer) if request.user == answer.user: if request.method == 'POST': form = AnswerForm(request.POST or None, instance=answer) print(new) if form.is_valid(): form.save() return redirect("main:home") else: form = AnswerForm(request.POST or None, instance=answer) return render(request, 'main/edit-answer.html', {'form': form}) else: return redirect("main:home") else: return redirect("main:home" ) forms.py class AnswerForm(forms.ModelForm): class Meta: model = Answer fields = ('answer',) edit-answer.html {% extends 'main/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <form action="" method="post"> {% csrf_token %} {{ form|crispy}} <input type="submit" class="btn btn-md btn-warning" value="Save"> </form> </div> {% endblock %} So the previously added answer by that user is not displaying in the form, all there is blank. -
I need a time selector which gives the time in the format hh:mm:ss only not along with the date
from django.db import models class Shop(models.Model): openingTime = models.TimeField() closingTime = models.TimeField() I used a timepicker of moment.js but it gives time alog with the date. which my data base is not accepting. I am using Django in my backend... sending data through Rest api -
Followers do not get added [on hold]
I am trying to add followers to my blogger model but unable to do so. This is the error I am getting. Thanks. views.py def follow(request,user_id): user =User.objects.get(username=request.user) userFolllow = get_object_or_404(Blogger, id=user_id) if request.method == 'POST': userFollow.follows.add(user) return redirect('winterblog:blogger_detail',user_id) models.py class Blogger(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField(User,related_name='following') def get_absolute_url(self): return reverse('blogger-detail',args=[str(self.id)]) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Blogger.objects.create(user=instance) template {% extends "winterblog/base_generic.html"%} {%block content%} <h1>{{user.username}}</h1> <h2>Blog Posts</h2> <form action="{% url 'winterblog:follow' user.id %}" method="POST"> {%csrf_token%} <input type="submit" value="follow"/> </form> I am expecting a follow request. This is a part of the template I am rendering. -
How to display opencv feed on webpage in django?
I am making a webapp in python using django. I want to use my webcam using opencv and display its feed in my web page. The problem is imshow() displays image in a desktop window and i don't want this. I want it to display feed in my webpage somehow. -
Accessing variables in view - Django template
I am totally new to python and django. I want to know how to access the dictionary variables in template. I tried few ways but nothing worked out. if i print the variable i receive from my view function this is what i get {'BSE:INFY': {'instrument_token': 128053508, 'last_price': 1150.3}, 'NSE:INFY': {'instrument_token': 408065, 'last_price': 1150}} I want to loop through the ltp and print something like this BSE:INFY - 1150.3 NSE:INFY - 1150 -
setting up gunicorn and django: No module named revamp.wsgi
Setting up django on a VM following this article and this is how I've setup gunicorn systemd [Unit] Description=gunicorn daemon After=network.target [Service] User=muiruri_samuel Group=www-data WorkingDirectory=/home/muiruri_samuel/webapp ExecStart=/home/muiruri_samuel/webapp/djangoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/muiruri_samuel/webapp/revamp/revamp.sock revamp.wsgi:application [Install] WantedBy=multi-user.target when I check the status there's an issue with how i created this (djangoenv) muiruri_samuel@pluscolor:~/webapp/revamp/revamp$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2018-01-22 10:52:33 UTC; 29min ago Main PID: 23354 (code=exited, status=3) Jan 22 10:52:33 pluscolor gunicorn[23354]: return util.import_app(self.app_uri) Jan 22 10:52:33 pluscolor gunicorn[23354]: File "/home/muiruri_samuel/webapp/djangoenv/local/ Jan 22 10:52:33 pluscolor gunicorn[23354]: __import__(module) Jan 22 10:52:33 pluscolor gunicorn[23354]: ImportError: No module named revamp.wsgi Jan 22 10:52:33 pluscolor gunicorn[23354]: [2018-01-22 10:52:33 +0000] [23379] [INFO] Worker ex Jan 22 10:52:33 pluscolor gunicorn[23354]: [2018-01-22 10:52:33 +0000] [23354] [INFO] Shutting Jan 22 10:52:33 pluscolor gunicorn[23354]: [2018-01-22 10:52:33 +0000] [23354] [INFO] Reason: W Jan 22 10:52:33 pluscolor systemd[1]: gunicorn.service: Main process exited, code=exited, statu Jan 22 10:52:33 pluscolor systemd[1]: gunicorn.service: Unit entered failed state. Jan 22 10:52:33 pluscolor systemd[1]: gunicorn.service: Failed with result 'exit-code'. that is the wsgi file. The wsgi file I do know exist here /home/muiruri_samuel/webapp/revamp/revamp\wsgi.py -
Is the concept behind Angular Components and Django Apps is similar?
I have learnt how to work with Angular, and I have a very good understanding of component and its development. Now I'm learning Django for backend. It's just a couple of weeks that I've started with Django. Now this time apps in Django looks very similar to components in Angular. Like unique responsibility for each component in Angular and same for apps in Django, then in angular we use different techniques and tools for component interaction. And there must be something in Django as well (this time I don't know). So, I just want to know that is the concept of both apps and components are similar or it's just my lack of knowledge in Django. -
TypeError: Invalid Keyword Argument 'user'
Im creating a signup view with a profile model. but got stuck with a small TypeError. Can someone tell me where am I going wrong.. models.py class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=10) full_name = models.CharField(max_length=200) is_doctor = models.BooleanField(default=True) @receiver(post_save, sender=User) def update_user_docto(sender, instance, created, **kwargs): if created: Doctor.objects.create(user=instance) instance.doctor.save() forms.py class DocSignUpForm(UserCreationForm): full_name = forms.CharField(help_text='Required') mobile = forms.CharField() class Meta: model = User fields = ('username', 'full_name', 'mobile', 'password1', 'password2',) views.py def docsignup(request): if request.method == 'POST': form = DocSignUpForm(request.POST) if form.is_valid(): user = form.save() #error in this line user.refresh_from_db() user.doctor.full_name = form.cleaned_data.get('full_name') user.doctor.mobile = form.cleaned_data.get('mobile') user.save() #username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('base') else: form = DocSignUpForm() return render(request, 'signup.html', {'form': form}) -
Django error when trying to display the sign up form
So I have this form which extends the User and I just want to allow the student to create and account and be able to select the courses from the course list.But when I try, I get the error: __init__() takes 1 positional argument but 2 were given I can't find any solution to this yet. I need some advice. These are my files: {% block body %} <div class="row"> <div class="col-md-8 col-sm-10 col-12"> <h2>Sign up as a {{ user_type }}</h2> <form method="post" novalidate> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form }} <button type="submit" class="btn btn-success">Sign up</button> </form> </div> </div> {% endblock %} class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) path('signup/', views.StudentSignUpView, name='signup') class StudentSignUpForm(UserCreationForm): attended_courses = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple, required=True ) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.save() student = Student.objects.create(user=user) student.attended_courses.add(*self.cleaned_data.get('attended_courses')) return user class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index') -
Django REST: CRUD on Through Table, Many-to-Many relationship
I have workers and tasks that they can complete. I would like for workers to be able to apply for tasks, and retrieve the following .json for each task. GET http://127.0.0.1:8000/api/tasks/ returns: "results": [ { "url": "http://127.0.0.1:8000/api/tasks/1/", "workers": [], "user": "Username", "created": "2018-01-21T19:56:35.398320Z", "title": "Help me with Django Rest", "description": "Here is my problem", }, Currently, the workers field is empty, and I would like to write a view so that workers can apply for this specific task using a POST request to: http://127.0.0.1:8000/api/tasks/1/apply This Many-to-Many relationship looks as follows: models.py class Worker(models.Model): user = models.OneToOneField(User) class Task(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=False) description = models.TextField(max_length=500, blank=False) user = models.ForeignKey('auth.User', related_name='tasks', on_delete=models.CASCADE) workers = models.ManyToManyField(Worker, through='Task_worker') def save(self, *args, **kwargs): super(Task, self).save(*args, **kwargs) class Task_worker(models.Model): worker = models.ForeignKey(Worker) task = models.ForeignKey(Task) created = models.DateTimeField(auto_now_add=True, blank=True) serializers.py class TaskWorkerSerializer(serializers.HyperlinkedModelSerializer): task = serializers.ReadOnlyField(source='task.id') worker = serializers.ReadOnlyField(source='worker.id') class Meta: model = Task_worker fields = ('task', 'worker', 'created', ) class TaskSerializer(serializers.HyperlinkedModelSerializer): workers = TaskWorkerSerializer(source='task_worker_set', many=True, read_only=True) user = serializers.ReadOnlyField(source='user.username') class Meta: model = Task fields = '__all__' class WorkerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Worker fields = '__all__' My urls.py contains task_list = views.TaskWorkerViewSet.as_view({ 'get': 'list', 'post': 'create' }) urlpatterns += [url(r'^tasks/(?P<task_id>[0-9]+)/apply$', task_list),] … -
Django cant see my toolbar
Hello I have a common problem in Django like Django can't see .. OK this time Django can't see my beautiful toolbar Terminal doesnt show any error. This is my cms_toolbar.py placed in my "aktualnosci" folder from django.utils.translation import ugettext_lazy as _ from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar from cms.utils.urlutils import admin_reverse from .models import * @toolbar_pool.register class PollToolbar(CMSToolbar): supported_apps = ( 'aktualnosci', ) watch_models = [Aktualnosci] def populate(self): if not self.is_current_app: return menu = self.toolbar.get_or_create_menu('poll-app', _('Aktualnosci')) menu.add_sideframe_item( name=_('Lista aktualnosci'), url=admin_reverse('aktualnosci_aktualnosci_changelist'), ) menu.add_modal_item( name=_('Dodaj aktualnosc'), url=admin_reverse('aktualnosci_aktualnosci_add'), ) Of course Django can't see it and ignore it. My question is - how to force Djnago to see it Screaming doesnt help! -
Django save_model file not yet uploaded
def save_model(self, request, obj, form, change): in this handler I can get the name of the uploaded file, but the file itself is not uploaded yet, so I can't make any operations on it, can be there a way to force django to upload that file in this save_model handler? in order to do some operations on it -
Django signals working yet one is giving unexpected results
I dislike having people go through the trouble of reviewing my code but even after trying for hours, I have no idea what the problem is. I didn't have a clear way of describing my question's title but I tried. I am building a College Management System. I have two apps at the moment. One is for accounts and the other is called klass. I have extended the default user and have added a boolean field of 'in_class' which I will be using as a check to do stuff later. Below is an overview of my accounts.models.py: accounts.models.py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) in_class= models.BooleanField(default=False) bio = models.TextField(blank=True, help_text='write something about yourself...') # goes on... I am not utilizing the permissions, i am using a role-based approach. The only difference is i've added the boolean fields to my user model instead of creating another model for the roles. Below is an overview of my klass.models.py: klass.models.py from django.db import models from accounts.models import User from django.db.models.signals import post_save, … -
Window not closing in django after save
I have two many to many fields when I click on one many to many feild and the save the window closes but there is one more m2m field inside 1st one when i clicked that and save the data my new window does not close -
Django view to call api
So i'm using django view to call api post method but its giving me 400 error As i encounter csrf forbidden error b4, im using the @csrf_exempt for now. I tried doing post method on both the API itself and also using the view to call the api. However when using the view to call, i got 400 error when both are using the same post value to post. Posting using api: QueryDict: {'book': ['Second '], 'author': ['Ban'], 'date': ['2018-01-10 08:00AM']} [22/Jan/2018 18:56:09] "POST /api/test/ HTTP/1.1" 200 61 Posting using view: QueryDict: {} [22/Jan/2018 18:56:12] "POST /api/test/?book=Second+&author=Ban&date=2018-01-10+08%3A00AM HTTP/1.1" 400 36 [22/Jan/2018 18:56:12] "POST /test/ HTTP/1.1" 200 19 Here is my code models.py class TestPost(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) date = models.DateTimeField(blank=True, null=True) serializer.py class TestPostSerializer(serializers.ModelSerializer): date = serializers.DateTimeField(format="%Y-%m-%d %I:%M %p") class Meta: model = TestPost fields = ('id', 'book', 'author', 'date') views.py from django.http import HttpResponse import requests def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', params=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', params=request.GET) if r.status_code == 200: return HttpResponse('Yay, it worked') return HttpResponse('Could not save data') class TestPostViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = TestPost.objects.all() serializer_class = TestPostSerializer -
Chatfuel bot - user validation
I have been reading a LOT seriuosly a lot of how can I implement this flow to my bot, for example: The user types his/her username I get the data written by the user I search in my Django Rest API if the user actually exists and then return to he/she the tasks he/she need to complete for the end of the week. I know that I have to use JSON plugin, and User Input, but what I don't know how to do, is obtain what the user type. Until now I got this URL setup in my JSON plugin: https://helloworld.herokuapp.com/post?username={{username}} so this mean that I have a running server. But then what? I read this: API integration and also this setup server side logic But step 3 is what I don't know how to develop, I achieve this: class GetView(TemplateView): template_name = 'profiles/get.html' def geturl(self, request): # url = 'https://helloworld.herokuapp.com/post?username={{username}}' # parsed = urlparse.urlparse(url) # return HttpResponse(urlparse.parse_qs(parsed.query)['username']) username = self.request.query_params print(username) url = 'https://helloworld.herokuapp.com/post/' + 'username' + username But I think i'm not even close to find the solution. -
Django rest Swagger 2.0 how to display DictFiled in swagger UI?
I'am trying to display below serializer dict field but its not showing in swagger UI Please take a look. class TargetSerializers(serializers.ModelSerializer): name = serializers.CharField(required=True) target_type = serializers.PrimaryKeyRelatedField(queryset=ScanType.objects.all()) configuration_details = serializers.DictField() class Meta: model = Target fields = ('id', 'name', 'target_type', 'lock_threshold', 'user_id', 'configuration_details') -
CBV or Functional View for JsonResponse
I am new to creating API endpoints using Django. Which is a better way to handle API requests and process JsonResponse? Should I do it in a Class-Based View? Or a Functional View? I would assumed CBV would be an overkill since people tend to use CBV for the generic-view inheritance. Since I am merely sending back a Json object, i would consider it unnecessary and thus a Functional view would suffice. However, I am not too sure what exactly are the other components of CBV and FV that would matter and make the difference. If there is one view better over another view, can you please tell me with reasons why one is preferred over another. Cheers. -
How can I change email sender's name in django
I'm creating email system in my django project and faced to next question: Send email from custom email sender name, f.e. sending email from gmail(btw it works in my project) requires sending messages only from gmail account, same thing with smtp-pulse, sendgrid and etc. . My question is: May I use any of already configured smtp servers in my case, or I only need to create my own using smtplib(f.e) and configure it? Tried: DEFAULT_FROM_EMAIL = 'support@site.com' SERVER_EMAIL = 'support@site.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 2525 EMAIL_USE_TLS = False EMAIL_HOST_USER = 'user@gmail.com' EMAIL_HOST_PASSWORD = 'password' This one doesn't work. Same with mail.ru/smtp-pulse.com -
Django convert raw SQL ordering to QuerySet API
I'm trying to perform natural ordering on CharField for model (here simplified version): class House(models.Model): number = models.CharField(max_length=32) def __str__(self): return str(self.number) >>> House.objects.all() <QuerySet [<House: 2>, <House: 1>, <House: 4>, <House: 3>, <House: 1b>, <House: 2b>, <House: 1c>, <House: 13c>, <House: 10>, <House: 2e>, <House: 3ab>]> I have managed to order it by raw SQL query: House.objects.raw("SELECT * FROM entry_house ORDER BY(substring(number, '^[0-9]+'))::int, substring(number, '[0-9].*$')") But I need to get QuerySet object not RawQuerySet (for our current pagination implementation). Iterating over all raw queryset is not an option because of huge amount of data. How can I convert result of RawQuerySet to QuerySet or even better, how to convert this raw SQL query to Django QuerySet API? -
Pass attributes from a Cutom Field to a Custom Widget template
I want to create a custom Field and a custom Widget. I'm trying to do this using ModelForms. How can I pass arguments from the Field to the Widget but not as widget attributes, similar to how {{ widget.name }} is passed. field_name = CustomField(obj_original=ALPHA, obj_type=100) I want to use this values in the widget template as conditional and/or as values for template tags(do some manipulation), so this is why I don't want them in attributes(the attribute will appear in the html elements), this don't. I know I can pass multiple attributes in widget, but I need then to remove them from attributes and attached as direct properties/attributes of the widget. I want to be passed in the Field, not in Widget. I check in django source ChoiceField and SelectField but it is not very clear for me. -
updated file name in django
This is an admin form handler, for example I upload a test.txt file in the django admin panel: def save_model(self, request, obj, form, change): if 'torrent_file' in form.changed_data: print("file has changed: ") print(obj.file) else: print("file has not changed") super(FileAdmin, self).save_model(request, obj, form, change) here I get the original file name from the upload form, but by fact the file is saved with another name if there is already a file with this name, but in the above code i get only the original name in all cases, how to can I get the changed/updated file name that was saved?.. -
Django boolean choice field
How can I make a django form of Yes and No. for example I want my django website to have a question like: "Do you use Django?" -Yes -No the - sign is the radio buttons. How can i do this in django