Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is_valid() failure
I tried several ways but is_valid() always returns false. Not sure why. I copied nearly whole syntax for better understanding but I don´t you need all that code. I really would be thankful for having help. Thanks! html: {% csrf_token %} {{ FirstContactForm.message }} forms: class FirstContactForm(forms.ModelForm): firstName = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Vorname', } )) imagine some more forms but cut them out for better overview message = forms.CharField(widget=forms.Textarea( attrs={ 'class': 'form-control', 'rows': '4', 'id': 'exampleFormControlTextarea1', 'maxlength': 2000, } )) class Meta: model = ContactForm fields = ('vorname', 'nachname', 'email', 'nummer', 'handyNummer', 'nachricht',) views class Contact(TemplateView): template_name = 'contact.html' context = { 'FirstContactForm': FirstContactForm, } def get(self, request): return render(request, self.template_name, self.context) def post(self, request): form = FirstContactForm(request.POST) text = form.cleaned_data['vorname'] if form.is_valid(): form = FirstContactForm(commit=False) form.save() text = form.cleaned_data['vorname'] form = FirstContactForm() return redirect('index') args = {'FirstContactForm': FirstContactForm, 'text': text} return render(request, self.template_name, args) model: class ContactForm(models.Model): vorname = models.CharField(max_length=400) nachname = models.CharField(max_length=400) email = models.CharField(max_length=400) nummer = models.CharField(max_length=400) handyNummer = models.CharField(max_length=400) nachricht = models.CharField(max_length=2000) -
NoReverseMatch not matching key argument
I have a response error that is driving me crazy, I tried everything but no way to find why am I getting that error : django.urls.exceptions.NoReverseMatch: Reverse for 'team_select' with keyword arguments '{'pk1': ''}' not found. 1 pattern(s) tried: ['website/project/(?P<pk1>[0-9]+)/linkteam2/$'] that is my views: class HomePage(TemplateView): template_name= 'index.html' class LinkTeam(generic.ListView): template_name = 'link_project.html' def get_queryset(self): #import pdb; pdb.set_trace() #team2 = Team.objects.all().filter(team_hr_admin = self.request.user) queryset = Team.objects.filter(team_hr_admin=self.request.user) return queryset def TeamSelect(request): import pdb; pdb.set_trace() if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): data = select_form.cleaned_data['team_choice'] obj2 = Project.objects.filter(project_hr_admin=request.user) obj3 = obj2.latest('id') if obj3.team_id == None: obj3.team_id = data obj3.save() obj4 = obj3.team_id obj5 = obj4.members.all() for i in obj5: current_site = get_current_site(request) message = render_to_string('acc_join_email.html', { 'user': i.first_name, 'domain':current_site.domain, }) mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app' to_email = i.email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() messages.success(request, 'test') return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':obj3.id})) else: print('this project has already a team') else: print('Non Valid form') else: select_form = EditSelectTeam(request.user) return render(request,'link_project.html', {'select_form':select_form }) class HRIndex(generic.ListView): #import pdb; pdb.set_trace() template_name = "HR_index.html" model = Project class CandidateIndex(TemplateView): #import pdb; pdb.set_trace() template_name = "candidate_index.html" class EmployeeIndex(TemplateView): #import pdb; pdb.set_trace() template_name = "employee_index.html" def get_context_data(self, **kwargs): … -
Add A New Field To Existing Model - django.db.utils.ProgrammingError: column {field} does not exist
models.py I have a Scorecard model that has a ManyToManyField to another model named Account: class Scorecard(models.Model): .... name = models.CharField(max_length=100) accounts = models.ManyToManyField(Account) ... def __str__(self): return self.name My Account class currently has four fields (account_name, adwords_account_id, bingads_account_id, label). class Account(models.Model): account_name = models.CharField(max_length=100) adwords_account_id = models.CharField(max_length=10, blank=True) bingads_account_id = models.CharField(max_length=15, blank=True) # gemini_account_id = models.CharField(max_length=15, blank=True) label = models.CharField(max_length=30, blank=True) def __str__(self): return self.account_name Notice that field gemini_account_id is commented out. I want to add this field to the model. If I leave gemini_account_id commented out and runserver, everything works fine. If I then uncomment gemini_account_id and do python manage.py makemigrations (venv) C:\Django\scorecard>python manage.py makemigrations FULL ERROR Traceback (most recent call last): File "C:\Django\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column scorecards_account.gemini_account_id does not exist LINE 1: ...t_id", "scorecards_account"."bingads_account_id", "scorecard... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Django\venv\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Django\venv\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "C:\Django\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Django\venv\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Django\venv\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Django\venv\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', … -
Static Root - Django version 2.0.1
Upgraded from Django 1.10 to 2.01. Settings.py (Has not changed) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = os.path.join('/processor/', 'static/') python manage.py collectstatic & python manage.py runserver both return the same errors below: hal@hal:~/CSsite$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Django version 2.0.1, using settings 'CSsite.production' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [ERROR] (Thread-1 ) Internal Server Error: / Traceback (most recent call last): File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hal/CSsite/processor/views.py", line 108, in index return render(request, 'processor/select.html', dic) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/backends/django.pstaticfilesy", line 61, in render return self.template.render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 943, in render bit = node.render_annotated(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated return self.render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/templatetags/static.py", line 106, in render url = self.url(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/templatetags/static.py", line 103, in url return self.handle_simple(path) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/templatetags/static.py", line 118, in … -
django-crontab does not execute scheduled jobs
I am having a very similar virtualenv setup than in the question: Django crontab not executing test function. in my_app.cron.py def test(): print('HELLO') in settings.py INSTALLED_APPS = ( ... 'django_crontab', ) CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'my_app.cron.test','>> /cron_job.log'), ] python manage.py crontab add adding cronjob: (bee8ad945bb9c6b15a3ff0847481a181) -> ('*/1 * * * *', 'my_app.cron.test', '>> /cron_job.log') python manage.py crontab show Currently active jobs in crontab: bee8ad945bb9c6b15a3ff0847481a181 -> ('*/1 * * * *', 'my_app.cron.test', '>> /cron_job.log') Everything seems fine yet nothing is printed in the log file or the console. What's missing here? -
userprofile-0-id Error , working with Django inline_formset
i am trying to let my site's users to edit their own profile pages, where that page contains information from poth "User model" & "UserProfile model", using django inline_formset, but i am encountering,userprofile-0-id error when submiting the form . models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(default=0) image = models.ImageField(upload_to="profile_image", blank=True) description = models.CharField(max_length=200, default='') category = models.CharField(max_length=600, default='') website = models.URLField(default='', blank=True) forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'last_name', 'email'] views.py @login_required() # only logged in users should access this def edit_user(request, pk): # querying the User object with pk from url user = User.objects.get(pk=pk) # prepopulate UserProfileForm with retrieved user values from above. user_form = UserForm(instance=user) # The sorcery begins from here, see explanation below ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('website', 'description', 'phone','category','image',)) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": user_form = UserForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return HttpResponseRedirect('/accounts/profile/') return render(request, "accounts/update.html", { "noodle": pk, "noodle_form": user_form, "formset": formset, }) else: raise PermissionDenied update.html <form action="." method="POST"> {% csrf_token %} <div class="form-row"> <div class="col"> <label for="Firstname">Vender Name</label> {% render_field … -
Can't create an object in django when field is a file
I'm using the last version of django and also I use Postgresql. I have a model called Subidos: class Subidos(models.Model): ramo = models.CharField(max_length=100) tipo = models.CharField(max_length=100) anyo = models.CharField(max_length=100) semestre= models.CharField(max_length=100) archivo = models.FileField(upload_to='pendientes/', null=True) def __str__(self): return '%s %s %s %s' % (self.ramo, self.tipo, self.anyo, self.semestre) As you see, archivo is a file. Now, my html form receive all this parameters (Works fine): <form method="post" action="{% url 'materialfdi:subir2' %}" enctype="multipart/form-data">{% csrf_token %} <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2" for="inputHelpText">Ramo</label> <div class="col-lg-6"> <input type="text" class="form-control" id="nombre_ramo" name="ramo" placeholder="Ejemplo: Bases de datos CIT"> <span class="help-block">Si existe el mismo ramo en distintas escuelas, por favor aclara a cual pertenece.</span> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2" for="inputHelpText">Tipo de archivo</label> <div class="col-lg-6"> <input type="text" class="form-control" id="tipo_archivo" name="tipo" placeholder="Ejemplo: Semestre 2"> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2" for="inputHelpText">Año del material</label> <div class="col-lg-6"> <input class="form-control" id="anyo" name="anyo" placeholder="Ejemplo: 2017" type="number"> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2">Semestre del material</label> <div class="col-lg-6"> <select class="form-control mb-3" name="semestre"> <option>Primer semestre</option> <option>Segundo semestre</option> </select> </div> </div> <div class="form-group row"> <label class="col-lg-3 control-label text-lg-right pt-2">File Upload</label> <div class="col-lg-6"> <div class="fileupload fileupload-new" data-provides="fileupload"> <div class="input-append"> <div class="uneditable-input"> <i class="fa … -
how to run celery with django on openshift 3
What is the easiest way to launch a celery beat and worker process in my django pod? I'm migrating my Openshift v2 Django app to Openshift v3. I'm using Pro subscription. I'm really a noob on Openshift v3 and docker and containers and kubernetes. I have used this tutorial https://blog.openshift.com/migrating-django-applications-openshift-3/ to migrate my app (which works pretty well). I'm now struggling on how to start celery. On Openshift 2 I just used an action hook post_start: source $OPENSHIFT_HOMEDIR/python/virtenv/bin/activate python $OPENSHIFT_REPO_DIR/wsgi/podpub/manage.py celery worker\ --pidfile="$OPENSHIFT_DATA_DIR/celery/run/%n.pid"\ --logfile="$OPENSHIFT_DATA_DIR/celery/log/%n.log"\ python $OPENSHIFT_REPO_DIR/wsgi/podpub/manage.py celery beat\ --pidfile="$OPENSHIFT_DATA_DIR/celery/run/celeryd.pid"\ --logfile="$OPENSHIFT_DATA_DIR/celery/log/celeryd.log" & -c 1\ --autoreload & It is a quite simple setup. It just uses the django database as a message broker. No rabbitMQ or something. Would a openshift "job" be appropriated for that? Or better use powershift image (https://pypi.python.org/pypi/powershift-image) action commands? But I did not understand how to execute them. Help is very appreciated. Thank you -
Django, Axax PUT 400 Bad request
I have a problem with Django (rest) and ajax, when I try to send the data of a form with the method (PUT), in the browser console sends me an error (PUT '/ url / api / 1', 400 Bad request) , before coming and ask I started to investigate about this error and in many other posts give as a solution to use "JSON.stringify" to convert to json the form with the data to update, I have tried this and it did not work, another is use - contentType: "application / json; charset = utf-8", - but it did not work either, someone who can help me? my views.py class pacienteDetail(APIView): def get_object(self, pk): try: return modelsHC.Paciente.objects.get(pk=pk) except modelsHC.Paciente.DoesNotExist: raise Http404 def get(self, request, pk, format=None): paciente = self.get_object(pk) serializer = pacienteSerializer(paciente) return Response(serializer.data) def put(self, request, pk, format=None): paciente = self.get_object(pk) serializer = pacienteSerializer(paciente, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): paciente = self.get_object(pk) paciente.delete() return Response(status=status.HTTP_204_NO_CONTENT) class pacientesList(generics.ListCreateAPIView): queryset = modelsHC.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) my form.html <form class="form-edit" action="{% url … -
django login_required decorator does not work with ip 127.0.0.1
I have created a login system the view is as follows: def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('home:index') else: form = AuthenticationForm() return render(request,'accounts/login.html',{'form':form}) and added a login_required decorator to the home page as follows: @login_required(login_url="/login/") def index(request): return render(request, 'home/index.html', context) the problem is when I access the index page with localhost:8000/home/ the page is redirected correctly to the login page but with 127.0.0.1:8000/home/ the home page is rendered and i am not redirected to the login page! any solution? thanks in advance! -
Why are images stored in a Django DB not displaying on a rendered template?
I have the following code snippets in which I am trying to display images stored in a database. (Django2); however, the images are not rendering on my template, they only display a broken image link icon. It is a simple DB model that receives images, and then displays those images in a div below. I presume that my issue must be the routing of the development server, but the documentation isn't explicit as I'd like it to be, since there are many different ways of doing this. Objective: How can I display images that are uploaded to my DB on a django rendered template? See below: # models.py from django.db import models CATE_CHOICES = ( ('MIN', 'MINIMAL'), ('BLOG', 'BLOG'), ('BIO', 'BIO'), ('STORE', 'STORE') ) # NEW_CHOICE = ( # (0, '0'), # (1, '1'), # ) NEW_CHOICE = ( ('NEW', 'new'), ('OLD', 'old'), ) # Create your models here. class catalogdb(models.Model): ''' This is used to handle the actual themes for WP. ''' name = models.CharField(null=False, max_length=20) dateAdded = models.DateField(auto_now_add=True) dloads = models.IntegerField(default=0) imgpocket = models.ImageField(null=False, upload_to='images/preview_icons') filepocket = models.FileField(upload_to='themes') desc = models.TextField(null=False, max_length=500) categ = models.CharField(max_length=15, choices=CATE_CHOICES) new = models.CharField(max_length=7, choices=NEW_CHOICE) def __str__(self): return "{0}/\n{1}/\n{2}/\n{3}/\n{4}/\nNew:{5}/".format( self.name, self.dateAdded, self.dloads, self.desc, … -
Cannot query "The Witcher 3: Wild Hunt": Must be "Article" instance
models.py for products from django.db import models from django.urls import reverse class ProductCategory(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.name class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) description = models.TextField(default=None) processor = models.CharField(max_length=300, blank=True, null=True, default=None) video = models.CharField(max_length=300, blank=True, null=True, default=None) ram = models.CharField(max_length=300, blank=True, null=True, default=None) disk_space = models.CharField(max_length=300, blank=True, null=True, default=None) oS = models.CharField(max_length=300, blank=True, null=True, default=None) video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None) img = models.CharField(max_length=10000, blank=True, null=True, default=None) category = models.ManyToManyField(ProductCategory, blank=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('product', args=[str(self.slug)]) class Meta: verbose_name = 'Game' verbose_name_plural = 'Games' class ProductDownload(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) link = models.CharField(max_length=10000, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) number = models.PositiveIntegerField(blank=True, default=True) def __str__(self): return '%s' % self.product.name class Meta: ordering = ['number'] class Meta: verbose_name = 'Download Link' verbose_name_plural = 'Download Links' class ProductImage(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) image = models.CharField(max_length=10000, blank=True, null=True, default=None) is_main = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.product class Meta: verbose_name = 'Image' … -
Django testing: How to test if an instance is part of the model object set?
The wording to this question is clumsy, sorry about that. I am trying to test whether an instance has been included in model objects. In short is instance, _ = AModel.objects.get_or_create(...) is instance is included AModel.objects. I am using: self.assertIn(model_name_instance, model_name.objects) but I get the error: TypeError: argument of type 'Manager' is not iterable Thank you for your time. -
Django local development server hangs after calling pandas df.plot a second time
I'm trying to build a small website, using django, that stores network performance data. The user will be able to use filters to retrieve the exact data he/she wants and then have the option to graph that data. I'm using django-pandas to convert filtered queryset to a dataframe and from there to create a plot. Everything works fine the first time the plot function is called. When the plot function is called a second time, the python web server just hangs (started from python2.7.exe manage.py runserver). Here is the django view function: def FilteredPerformanceChartsView(request): f = PerfvRtrOnlyFilter(request.GET, queryset=PerfvRtrOnly.objects.all()) df = read_frame(f.qs, fieldnames=['runDate', 'deviceName', 'aggrPPS', 'jdmVersion']) ################################################################# # Let's pass the Pandas DataFrame off to a seperate function for # further processing and to generate a chart. # This should return an image (png or jpeg) ################################################################# chart = pandas_generate_chart(f.qs) return render(request, 'performance_charts.html', context={'filter': f, 'chart': chart, 'dataFrame': df, }, ) The function pandas_generate_chart is where the problem is. After performing a lot of troubleshooting, what appears to trigger the hang is calling df.plot a second time. In other words, when the user hits the button to generate a different chart. Until that second request to generate a chart is submitted, … -
CSRF Cookie Not Set
I have problem with Django CSRF. When I try to register new user or log in I get the next error: CSRF cookie not set. Also on the register page the username and web-site label's don't load correctly, I get symbols like this: 'Ð˜Ð¼Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ' instead. I have already tried CSRF_COOKIE_SECURE = True,django.middleware.csrf.CsrfViewMiddleware, clearing browser data, my {% csrf_token %} is placed inside the form. Could anyone give me at least some hints about possible errors? My code: forms.py: <form method="post" action="register/"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} views.py def register(request): c = {} c.update(csrf(request)) registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() return render_to_response( 'register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, c) Thank you for your consideration! -
ValidationError: is not a valid UUID in Django
I'm using Django 2.0 I have a Note table and StarredNotes table. Initially, there was no id field as it was added by default by Django as integer data type. Now I have changed the data type of id to UUID in model model.py class Starred(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) note = models.ForeignKey(Note, on_delete=models.CASCADE) objects = StarredManager() and views.py class StarredNotes(ListView): template_name = 'notes/starred.html' model = Starred context_object_name = 'starred_notes' def get_queryset(self): starred_notes = Starred.objects.filter(user=self.request.user).order_by('-updated') return starred_notes @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) and urls.py app_name = 'notes' urlpatterns = [ path('starred-notes/$', StarredNotes.as_view(), name='starred'), ] but when I access the view using http://127.0.0.1:1234/notes/shared-notes/ It gives error as ValidationError at /notes/shared-notes/ ["'shared-notes' is not a valid UUID."] -
How to handle video files uploads with django
I'm working on a django project that requires video files of any kind to be uploaded and then transcoded. Everything work fine its just that I sporadically get a "Timeout when reading response headers from daemon process" when uploading a video (well under 2GB in size). This occurs before any processing of the file. I've looked online for a solution and have tried several things to fix, including WSGIApplicationGroup %{GLOBAL} in the httpd.conf and increasing the TimeOut values, but the problem persists. Is there anything I can do in python/django to fix this issue? -
DDT in the Django-admin
Here is what I have in my settings.py file """ Django development settings for v6 project. """ from .common import * # noqa DEV = True DEBUG = True STAGE = 'dev' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' USERENA_USE_HTTPS = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] INSTALLED_APPS = INSTALLED_APPS + [ 'django.contrib.staticfiles', 'debug_toolbar', 'django_extensions', ] MIDDLEWARE = MIDDLEWARE + [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', ] DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } I don't know why, but I can't see the Django debug toolbar in the http://localhost:8000/admin even if I am following the instruction on http://django-debug-toolbar.readthedocs.io/en/stable/installation.html. Django_extensions is working well, but not DDT. What do I need to do to show DDT in the admin? Do I need to add something in settings.py? -
'AttributeError' when overriding 'RelatedField' in Serializing
I'm working with a Django project that implement the Rest framework. I have this model class Portfolio(models.Model): ticker = models.CharField(max_length=10, default='???') name = models.CharField(max_length=25) amount = models.FloatField() owner = models.ForeignKey('auth.User', related_name='portfolio', on_delete=models.CASCADE) def __str__(self): return self.name Note on the 'owner' ForeignKey. And in my serializers.py I have this class MyRelatedField(serializers.RelatedField): def to_representation(self, obj): return 'Test' class UserSerializer(serializers.ModelSerializer): portfolio = serializers.MyRelatedField(many=True) class Meta: model = User fields = ('url', 'id', 'username', 'portfolio') AS I read on the docs, I should override the RelatedField (which I did) if I want a custom representation. However when I try to run I get this error AttributeError: module 'rest_framework.serializers' has no attribute 'MyRelatedField' No matter what I return in MyRelatedField, the same error occurs. My question is how to debug and ideally, fix this error. Thank you. -
Django null value in column "user_id" violates not-null constraint DETAIL: Failing row contains
I have the following problem: I am try to save the user and profile but When I try to post in my database the following error occur: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (16, 2018-01-01 00:00:00+00, null, colegio monserrat, femenino, null, primero, social, null, null, null, null, null, null, null, null, null, null, Ciencias mundo contemporáneo, Historia de la filosofía, Lengua catalana y literatura I, Lengua catalana y literatura II, Lengua extranjera I, Lengua extranjera II, Lengua castellana y literatura I, Lengua castellana y literatura II, fisica, matematicas, quimica, matematicas, matematicas, matematicas, matematicas, fisica, Educación física, Filosofía, null, Historia). My models is the following: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateTimeField(null=True, blank=True) sex = models.CharField(null=True, max_length=50, choices=SEX_CHOICES) school = models.CharField(null=True, max_length=50, choices=SCHOOL_CHOICES) schoolCode = models.IntegerField(null=True) bachelorCourse = models.CharField(null=True, max_length=50, choices=COURSE_CHOICES) bachelorModality = models.CharField(null=True, max_length=50, choices=COURSE_MODALITY_CHOICES) password = models.CharField(null=True, max_length=50) password2 = models.CharField(null=True, max_length=50) obligatorySubjectOne1 = models.CharField(null=True, max_length=100, default='Lengua catalana y literatura I') obligatorySubjectTwo1 = models.CharField(null=True, max_length=100, default='Lengua castellana y literatura I') obligatorySubjectThree1 = models.CharField(null=True, max_length=100, default='Lengua extranjera I') obligatorySubjectFour1 = models.CharField(null=True, max_length=100, default='Ciencias mundo contemporáneo') obligatorySubjectFive1 = models.CharField(null=True, max_length=100, default='Educación física') obligatorySubjectSix1 = models.CharField(null=True, max_length=100, default='Filosofía') optionalSubjectOne1 = models.CharField(null=True, max_length=100, choices=SUBJECTS_CHOICES_OPTIONALLY) optionalSubjectTwo1 … -
Can't use django variable in include tag
I'm trying to include a .html using {% include "paintings/experiments/points/{{substance.name}}.html" %} This however leads to the error TemplateDoesNotExist. If I hardcode the name of the .html file, it does work. {% include "paintings/experiments/points/fabric.html" %} And, in fact, I can use {{substance.name}} inside the included html, were it does indeed get substituted for fabric. Why can I not use a django variable when using an include tag? -
Django: Hide language prefix conditionally
I'm trying to hide the language prefix in my URL depending on a configuration saved in the database. I already know that setting prefix_default_language=False will hide the default language. My problem: I need the default language to be hidden or showed dynamically depending on a saved object in the database. My idea: create a middleware that reads the object in database and show or hide the prefix. Additional info: I am using the middleware 'django.middleware.locale.LocaleMiddleware'. -
Cutom widget in Django template using inline_formset
I have 2 models Company and CompanyLogo, where CompanyLogo has an FK to Company. For the CompanyLogo I want to have a custom widget. Even if I created a custom widget Django is still using the default Widget, and I don't know why ? The relation between CompanyLogo and Company is 1 to many. It is the same logo, but on different size. If I want to show only a specific size of the logo in widget, how can I replace the for loop and pass that specific size in template ? Models: class Company(Meta): name = models.CharField(max_length=255) class CompanyLogo(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) logo = models.ImageField(upload_to='static/temp') Forms: class CompanyLogoModelForm(forms.ModelForm): class Meta: model = CompanyLogo fields = ['logo'] widgets = { 'logo': forms.CompanyLogoWidget } CompanyLogoFormSet = forms.inlineformset_factory(parent_model=Company, model=CompanyLogo, form=CompanyLogoModelForm, extra=1, can_delete=True) Template: {% for logo_form in form.logos %} {{ logo_form }} {% endfor %} -
Is it possible to pass values from a query to models.py in django?
I'm trying to make an app that some person inserts an id and a birthday date from someone and outputs something. My doubt here is: having a query (from oracle) with the severall id and birthday dates using: connection = cx_Oracle.connect(...) cursor = connection.cursor() cursor.execute("query") My question is: Is it possible to pass some values from the query to my models.py file? For example, in my "models.py" file I have a field called "id" and I would like to pass all the records from the query in the field "doente" to the "models.py" file as "id". My form is something like this: Form where the values from the fields: "GTS do autorizante" and "Data de nascimento do autorizante" are in my models.py and the values from the fields: "GTS do autorizado" and "Data de nascimento do autorizado" come from the query. I would like to copy all the values from the query to my models.py file but I don't know if that is possible. -
Maintain timezone awareness with date and time arithmetic
According to Django : RunTimeWarning : DateTimeField received a naive datetime while time zone support is active, get today's date with timezone information with from django.utils import timezone today = timezone.now() When I do: from datetime import timedelta yesterday = today - timedelta(days=1) But now yesterday is no longer timezone aware. How do I maintain the timezone awareness while doing date and time arithmetic?