Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Memcache works on localhost (without anything in settings.py)
My question is "can anybody corroborate or explain?" The following caching logic works as expected on localhost, but fails on heroku (queries every time): from django.core.cache import cache QUEUE_KEY = "queue" def index(request): queue = cache.get(QUEUE_KEY) if not queue: queue = QueueItem.objects.order_by("id") cache.set(QUEUE_KEY, queue) c = {'queue': queue} return render_to_response('index.html', c) -
Django forms - multiple choice field too many values to unpack (expected 2)
im trying to use a query set as the source for a multiple choice field and add a class to it in my forms.py. However I am receive the error too many values to unpack (expected 2) Would anyone know the cause for this? sub_types = SubnetTypes.objects.all() stypes = [] for st in sub_types: stypes.append(st.subnet_type) subnets = forms.MultipleChoiceField( choices=stypes, widget=forms.CheckboxSelectMultiple( attrs = {'class': 'form-control'} ) ) -
Django Url Not Matching
I have three urls: # Better Fund Detail Api url(r'funds$', api_views.Api.as_view()), url(r'funds/(?P<ticker_name>[^/]+)$', api_views.Api.as_view()), url(r'funds/(?P<ticker_name>[^/]+)/(?P<series_name>[.]+)$', api_views.Api.as_view()), When I goto this url: funds/BND/A it should match the third one but it doesn't. Any ideas? -
How to pass variable id from AngularJS to Django for SQL query
I have a table of employees when I click a row it will get the Id of the row and pass it to django sql query. This is my raw sql query in django class GetEmployeeDetailsApi(ListAPIView): queryset = EmployeeTb.objects.raw('SELECT * FROM EmployeTable WHERE EmployeeId = %s', [id]) serializer_class = GetEmployeeDetailsSerializer I already tried another a way to do this by fetching all records then filter it in front-end and it worked, but I do not want to do this because of security reasons, it exposes the whole table when I only need one record. -
django - get a list of joins between two models based on a third model
I have three models that are set up like so: class A(models.Model): name = models.CharField(max_length=200) class B(models.Model): name = models.CharField(max_length=200) a = models.ForeignKey(to=A, null=True, blank=True) class C(models.Model): name = models.CharField(max_length=200) a = models.ForeignKey(to=A, null=True, blank=True) The B-to-A relationship is one-one and the C-to-A relationship is many-one. I have a template where I want to show a list of all B.name, and for each B.name, have a list of C.name where C.a = B.a. What's the simplest way to do that? I know I can just get the list of Bs and the list of Cs, and for each B get B.a and search the list of Cs for the matching C.a, but is there a cleaner way to just get a queryset that combines both? -
user() missing 1 required positional argument: 'request'
I have a problem is that it does not let me use the limit_choice_to what I want is that according to the area that the logged in user belongs to, show me in that field the users that only belong to that area def user(request): if request.user: user = request.user userc = User.objects.get(empresa_area_id=user.empresa_area_id) return userc class Tickets(models.Model): alta = '1' media = '2' baja = '3' prioridades = ( (alta ,'Alta'), (media , 'Media'), (baja ,'Baja'), ) estados = ( (1,'iniciado'), (2,'terminado'), ) ticket_id = models.AutoField(primary_key=True) Usuario_id = models.IntegerField() area_destino_id = models.ForeignKey(Empresa_area,null=True, blank=True, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now_add=True) fecha_estimada = models.DateTimeField() tipo_id = models.ForeignKey(Tipo_ticket, null=True, blank=True, on_delete=models.CASCADE) prioridad = models.CharField(max_length=3, choices=prioridades) asunto = models.CharField(max_length=40) mensaje = models.TextField() estado = models.IntegerField(choices=estados, default=1) fecha_fin = models.DateTimeField(null=True, blank=True) consultor_id = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, limit_choices_to =user ) archivo_id = models.ForeignKey(Archivos, null=True, blank=True, on_delete=models.CASCADE) At the moment of running the program, I am sent a user () missing 1 required positional argument: 'request' I would like to know what the problem is and how I can solve it -
Wagtail authentication error (User has a valid ticket but not a valid session) using django-cas server
Wagtail virtual environment has django-cas client [1] configured to allow users to use a django-cas-server [2] to log in, which has its own venv. When the user clicks to sign in, redirect to the CAS login page is done. Afterwards when user tries to login using a valid account (username/password), the Web Browser shows: "Forbidden Login Failed' In the terminal of wagtail, error is displayed: User has a valid ticket but not a valid session [03/Jan/2018 19:47:39] "GET /admin/login/?next=%2Fadmin%2F&ticket=ST-4w5TiBrICCZ1KdUQUtNtgW6coOMBb6FzZnraIi8MOuzjfbhPTabPrxKkiDmag HTTP/1.1" 403 38 Any help/suggestions to overcome this problem will be appreciated. References: [1] django-cas https://github.com/kstateome/django-cas [2] django-cas-server https://github.com/nitmir/django-cas-server -
Adding a Z prior to my query set
I have a few if statements, which identify a datareducecode. Everything is working correctly except for the last one, which is number 7 in the view below: if request.method == 'POST' and selectedaccesslevel == '3': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '4': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '5': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('rlevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '6': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('dlevel', flat = True) print (datareducecode) if request.method == 'POST' and selectedaccesslevel == '7': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('f"Z{coid}"', flat = True) print (datareducecode) I know it's because the values_list where I have 'f"Z{coid}"' to place a Z prior to the coid. I get the following error message: Cannot resolve keyword 'f"Z{coid}"' into field. Choices are: blevel, coid, dlevel, facilitydimension, rlevel, slevel, user My question is how do I get a Z prior to the results of datareducecode for selectedaccess == 7? datareducecode eventually get's saved to the database as datareducecode = list(datareducecode)[0] -
django.core.exceptions.FieldError: Unknown field(s) specified by user
I'm using Django 2.0 I have extended AbstractBaseUser model to create a custom User model. In my accounts/models.py class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=False): if not email: raise ValueError('User must have an email address') if not password: raise ValueError('User must have a password') user = self.model( email=self.normalize_email(email) ) user.is_staff = is_staff user.is_superuser = is_admin user.is_active = is_active user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): return self.create_user( email, password=password, is_staff=True, is_active=True ) def create_superuser(self, email, password=None): return self.create_user( email, password=password, is_staff=True, is_admin=True, is_active=True ) class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=250, blank=False, unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) groups = models.ManyToManyField(Group, blank=True) last_login = models.DateTimeField(auto_now=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' objects = UserManager() @property def is_staff(self): return self.is_staff @property def is_active(self): return self.is_active @property def is_superuser(self): return self.is_admin def __str__(self): if self.first_name is not None: return self.get_full_name() return self.email def get_full_name(self): if self.last_name is not None: return self.first_name + ' ' + self.last_name return self.get_short_name() def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): … -
Django migration: all the columns are not generated as the model
For all the tables some of columns are generated and some of columns didn't. Here is my models personalInfo.py from django.db import models # Create your models here. class Students(models.Model): student_name = models.CharField(max_length=100) student_id = models.CharField(max_length=50) student_dept = models.CharField(max_length=30) student_sec = models.CharField(max_length=2) class StudentDetails(models.Model): students = models.ForeignKey(Students, on_delete=models.CASCADE) present_address = models.TextField permanent_address = models.TextField student_phone = models.BigIntegerField gpo_box_number = models.IntegerField class Teachers(models.Model): teacher_name = models.CharField(max_length=100) teacher_id = models.CharField(max_length=50) teacher_dept = models.CharField(max_length=30) class TeacherDetails(models.Model): teachers = models.ForeignKey(Teachers, on_delete=models.CASCADE) present_address = models.TextField permanent_address = models.TextField teacher_phone = models.BigIntegerField gpo_box_number = models.IntegerField studentAdvising.py from django.db import models from personalInfo.models import Students, Teachers # Create your models here. class Advising(models.Model): student = models.ForeignKey(Students, on_delete=models.CASCADE) teacher = models.ForeignKey(Teachers, on_delete=models.CASCADE) subject_matter = models.CharField(max_length=400) comment = models.TextField starting_time = models.TimeField ending_time = models.TimeField date = models.DateField migration details for personalInfo.py # Generated by Django 2.0 on 2018-01-03 17:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='StudentDetails', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Students', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('student_name', models.CharField(max_length=100)), ('student_id', models.CharField(max_length=50)), ('student_dept', models.CharField(max_length=30)), ('student_sec', models.CharField(max_length=2)), ], ), migrations.CreateModel( name='TeacherDetails', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Teachers', … -
Management Command Testing with Django-Nose Database Issue
I'm working on generating unit tests for my django application, and I'm running into a bit of a snag. I'm working on a unit test that is used by the django application to generate data for the database nightly. This function is called my a manage.py command, and works find used standalone. However, when I use the following test to launch it, I get a missing table issue: # Test case def test_commit_volume_metric_generation(self): args = [ ... ] opts = {} call_command('generate_metrics', *args, **opts) #Output test_commit_volume_metric_generation (project.tests.UrlTestCase) ... Traceback (most recent call last): File "/home/ubuntu/main-site/project/management/commands/generate_metrics.py", line 236, in generate_one_metric project = Project.objects.get(id=project_id) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 381, in get num = len(clone) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 240, in __len__ self._fetch_all() File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/query.py", line 52, in __iter__ results = compiler.execute_sql() File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql cursor.execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/ubuntu/virtualenvs/venv-system/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute return Database.Cursor.execute(self, query, … -
Running python script periodically with crontab. Error
I'm using crontab to run this python script every minute: def cronSendEmail(): print("Hello") return True In the log file: /var/log/syslog Jan 3 23:37:01 brahmh CRON[4627]: (me) CMD (/home/venv/bin/python /home/proj/manage.py crontab run b74d4d1f47748498b81b5bcf863684c3 >> /home/proj/file.log # django-cronjobs for proj Jan 3 23:37:02 brahmh CRON[4626]: (CRON) info (No MTA installed, discarding output) These two statements are logged every minute. Why am I seeing 'no MTA installed, discarding output'? Also the program is not printing 'Hello' to the file.log as expected. Note: This is a django project and I'm using django-crontab to create the crontab jobs. -
Django on Heroku - ProgrammingError at / relation "..." does not exist
I'm getting this error. I know you usually get this error because the databases wasn't properly migrated. When I run heroku local web, the website works fine when I go to localhost:5000. However after I deploy the app to heroku with git push heroku master, the error comes up. In other words, it works in my local environment. But it does not work after deploying to heroku. I have Heroku-Postgres installed as an add-on in heroku. What could be causing this? -
Trying to create a home page with a login form, but getting 'NameError: name 'url' is not defined'
I'm relatively new to django and trying to create a home page that has a login form on it, consisting of username and pw bars. I was trying to recreate what I saw here in my own project: homepage login form Django but I keep getting back NameError: name 'url' is not defined. I am pretty lost on what is causing this. I was initially writing into the project level urls.py but then moved to the app level (accounts) urls.py because that makes sense to me...but I'm not confident about this. Here are my files: project ├── manage.py ├── db.sqlite3 ├── templates ├── accounts | ├──migrations | ├──_pycache_ | ├──admin.py | ├──apps.py | ├──models.py | ├──_init__.py | ├──urls.py | ├──tests.py | └──views.py └── project ├── settings.py ├── urls.py └── wsgi.py project/settings.py from django.urls import reverse_lazy import os ... SITE_ID = 1 LOGIN_URL = reverse_lazy('login') LOGIN_REDIRECT__URL = reverse_lazy('home') LOGOUT_REDIRECT__URL = '/' enter code here project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls')), path('accounts/', include('allauth.urls')), path('', include('posts.urls')), ] accounts/urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUpView.as_view(), name='signup'), url(r'^accounts/', HomeView.as_view(template_name='../templates/home.html', name='home')), url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'), url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', … -
Subclass a views in django-registration-redux
I'm using Django-registration-redux and I want give more data to a view for render my base template. I read the example in doc. My url.py: class MyPasswordChangeView(PasswordChangeView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) #context['book_list'] = Book.objects.all() #example in doc context_dict = services.get_base_data_for_views(request) return context_dict urlpatterns = [ ... path('accounts/password/change/', MyPasswordChangeView.as_view( success_url=reverse_lazy('auth_password_change_done')), name='auth_password_change'), ... ] I have the extra data in services.py but this code gives error: name 'request' is not defined so context_dict isn't definited. Should I write another function? Thank you -
Get full URL image with object ID - Django Rest Framework
I write a Serializer in Django Rest Framework about Profile have Avatar Image but I want to get full URL Image instead of ID. My Serializers (which return profile_pic_url is ID): class ProfileDetailSerializer(ModelSerializer): profile_pic_url = SerializerMethodField() class Meta: model = Profile fields = [ 'profile_pic_url', ] def get_profile_pic_url(self, obj): request = self.context.get('request') profile_pic_url = obj.profile_pic_url.image return request.build_absolute_uri(profile_pic_url) This code returns this issues: 'ImageFieldFile' object has no attribute 'find' -
Command "python setup.py egg_info" failed with error code 1 When installing Django
Egg_info Error getting this error when attempting to pip install Django. Is there something i am doing incorrectly?? -
Why Django redirects me to my api view after save a record with ajax?
I have a problem, I'm using Django with restframework to develop a school project but when I save a record with ajax this redirects me to the api page and not to the CRUD page, only admins can see the api page(view) so... Can you help me to resolve this? this is my views.py class pacientesList(generics.ListCreateAPIView): queryset = Paciente.objects.all() serializer_class = pacienteSerializer permission_classes = (IsAuthenticated, ) def list(self, request): queryset = self.get_queryset() serializer = pacienteSerializer(queryset, many=True) return Response(serializer.data) def perform_create(self, serializer): serializer.save(user=self.request.user) and this is my ajax code to save data $("#btnGuardarPaciente").click(function() { $.ajax({ url: '{% url "core:pacientes_list" %}', type: 'POST', data: $("form").serialize(), dataType: 'json', success: function(data) { console.log(data); // only to see if this is working alert("Paciente agregado!."); $("#exampleModal").modal('toggle'); }, error: function(xhr, resp, text) { console.log(xhr, resp, text); } }); }); It's working fine, this save the record into db but only the problem is when I click on save button this redirects me to my api page and not to the CRUD page. my html form <form id="savePaciente" action="{% url 'core:pacientes_list' %}" method="post" >{%csrf_token%} <md-form> <input type="text" required name="first_name" class="form-control" id="id_first_name" placeholder="Nombre(s)"> <input type="text" required name="last_name" class="form-control" id="id_last_name" placeholder="Apellidos"> <label for="id_gender">Selecciona el sexo</label> <select class="form-control" name="gender" id="id_gender" required> … -
django: list transfer to template and to JS
In Views.py i create a list variable - mortgages_counter.append(MonthlyPaymentAmount) it is transferred to .html template as: <input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{mortgages_counter}}'> in JQuery (separate file i have to check if each element of this list is used). value is transferred to .js file as: var mortgages_counter = $('#mortgages_counter').val(); but according to console it was transferred as a string to Jquery - like ['1234','125'] and its length is 1 because of some reason, also check like access to index [0] gives - ' and [1] - 1 etc. how to operate with this list as with LIST and NOT a string? -
Order by in django doesn't work well
I have this model in my django project: lass Archivos(models.Model): ramo = models.ForeignKey(Ramo, on_delete=models.CASCADE) anyo = models.PositiveIntegerField() semestre = models.PositiveIntegerField() tipo = models.CharField(max_length=20) detalle_tipo = models.IntegerField() extension = models.CharField(max_length=5) archivo = models.FileField(upload_to='archivo/', null=True) def __str__(self): return '%s %s %s %s %s %s' % (self.ramo, self.anyo, self.semestre, self.tipo, self.detalle_tipo, self.extension) When I try to make a query of this objects, ordering by -anyo (Year descending), the list of objects are ordering ascending. This is my query: archivos = Archivos.objects.filter(ramo=ramo.id).order_by('-anyo', 'semestre','detalle_tipo') I've try adding a Meta class in my model like this: class Meta: ordering = ['-anyo'] But the list is still ordering ascending. It doesn't matter if the query is ordering by anyo or -anyo. How to solve this? I'm using the last version of django. -
Django 1.11: pass id to url to generate detail view
I've a list of "nanas" (babysitters) that I render correctly. Now I need that when someone clicks on one of them , a detail page (for only the clicked nana opens). I think my problem is on my template for all the Nanas, in the href: <a href="{% url 'app-administrador:nana' nana.id %}"> Or in the Urls. All Nanas page: This is listing nanas View: class NanasView(View): def get(self, request): nanas = Nana.objects.all() context = {'nanas': nanas} return render(request, 'app_administrador/nanas-registradas.html', context) It's URL: url(r'^referencias_de_nanas', views.NanasReferenciasView.as_view(), name='referencias_de_nanas'), All Nanas templates: {% extends 'app_administrador/templates/base.html' %} {% load staticfiles %} {% block content %} <!-- Member Entries --> {% for nana in nanas %} <!-- Single Member --> <div class="member-entry"> <a href="extra-timeline.html" class="member-img"> <i class="entypo-forward"></i> </a> <div class="member-details"> <a href="{% url 'app-administrador:nana' nana.id %}"> <h4> <p href="extra-timeline.html">{{ nana.nombre }} {{ nana.apellido_paterno }} {{ nana.apellido_materno }}</p> {% if nana.foto %} <img src="{{ nana.foto.url }}" class="img-rounded" width="160px"/> {% endif %} </h4> <!-- Details with Icons --> <div class="row info-list"> <div class="col-sm-4"> <i class="entypo-briefcase"></i> <a href={{ nana.antecedentes_policiales }}>Antecedentes policiales</a> </div> <div class="col-sm-4"> <i class="entypo-twitter"></i> <a href="#">@johnnie</a> </div> <div class="col-sm-4"> <i class="entypo-facebook"></i> <a href="#">fb.me/johnnie</a> </div> <div class="clear"></div> <div class="col-sm-4"> <i class="entypo-location"></i> <a href="#">{{ nana.direccion }}</a> </div> <div class="col-sm-4"> … -
Need to save a model accessed throuh ForeignKey Relation
Taking the below class, with a OneToOne Relation to django's user-model, is there a need to save the user object if it gets modified? In my testings it sometimes got updated and sometimes not. Is there some configuration to control this behaviour or should I simply call save() every time. Witch would also, through signals, call MyModel every time. class MyModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def first_name(self): return self.user.first_name @first_name.setter def first_name(self, first_name): self.user.first_name = first_name # is this needed? self.user.save() -
Django: Trying to click on a link and remove an assigned client
Good morning. I am having an issue trying to remove a client from an assigned bed. I created a one-item form called "RoomUpdate" that will allow a user to add a client to a bed that is empty via a dropdown through a ModelChoiceField. When the bed is full, it does not allow the access to the drop down, instead, I have a link that states "remove client." What I want to happen is when I click that button, it assigns the default value of None to that bed in that room. What's tricky, at least to my new-ish to Django mind, is how I do this through multiple tables. Having looked for multiple answers and tried different things, I know I've lost track of what I'm doing so I definitely could use some help. models.py class Room(models.Model): room_id = models.AutoField(primary_key=True) room_number = models.CharField(max_length=5) shelter_id = models.ForeignKey(Shelter) max_occupancy = models.CharField(max_length=3) floor_location = models.CharField(max_length=3) def __str__(self): return self.room_number class Bed(models.Model): bed_id = models.AutoField(primary_key=True) room_id = models.ForeignKey(Room, related_name='beds') bed_size = models.ForeignKey(BedSize) client_assigned = models.ForeignKey(Clients, null=True, blank=True, default=None) forms.py class RoomUpdate(forms.ModelForm): client_assigned = forms.ModelChoiceField(queryset=Clients.objects.all(), required=False) #def __init__(self, *args, **kwargs): #super(RoomUpdate, self).__init__(*args, **kwargs) #self.fields['client_assigned'].choices.insert(0, ('','---------' ) ) class Meta: model = Room fields = … -
Cron log showing shows cron jobs are running but not being executed? (Django-Python)
I have a django project and I'm using django-crontab to execute a periodic task. For testing I have this task at myapp/cron.py def cronSayHello(): print("Hello") return True In settings.py I have: CRONJOBS = [ ('*/1 * * * *', 'myapp.cronSayHello', '>> /home/myuser/myproj/myapp/file.log') ] No "Hello" is being printed in file.log . Am I missing something? Also /var/log/syslog shows: Jan 3 21:44:01 brahmh CRON[21727]: (vaish) CMD (/home/myuser/myvenv/bin/python /home/myuser/myproj/manage.py crontab run b74d4d1f47748498b81b5bcf863684c3 >> /home/myuser/myproj/myapp/file.log # django-cronjobs for myproj) Jan 3 21:44:01 brahmh CRON[21726]: (CRON) info (No MTA installed, discarding output) This is being logged every minute. Why is the output discarded? -
errorlist this field is required
form = AuthorForm(self.request.POST, self.request.FILES, self.request.user) class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['file','user'] class Author(models.Model): user = models.ForeignKey(User) file = models.FileField(upload_to='authors/') With above configuration, I get the error <tr><th><label for="user">User:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select id="user" name="user" required <option value="" selected="selected">---------</option> <option value="2">admin</option> <option value="3">user2</option> I do not want to set blank=True in user field. I've passed request.user to ModelForm and I want the same to be stored in db but it's not working as expected. May I know how to pass request.user to ModelForm.