Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - get() missing 1 required positional argument: 'header'
I am trying to develop a REST framework where IoT devices upload data to the server. I am using a python program to simulate that using urllib during development. Sometimes the program uploads successfully, but other times returns a HTTP 500 with the following Django error information. TypeError at /logdata/ get() missing 1 required positional argument: 'header' Request Method: POST Django Version: 2.0.3 ... Exception Location: /usr/local/lib/python3.5/dist-packages/django/middleware/clickjacking.py in process_response, line 26 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.3 I found a similar SO question dealing with HTML forms, but I am doing simply raw POST requests with URL-encoded data, and hence do not need a HttpResponseRedirect do I? I only return HttpResponseBadRequest when invalid data is sent, and application/json data when the request is valid. Here is a simplified version of my Django view: def publish_data(request): params = request.POST if validate(params): ... # do stuff with params return HTTPResponse(my_data, content_type="application/json") else: return HttpResponseBadRequest('Invalid Data') The exception location seems to be tied to setting X-Frame-Options: SAMEORIGIN which I tried to do manually within my Django view, but I still get the HTTP 500 error. Any ideas for common pitfalls I can check for? -
Invalid form with FileField
I have an UpdateView with an object which has a FileField. If the model has a file uploaded, I show the link to the file, and also a file input in case the user wants to update it. <form> {% if object.file %}<a href="{{ object.file.url}}">Download</a>{% endif %} <input type="file" name="{{ form.file.name }}"> <input type="text" name="{{ form.other_field.name }}"> </form> which works fine if the object is new and does not have a file, in which case the Download link does not show or if it has a file, in which case the Download link shows up. But, if I select a file to upload, and the form is invalid, the object.file field exists, and it points to a non-existent file. Is there a way to tell in an invalid form if the file is real? -
Ajax call is not working when selecting checkboxes in the form
I am developing a form using django framework. I have a form where i have a table followed by some check boxes in the form. I am collecting that data into a dictionary and passing that to my django function. If i am submitting my form without selecting checkboxes it is working fine. But when i select checkboxes that data is not getting posted to views.py file. I see that data is being populated in the dictionary by using console.log. Require guidance regarding this. my html: `<table> ..... ..... </table> <div class="checkbox"> <label><input type="checkbox" name="run_prep" value="">Run Prep</label> </div> <div class="checkbox"> <label><input type="checkbox" name="run_post"value="">Run Post</label> </div>`enter code here` <div class="checkbox"> <label><input type="checkbox" name="run_reports" value="">Run Reports</label>`enter code here` </div>` Below is my js code: `$(document).ready(function(){ $("form").submit(function(e){ e.preventDefault(); var data = {}; form_data = [] $("tr", "tbody").each(function(row){ var count_row = true; $("input", this).each(function(idx, inp){ if (!($(this).val())){ count_row = false; } }); $("select", this).each(function(idx, inp){ if (!($(this).val())){ count_row = false; } } ); if (count_row){ row_data = {}; $("input", this).each(function(idx, inp){ row_data[$(this).attr("name")] = $(this).val(); }); $("select", this).each(function(idx, inp){ row_data[$(this).attr("name")] = $(this).val(); }); var id = $(this).attr("id"); data[id] = row_data; form_data.push(data); data = {}; } }); run_check = {}; $("input[type=checkbox]", this).each(function () { if (this.checked) … -
Replace windows authentication popup with custom page in django
I want to replace the windows authentication popup with custom login page in django. Thanks In Advance. -
How to block selected characters in simple register Django.
I have a problem with simple registration in Django. When the user will write at the first registration the username with '.' or @, for example 'User.Name' my internet application returns error like this 'NoReverseMatch at /' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.7 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'reviews', 'registration'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\tymot\Desktop\projrkt22.08-20.00\env\my_app\winerama\templates\base.html, error at line 50 Reverse for 'user_review_list' with arguments '('aleksandra.franiczek',)' not found. 2 pattern(s) tried: ['review/user/$', 'review/user/(?P<username>\\w+)/$'] 40 : </div> 41 : <div class="col-sm-4 offset-md-1 py-4"> 42 : <h4 class="text-white">Nawigacja</h4> 43 : <ul class="list-unstyled"> 44 : <li><a href="{% url 'reviews:home' %}" class="text-white">Strona główna</a></li> 45 : <li><a href="{% url 'reviews:wine_list' %}" class="text-white">Lista produktów</a></li> 46 : <li><a href="{% url 'reviews:review_list' %}" class="text-white">Najnowsze opinie</a></li> 47 : </ul> 48 : <ul class="list-unstyled"> 49 : {% if user.is_authenticated %} 50 : <li><a href=" {% url 'reviews:user_review_list' user.username %} " class="text-white">Witaj {{ user.username }}</a></li> 51 : <li><a href="{% url 'reviews:user_recommendation_list' %}" class="text-white">Sugerowane produkty</a></li> 52 : <li><a href="{% url 'logout' %}" class="text-white">Wyloguj</a></li> 53 : {% else %} 54 : <li><a href="{% url 'login' %}" class="text-white">Logowanie</a></li> 55 : <li><a href="/accounts/register" class="text-white">Rejestracja</a></li> 56 : … -
How to asign function to Django forms
I would like to write a website with some calculators. Each calculator as separate app. I have ealier prepared and tested python code for main functions and now I have problem how to use it in Django. I am not using Models, I am not sure but I think as it will be fast calculation by user and no need to store data in database so I decided to use only forms. My main question is how to asign function to a Django form? By the way,how to put clear python code properly to Django to keep 'good practice of clean code'? My code: app mathcalc: mathcalc/views.py: def math_page(request): math_form = CalculationForm(request.POST or None) content = { "form": math_form } return render(request, 'math.html', content) class Calculator(object): def simpleFunction(self, a, b): score = a + b print(score) print('Tests gone well') def otherFunction(self): # function here return some stuff and in main project/forms.py: class CalculationForm(forms.Form): Years = forms.CharField() # a from simpleFunction Ammount = forms.CharField() # b from simpleFunction and in math.html: <form method='POST'> {% csrf_token %} {{ form }} <button type='submit' class='btn btn-default'>Submit</button> </form> I do not know how to connect it all, that after user input some data it will … -
calling celery task with delay gets stuck
A celery task defined like: from celery.decorators import task @task(name="send_email") def send_email(email, host): When calling it like this, Django gets stuck: send_email.delay(email, host) Like if it wasnt being ran asynchronously, what am I missing? Those are some of the celery settings, and its using redis as broker: >>> settings.CELERY_ACCEPT_CONTENT [u'application/json'] >>> settings.CELERY_BROKER_URL u'redis://redis:6379/0' >>> settings.CELERY_RESULT_BACKEND u'redis://redis:6379/0' >>> settings.CELERY_RESULT_SERIALIZER u'json' >>> -
Key error: 'Unknown language code .'
I'm trying to make a brand new project with PyCharm: Django 2 In my settings.py I've just changed this: LANGUAGE_CODE = 'fr-fr' LANGUAGES = ( ('en-us', _("English")), ('fr-fr', _("French")), ) TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True And here's my urls.py, almost empty but ready for translation: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.urls import path, re_path, include from app.views import IndexView urlpatterns = [ re_path(r'^i18n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('', IndexView.as_view(), name='app_index'), prefix_default_language=False ) Of course, views.py is 3 lines long: from django.views import generic class IndexView(generic.TemplateView): template_name = 'index.html' And I'm trying to use pre-defined stuff in the template like it's explained here, so here's my template: {% load i18n %}<!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <title>Main menu</title> </head> <body> {{ LANGUAGE_CODE|language_name_translated }} </body> </html> And when I try to display "http://127.0.0.1:8000/" i get this error: KeyError at / 'Unknown language code .' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.8 Exception Type: KeyError Exception Value: -
How to add/remove workers programatically in celery?
So basically, I want to manage the workers based on the queue size/time of the day for one particular queue. I want to run less number of workers for a queue in peak hours and increase them when the load comes down. -
django polymorphic serializer dont work
I would like use a json serializer to serialize a lot of class (https://django-polymorphic.readthedocs.io/en/stable/) with fields witch have ManyToMany, OneToMany, Foreign key relation. I have try with serializers.serialize("json", model.objects.all()) but this dont take ManyToMany and heritage. To you have a other solution ? -
Tutorial on how to implement the ability to draw a picture on a website with a mouse using Django
I want to create a 28x28 grid on my website (created with Django) where a visitor can use their mouse to draw an image (like the number 7) in the grid, then save it in the sqllite database with a label entered in an adjacent text box via a button. The data format would be 785 interger values: the first integer is the label while the 784 values are pixel grayscale intensitive values throughout the grid. I want the ability as the admin to view these data entrys as the drawn images on the website and delete the ones I want to delete. Where can I figure out how to do this? I only picked up Django twpo days ago and have followed a tutorial to make a simple poll app. -
Efficiency for many-to-one relationship
Currently, we are building a commercial API as service. We have a following requirement. User will login via email Each user has a unique API key Every consumption of API, there will be a log for audit purpose. We plan to use the following custom user model. class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email 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): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin def get_fields(self): return [(field.name, field.value_to_string(self)) for field in User._meta.fields] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_key = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) def __str__(self): return str(self.api_key) class ApiLog(models.Model): api_consumed = models.TextField(blank=False, null=False) date_consumed = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) Is the above a good data models for Django? Our worry is, a user will produce hundred thousand row of new ApiLog rows. We need not to access those data … -
Django - Extend page doesn't fill
I want to fill my index.html with content of the header.html. The index.html shows everything - except the content of the header.html. Why isn't it showing the "Hello World"? On the header.html I also tried to ref to "index.html" or "Immo/private/index.html", but it didn't worked. header.html: {% extends 'private/index.html' %} {% block content %} <h1>fill: Hello World</h1> {% endblock %} index.html: {% load static %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Index-Page</title> </head> <body> <div class="page-header"> <h1><a href="/">Index-Page</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I work with django 2.1 on Visual Studio on windows. -
Retrieve origin IP address of of entity that makes a change to a database - Django
I'm using Heroku, and Django. I want to know how can I retrieve the IP address of the origin IP that makes any database change. I want to add some security measures to a database that will be managed by multiple people through the admin section of a website, and I want to restrict uses of the system to a specific IP address / send alerts if the IP is different. I thought the data would be stored in django sessions but I couldn't find any information about IP addresses. Any other security best practices would be great too. Your help would be much appreciated. -
Django - passing a parameter from page redirect
I just started with Python and Django and want to redirect a user to a home page after successful form-registration with a head-massage changed to "You have successfully registered". My code without changing a massage after redirection is: urls.py: urlpatterns = [ path('', IndexView.as_view(), name = 'index'), path('register/', views.register, name = 'register'), ] views.py: class IndexView(TemplateView): template_name = 'first_ap/index.html' def get_context_data(self, *args, **kwargs): t_user = 'Hello my friend' context = { 'viva':t_user } return context def register(request): if request.method == "POST": form = RegForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.set_password(form.cleaned_data['password']) new_user.save() return redirect('index') else: form = RegForm() return render(request, 'first_ap/register.html', {'form': form}) In html file I put: <h1>{{ viva }}!</h1> How should I modify a code to change a context after redirection from "Hello my friend" to "You have successfully registered"? I tried several options but they all failed. -
How to enable automatic mail sending in the default django admin template submit_line.html
I am in deep trouble and spent almost 3 days in searching for this but not get a actual answer so the problem is I have override my submi_line.html {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" {{ onclick_attrib }}/>{% endif %} {% if show_delete_link %}<p class="deletelink-box"><a href="{% url opts|admin_urlname:'delete' original.pk|admin_urlquote %}" class="deletelink">{% trans "Delete" %}</a></p>{% endif %} {% if show_save_as_new %}<input type="submit" value="{% trans 'Save as new' %}" name="_saveasnew" {{ onclick_attrib }}/>{%endif%} {% if show_save_and_add_another %}<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother" {{onclick_attrib}}/>{% endif %} {% if show_save_and_continue %}<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue" {{ onclick_attrib }}/>{% endif %} </div> If i want to change the name of the buttons then it is working perfect. But i dont know what this{{onclick_attrib}} is doing here .I want If (save,save and continue,save and add another) will be clicked then a automatic email is send to the user in which it is written that your current password is this and you can change your password by clicking on this page.The link must be visible to the email reader so that he can reset his password.MY … -
Cannot run some urls locally on django
I have a django app and I am trying to run it locally. All the other links/urls works well except some. I get this error. I have just cloned this from the master repo, but the production site works very well witouht any errors. Here's the code for marketing.py from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.views.generic import TemplateView from auto_wheedles.tests import auto_wheedle_overview, manual_auto_wheedling, manual_auto_wheedle_reset from wheedle.views import HomeView, ContactView, MissedView, TestEmail, GetThumbnailView from establishment.views import EstablishmentSocialCounter from events.views import EventDetailsRedirect from wheedle.urls import guests, hosts from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^(?P<size>(large|Large|medium|Medium|small|Small))/(? P<path>.*)$', GetThumbnailView.as_view()), url(r'^(?P<social>\w{1,2})/(?P<slug>[^/]*)/$', EstablishmentSocialCounter.as_view(), name='social_counter'), url(r'^$', HomeView.as_view(), name='home'), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^app/', include(guests)), url(r'^host/', include(hosts)), url(r'^auto/', auto_wheedle_overview, name='aw_overview'), url(r'^auto_wheedling/', manual_auto_wheedling), url(r'^reset/', manual_auto_wheedle_reset), url(r'^(public-)?event/(?P<slug>[^/]*)/$', EventDetailsRedirect.as_view(), name='public_event'), url(r'^privacy/$', TemplateView.as_view(template_name="privacy_policy.html"), name='privacy'), url(r'^terms/$', TemplateView.as_view(template_name="terms_of_use.html"), name='terms'), url(r'^contact/$', ContactView.as_view(), name='contact'), url(r'^email/(?P<template>[^/]*)/', TestEmail.as_view()), url(r'^missing/$', MissedView.as_view(), name='missing_object'), url(r'^foodtruck', TemplateView.as_view(template_name='foodtruck.html')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Wagtail import needs publish() to display images
During a data migration to Wagtail, images are being created and added to the article body (as eg. <embed alt="Paralympics. Demotix/Julio Etchart. All rights reserved." embedtype="image" format="fullwidth" id="2453"/>) and are visible in the admin screen but not on the live article. If I click the Publish option in the admin screen, the images then become visible on the live article (along with a publish success message even though it was already live). I would like to run whatever process is run by the Publish button during the article migration (so that images are visible on site), but I can't work out what functions it is running. I have tried a variety of options in the shell, including: Article.save() a = Article.get_revision() a.publish() but those don't seem to work. Any ideas? -
Django - Anyway to call a view function from a button on a template?
I have seen a couple of this same question posted but I am still not understanding how to do this. I have template that displays hyperlinks leading to the actual record to be updated. I want to put a button on the template that just displays the list to be able to create records in a table by looping over each of the records in this "temp" table. The behavior is meant to mimic a Cart on a eCommerce site. That is why I am storing the records in this temp table because when they "Check-out" they will be considered 1 order with multiple lines. Writing the logic in the view isnt the issue, its calling this function when the button is pressed that I am not understanding. Thank you! -
Not seeing my log messages - Django/Apache/mod_wsgi
I've added the following to my views.py logger = logging.getLogger(__name__) However, I'm not seeing any of my log messages in the Apache logs. Here's an example of a log message that I'm expecting to see: try: response.raise_for_status() except requests.exceptions.HTTPError as e: logger.error("get_thumbnails call failed: ", e) httpd.conf # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel debug I'm using the latest versions of both mod_wsgi and Django -
Basic django2 web page
I'm trying to learn django(version 2.1), I thought of creating a webpage which has a text_field(to accept the path of a csv in a local machine) and and button to submit the request. OR even a text field and a button, which prints the text entered in the text box in upper case and something like this. Youtube and other websites are filled with blogging apps, polling apps and some other complex stuff which i couldn't follow. I tried almost 30-40 different application from all over the internet, still didn't able to get the things right. Please please somebody guide me to create one of the above basic stuff else if you have any study material recommendations, will be greatly appreciated! Please don't rush to mark it as a broad post, this might serve as learners guide for newbies like me. -
How does user variable pass to home view template
I currently following a tutorial at https://wsvincent.com/django-allauth-tutorial-custom-user-model/ I look at how they implemented home view. pages/views.py # pages/views.py from django.views.generic import TemplateView class HomePageView(TemplateView): template_name = 'home.html' templates/home.html <!-- templates/home.html --> <h1>Django Login Mega-Tutorial</h1> {% if user.is_authenticated %} <p>Hi {{ user.username }} <p><a href="{% url 'logout' %}">Log out</a></p> {% else %} <p><a href="{% url 'signup' %}">Sign Up</a></p> <p><a href="{% url 'login' %}">Log In </a></p> {% endif %} However, I don't see how user variable is being passed to the home view template (templates/home.html). May I know how that happen? -
Como listar os usuários que são autores de um determinado objeto
Olá, tenho um objeto RespostasEdp, cuja a chave estrangeira é Edp e um usuário podem ter varias RespostasEdp de sua autoria. Porém, ao listar as respostas desejo agrupa-las por usuário. Sabem como posso fazer isso? Tentei a solução abaixo mas não consigo acessar os valores dos usuários. @teacher_required def listarRespostasEDA(request): edpsTodas = Edp.objects.all() title = 'Estruturas Digitais Pedagogicas' template = 'edp/listarEDArespondida.html' edps = list() for edp in edpsTodas: if edp.respostas.all().count() != 0: # if not edp.respostas.none: edps.append(edp) return render(request, template, {'title': title, 'edps': edps}) def listaAlunosResponderamEdp(request, slug): edp = get_object_or_404(Edp, slug=slug) # respostas = RespostaEdp.objects.filter(edp=edp) lista = list() respostas = RespostaEdp.objects.filter(edp=edp).values('aprendiz').distinct().order_by('aprendiz') for r in respostas: for k,v in r.items(): aluno = User.objects.filter(pk=v) lista.append(aluno) print (lista) return render(request, 'edp/teste.html', {'lista':lista}) -
Django Admin MediaOrderConflictWarning
Ever since upgrading to Django 2.1, I am receiving a runtime error /Applications/anaconda3/envs/svod-api-env/lib/python3.6/site-packages/django/forms/widgets.py:126: MediaOrderConflictWarning: Detected duplicate Media files in an opposite order: admin/js/collapse.js admin/js/inlines.js MediaOrderConflictWarning, I think it is because have one collapsed fieldset in my model admin class and my tabular inline classes are to be collapsed as well. If I remove either the fieldset collapse class or the inline collapse classes, the warning goes away, but it seems they cause a warning when they are both used at the same time. The Django 2.1-dev docs say In older versions, forms and formsets combine their Media with widget Media by concatenating the two. The combining now tries to preserve the relative order of elements in each list. MediaOrderConflictWarning is issued if the order can’t be preserved. but I can't find a way to fix the media ordering while keeping all the original collapsed classes. Has anyone else encountered the same problem? @admin.register(User) class UserModelAdmin(UserAdmin, ExportMixin): ... fieldsets = ( ( _('Authentication'), { 'classes': ( 'collapse', ), 'fields': ( 'username', 'password', 'user_permissions', 'groups' ) } ), ( _('Status'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser' ) } ), ... ) inlines = ( DeviceTabularInline, PaymentTabularInline ) class DeviceTabularInline(admin.TabularInline): model = Device … -
DjangoRestFramework - How to update fields in model
I am using Django user model and also extended with my own profile model for some other data.When i want to update user data which is in Profile Model It doesn't get updated because all the user id,username,email,password reside in user model while the fields which are needed to get updated are in profile model.I have used this approach, all it does is takes inputs and displays the response but does not show any change in User Data when viewing it as a whole. models.py class Profile(models.Model): user = models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE) location = models.CharField(max_length=30,blank=True) friends_count = models.PositiveIntegerField(default=0) profile_pic = models.FileField(upload_to='profile_pics/',blank=True,null=True) def natural_key(self): return (self.user.username,) views.py class UserUpdateAPI(generics.GenericAPIView,mixins.UpdateModelMixin): """Update User Profile Data""" permission_classes = (permissions.UpdateOwnProfile,) authentication_classes = (TokenAuthentication,) queryset = Profile.objects.all() serializer_class = ProfileUpdateSerializer def put(self,request,*args,**kwargs): return self.partial_update(request,*args,**kwargs) urls.py url(r'^user-update/(?P<pk>\d+)/$',views.UserUpdateAPI.as_view(),name="user- update"), serializers.py class ProfileUpdateSerializer(serializers.ModelSerializer): """A serializer for updating user data""" class Meta: model = Profile fields = ('location','profile_pic')