Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django automatic database upload
I'm developing application with react-native and Django REST api. what I want to do is to build a database using open api. I made codeline for I have implemented getting json format data through open api. But I have no idea what to do next. How can I put the data I have received into the relation table defined by Django model? -
Django race condition inside a transaction
I have Django 1.11 app with PostgreSQL. Take a look at code below. Is it possible to have race condition there? I am afraid I could get race condition on diff=-account.hours. Does transaction.atomic save from race condition? from django.db import transaction def write_off(account_ids): account = Account.objects.filter(id__in=account_ids) with transaction.atomic(): MyLog.objects.create( hours=0, operation_type=LOG_OPERATION_WRITE_OFF, diff=-account.hours, ) Account.objects.filter(pk=account.pk).update(hours=0) -
django group model extension duplicated key entry
I created a (second!) model that subclasses auth_models.Group: class SecondModel(auth_models.Group): display_name = models.CharField(max_length=48) class Meta: db_table = 'second_model' verbose_name = 'SecondModel' As mentioned above, there is already a first model the subclasses auth_models.Group in the same way (second -> first). Both models exist, FirstModel has entries and SecondModel as well. I now would like to add the subclassing to SecondModel. The generated migration part looks like this: migrations.AddField( model_name='second_model', name='group_ptr', field=models.OneToOneField(auto_created=True, default=1, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.Group'), preserve_default=False, ) Problem: when executing the migration script I get the following error: psycopg2.IntegrityError: could not create unique index "second_model_pkey" DETAIL: Key (groupl_ptr_id)=(1) is duplicated. .. django.db.utils.IntegrityError: could not create unique index "second_model_pkey" DETAIL: Key (group_ptr_id)=(1) is duplicated. I tried change the name put this does not solve anything. -
Post a form value to Django rest framework to retrieve json
How do i post a HTML form value from a django view to django-restframework view? I am constructing a Django application. It has an app called 'API' from this app i configured the urls.py as url(r'^programdetail/(?P<pk>[0-9]+)/$', ProgramDetail.as_view(), name='programdetail') when i visit http://127.0.0.1:8000/programdetail/1/ The program detail whose primarykey is 1 is displayed. I used the following code class ProgramDetail(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'test.html' def get(self, request, pk): pg = get_object_or_404(Program, pk=pk) serializer = ProgSerializer(pg) return Response({'serializer': serializer, 'data': pg.name}) Now i have a html form and a view to render it. The codes are <body> <h1>Programs</h1> {% csrf_token %} <form action ="" method="GET" novalidate> <select name="pk"> {% for program in programs %} <option value="{{ program.program_id }}">{{ program.name }}</option> {% endfor %} </select> <button type="submit">View</button> </form> </body> and the view i used is def programsform(request): progs = Program.objects.all() return render(request, 'allprograms.html', {'programs':progs}) This view gives me a HTML form that shows a drop down list of program names. Now the question is about action attribute. To which URL do i POST or GET these values to construct a the URL like http://127.0.0.1:8000/programdetail/{the posted program_id} and display them in my template. I tried posting these values to the same ProgramDetail class … -
How to show local time in template
I'm using PostgreSQL to store an object with a DateTimeField. The DateTimeField is using auto_now_add options. And it is created automatically from serializer in Django Rest Framework. As described in Django docs, I tried to get local timezone and activate it. from django.utils.timezone import localtime, get_current_timezone tz = get_current_timezone() timezone.activate(tz) session.started_at = localtime(session.started_at) In template index.html, I also try to load timezone. {% localtime on %} Session: start time {{ item.session.started_at }} {% endlocaltime %} In settings.py USE_TZ = True TIME_ZONE = 'UTC' I'm using GMT+7 timezone but it still shows UTC time on template. I'm using Django development server to test. Am I missing something? -
python django - how to structure questionnaire that multiple users answer
I am building my first Django app. The idea is to create a single questionnaire that 10 people have to answer every quarter (e.g. how much profit have you made this quarter). I wanted to check whether the model is correct, or if there's a better way to do it. I have model classes for Members (the people answering the questions), the Questionnaire (to which I will add all of the questions), the Submission (which will be the instance of the Questionnaire being submitted), and then Question and Answer classes. class Member(models.Model): company_name = models.CharField(max_length=50) website = models.URLField() company_type = models.CharField(max_length=1, choices=( ("S", "Small"), ("L", "Large") ) ) representative = models.CharField(max_length=50) representative_email = models.EmailField() representative_phone = models.CharField(max_length=12) address_l1 = models.CharField(max_length=50) address_l2 = models.CharField(max_length=50) town = models.CharField(max_length=50) postcode = models.CharField(max_length=8) def __str__(self): return self.company_name class Questionnaire(models.Model): modified_date = models.DateTimeField(auto_now=True) published_date = models.DateTimeField(auto_now_add=False) class Submission(models.Model): questionnaire = models.ForeignKey(Questionnaire) member = models.ForeignKey(Member) submitted = models.BooleanField(default=False) submission_date = models.DateTimeField(auto_now_add=False) class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) question_group = models.CharField(max_length=100) question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey(Question) member = models.ForeignKey(Member) answer = models.IntegerField() reason_for_diff = models.CharField(max_length=200) I will have only 3 pages in the end - one will be the Index … -
Testing Django view: how can we know if catched exception was actually raised?
I want to test if exceptions in my views are raised when expected. The "issue" I am facing with is that I am using try and except statements in my view, so I actually catch those exceptions (in order to do some stuff when they are raised). My question is the following: how can I test if one expected exception was raised, if it was catched in my except statement? For instance: myviews.py class SomeView(LoginRequiredMixin, CreateView): model = models.MyModel template_name = "my_template.html" form_class = forms.MyForm def form_valid(self, form): try: # normal stuff here except Exception1 as e: # some other stuff here print("Exception1 occured: ", e) messages.error(self.request, "Message1" except Exception2 as e: # some other stuff here print("Exception2 occured: ", e) messages.error(self.request, "Message2") except Exception as e: # some other stuff here print("Something unexpected occured! ", e) messages.error(self.request, "Message_unexpected") mytests.py def test_SomeView(self): # test: everything must works just fine form_data = some_valid_data response = self.client.post("some_url", form_data) self.assertEqual(response.status_code, 200) # test: Exception1 should be raised in SomeView form_data = some_NOT_valid_data # on purpose # below, I want to know that Exception1 was raised (then catched) # I know what I wrote does not work as expected, but I do not know … -
find a field via forign key
This is my table in model: class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number')) suffix=models.CharField(blank=True,null=True,max_length=12,verbose_name=_('uffix')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price')) date=models.DateTimeField(auto_now_add = True,verbose_name=_('date')) seller=models.BooleanField(verbose_name=_('seller'), default='null') the user field is connected to the default django User table via forignkey User table fields are: username password first_name last_name email now I want to find email of the users which the date of their stocks are lass than specific date this is my view def allstocks_view(request): last_month = datetime.today() - timedelta(days=30) q=Stocks.objects.all().filter(date__lte=last_month).??? I dont know how can i find the email Any advice is appreciated. -
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