Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow CSRF token header in Django CORS sent from axios call
How can I solve this CORS problem for django? I'm doing a POST http call using axios and need to have a CSRF token to do so. In order to do that, I need to pass in a CSRF header axios.post('/test', data, { headers: { 'HTTP_X_CSRFTOKEN': 'X-CSRFToken', } }) .then((res) => { console.log(res) }) .catch((err) => { console.log(err) }) settings.py CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CSRF_COOKIE_NAME = "XSRF-TOKEN" CSRF_HEADER_NAME = ( 'HTTP_X_CSRFTOKEN' ) Error: Request header field xsrfHeaderName is not allowed by Access-Control-Allow-Headers in preflight response. -
Django parameter URLs, how to?
I need to write a search based on the URL like this: Example 1: /ad/state/new-york/borough/queens/tag/expensive/tag/beer/ Example 2: /ad/state/new-york/ Example 3: /ad/state/new-york/tag/beer/ I don't know how to handle this in the "urlpatterns" on the urls.py and how should be my view on views.py Can someone give me some help on this? -
Django: override save method on ModelForm that inherits values from another ModelForm
For convention at my company any validation must be done in the form and not in the view of any Django APP. I've this code that applies to my form, as a regular form. But I've "upgradete" it to be a 'ModelForm' and this code, works but doesn't save the "document" attribute on the 'Nana'. What I'm doing wrong? forms.py class NanaForm(forms.ModelForm): class Meta: model = Nana fields = ['nombre', 'apellido_paterno', 'apellido_materno', 'fecha_de_nacimiento', 'direccion', 'telefono_o_celular', 'genero', 'foto', 'latitud', 'longitud'] widgets = { 'fecha_de_nacimiento': DateInput(), 'latitud': forms.HiddenInput(), 'longitud': forms.HiddenInput() } def clean(self): form_data = self.cleaned_data try: tipo_documento = TipoDocumento.objects.get(form_data['tipo_documento']) if not tipo_documento.validar_documento(form_data['documento']): self._errors["documento"] = ["El documento no cumple el formato."] del form_data['documento'] except ObjectDoesNotExist: self._errors["tipo_documento"] = ["No existe el tipo de documento seleccionado."] del form_data['tipo_documento'] return form_data @transaction.atomic() def save(self): valid_data = self.cleaned_data documento_codigo = valid_data.pop('documento') documento_tipo_id = valid_data.pop('tipo_documento') documento = Documento(codigo=documento_codigo, tipo_documento_id=documento_tipo_id) documento.save() nana = Nana(documento=documento, **valid_data) nana.save() return nana class DocumentoForm(forms.ModelForm): class Meta: model = Documento fields = ['tipo_documento', 'codigo'] models.py class TipoDocumento(models.Model): nombre_corto = models.CharField(blank=False, null=False, max_length=25) nombre_largo = models.CharField(blank=False, null=False, max_length=100) tipo_patron = models.IntegerField(blank=False, null=False, choices=TIPO_PATRON) tipo_contribuyente = models.IntegerField(blank=False, null=False, choices=TIPO_CONTRIBUYENTE) tipo_longitud = models.IntegerField(blank=False, null=False, choices=TIPO_LONGITUD) def __str__(self): return self.nombre_corto -
running pyodbc with Django on Heroku
Has anyone managed to install django-pyodbc-azure on Heroku? I am told by Heroku support that odbc is not supported but that it can be installed via 3rd party buildpacks. I have found a couple but can't get them to work: https://github.com/film42/heroku-buildpack-python-odbc and https://github.com/Yesware/heroku-snowflake-odbc-buildpack Someone out there must be using Django with an Azure db??? -
Django 1.11 - Inline Admin Model - Error: admin.E106
I want to access the Image model in the Art admin page as it's written in the docs but something goes wrong: /gallery/models.py: class Image: name = models.CharField(max_length=256) thumb = models.CharField(max_length=256) product = models.ForeignKey(Art, on_delete=models.CASCADE, related_name='images') /product/admin.py: class ArtImage(admin.TabularInline): model = Image extra = 3 class ArtAdmin(admin.ModelAdmin): inlines = [ArtImage] admin.site.register(Art, ArtAdmin) When I apply the makemigrations command I get SystemCheckError: System check identified some issues: ERRORS: : (admin.E106) The value of 'product.admin.ArtImage.model' must be a Model. What could it be? -
django.db.utils.ProgrammingError: relation "users_user" does not exist
I'm trying to migrate my apps, so this error it's happening "django.db.utils.ProgrammingError: relation "users_user" does not exist". I tried with many ways and this not running. I'm using multi-tenant configuration. Help me please. <pre> My manage.py migrate_schemas --list [standard:public] admin [standard:public] [ ] 0001_initial [standard:public] [ ] 0002_logentry_remove_auto_add [standard:public] [ ] 0003_auto_20171127_1309 [standard:public] auth [standard:public] [X] 0001_initial [standard:public] [X] 0002_alter_permission_name_max_length [standard:public] [X] 0003_alter_user_email_max_length [standard:public] [X] 0004_alter_user_username_opts [standard:public] [X] 0005_alter_user_last_login_null [standard:public] [X] 0006_require_contenttypes_0002 [standard:public] [X] 0007_alter_validators_add_error_messages [standard:public] contenttypes [standard:public] [X] 0001_initial [standard:public] [X] 0002_remove_content_type_name [standard:public] foundation [standard:public] (no migrations) [standard:public] sessions [standard:public] [ ] 0001_initial [standard:public] sites [standard:public] [X] 0001_initial [standard:public] [X] 0002_alter_domain_unique [standard:public] tenants [standard:public] (no migrations) [standard:public] users [standard:public] [X] 0001_initial Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site- packages\tenant_schemas\management\commands\migrate_schemas.py", line 53, in handle executor.run_migrations(tenants=tenants) File "C:\Python27\lib\site- packages\tenant_schemas\migration_executors\base.py", line 57, in run_migrations if public_schema_name in tenants: TypeError: argument of type 'TenantQueryset' is not iterable </pre> -
Persisting chosen value(s) from a Radio Button in an Django Application
In an Django Application, how can I persist information chosen from two options; two Radio Buttons at the Form - but with the second one offering to the user the ability to type in text boxes two values, 'min' and 'max'? For example: Choose the Temperature: o A fixed-value at _____ or o Values from _____ to _____ How can I implement this? Thanks. -
Django: How can i add recipes to a shopping list model
In my app I have a Recipe model of which I want to add recipes to a shopping list model. However, I don't know how to add an object from one model to another. How do I go about this? (This is my first question so I'm still getting the hang of this, sorry.) -
Websocket timeout in Django Channels / Daphne
Short question version: what am I doing wrong in my Daphne config, or my Consumer code, or my client code? channels==1.1.8 daphne==1.3.0 Django==1.11.7 Details below: I am trying to keep a persistent Websocket connection open using Django Channels and the Daphne interface server. I am launching Daphne with mostly default arguments: daphne -b 0.0.0.0 -p 8000 my_app.asgi:channel_layer. I am seeing the connections closing after some idle time in the browser, shortly over 20 seconds. The CloseEvent sent with the disconnect has a code value of 1006 (Abnormal Closure), no reason set, and wasClean set to false. This should be the server closing the connection without sending an explicit close frame. The Daphne CLI has --ping-interval and --ping-timeout flags with default values of 20 and 30 seconds, respectively. This is documented as "The number of seconds a WebSocket must be idle before a keepalive ping is sent," for the former, and "The number of seconds before a WebSocket is closed if no response to a keepalive ping," for the latter. I read this as Daphne will wait until a WebSocket has been idle for 20 seconds to send a ping, and will close the Websocket if no response is received 30 … -
Using django settings as argument defauts
Is there a reason not to use django settings as default arguments in functions like so: from django.conf import settings def my_function(some_arg=settings.SOME_ARG_DEFAULT): ... the alternative is setting the argument if it is None as is suggested for mutable defaults (such as lists or dicts): from django.conf import settings def my_function(some_arg=None): if some_arg is None: some_arg = settings.SOME_ARG_DEFAULT ... Could there be some unintended side effects from the first option? -
Wagtail: Is there a way to get all pages a snippet is used on?
I am using Wagtail 1.7 and need to retrieve a list of all the pages a snippet is used on. I looked at get_usage, get_usage_url but that didn't seem to be quite what I needed. I am using the sites framework with wagtail and need show different search results based on which site you are on (using elasticsearch). The snippets are the only thing fouling that up at the moment. -
Validation with cleaned_data()
I'd like to ask you if you can briefly and in plain English explain to me how cleaned_data() function validates data ? Reason for asking is that I'm designing a web app powered by Django and initially I thought cleaned_data() is smart enough to block user's input that contains potentially harmful characters. Such as # ; < > and alike. Characters that can be used for SQL injection attacks. To my surprise, when I deliberately slipped few of those characters into form field, the input made it to database. I was quite shocked. So then ... what the cleaned_data() function is good for ? I read about this function in docs, however I couldn't find necessarily answer to this. -
User Model flags a User based on another models table
I'm trying to solve a problem where a user logs in with their windows NT login and if they fall within a list of NT names in another table in the model / existing database table I'd like to flag them as a CFO by placing a 1 in the is_cfo field. Is it possible to do this way if not how would you solve this problem? The list of NTNames would be in the following model: class QvDatareducecfo(models.Model): cfo_fname = models.CharField(db_column='CFO_FName', max_length=100, blank=True, null=True) # Field name made lowercase. cfo_lname = models.CharField(db_column='CFO_LName', max_length=100, blank=True, null=True) # Field name made lowercase. cfo_ntname = models.CharField(db_column='CFO_NTName',primary_key=True, serialize=False, max_length=7) # Field name made lowercase. cfo_type = models.IntegerField(db_column='CFO_Type', blank=True, null=True) class Meta: managed = False db_table = 'QV_DataReduceCFO' My User model uses LDAP authentication and pulls the Users information from AD into the following model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_cfo = models.BooleanField(default=False) facility = models.CharField(max_length=140) officename = models.CharField(max_length=100) jobdescription = models.CharField(max_length=140) positioncode = models.CharField(max_length = 100) positiondescription = models.CharField(max_length=140) coid = models.CharField(max_length=5) streetaddress = models.CharField(max_length=140) title … -
Class-based views DetailView+FormView with comments
I have a few questions. It's my code: class DetailPost(DetailView, FormView): model = Post template_name = 'blog/post_detail.html' form_class = CommentForm def get_context_data(self, *args, **kwargs): context = super(DetailPost, self).get_context_data(**kwargs) context['form'] = self.get_form() context['comments'] = Comment.objects.all() if self.request.user.is_authenticated else Comment.objects.filter(visible_comment=True) return context def post(self, request, *args, **kwargs): pk = self.kwargs.get('pk') if self.request.POST.get('change_visible_comment'): comment_pk = self.request.POST.get('change_visible_comment') comment = Comment.objects.get(pk=comment_pk) comment.visible() return redirect('post_details', pk = pk) form = CommentForm(self.request.POST) post= get_object_or_404(Post, pk=self.kwargs.get('pk')) if form.is_valid(): comment = form.save(commit=False) comment.post= post comment.save() return redirect('post_details', pk = pk) <form method="POST" action="{% url 'post_details' pk=post.pk %}">{% csrf_token %} <input type="hidden" name="change_visible_comment" value="{{ comment.pk }}" /> <button>Change Visible</button> </form> As you can see this is one View with post detail + comment form + comments + comment visible button which send POST 'change_visible_comment', so I have few questions: Is it good when I code "if self.request.POST.get('pk')" or other such code in post method when I want handle POST? Are you know any other, better ways to make such a common view with detail + form? Sorry if my english or code hurts you, but I'm learning django for a few days. -
Django URL to User's Posts
I have a Member Model and a Blog Model. My blog model is called MyPosts. And MyPosts user field is FK to Member. To view a detail page of a user I have got the url type below: url(r'member-detail/(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$', views.MemberDetailView.as_view(), name='member-detail'), And for blog posts I have the following: url(r'my-posts/$',views.postlistall.as_view(), name='my-posts'), Now, how can I arrange my-posts url to view a user's posts? I mean the url for a member detail view is: http : //127.0.0.1:8000/directory/member-detail/12/michael/ However my post link is: http : //127.0.0.1:8000/directory/my-posts/ How can I convert it into http : //127.0.0.1:8000/directory/12/michael/my-posts/ or something like this which might be the best? Plus, They have two different views and templates. How can I show the last 5 posts of the user on his/her detail page. I fail in combining the 2 views. -
FB login redirect error
I am getting this error when Facebook login redirecting on Django: unsupported operand type(s) for +: 'NoneType' and 'int'. How can I solve it? -
URL not matching any url pattern in Django
I am learning Django by trying to create a blog. I wanted to add a comment section in the blog post. Now I am getting a no match error with the regex I used in my URL Pattern when I click submit in my comment form. But when I try the regex on pythex it seems to match the resultant url that gets redirected after I click the submit button. This is my HTML form: <form id ="post_form" method = "post" action = "add_comment/"> {{ commentform | as_bootstrap }} <input type = "submit" name = "submit" value = "Create Comment"> This is the URL pattern: from django.conf.urls import url, include from blog import views urlpatterns = [ url(r'^$', views.index, name = 'index'), url(r'^add_post/', views.add_post, name = 'add_post'), url(r'^(?P<slug>[\w|\-]+)/$', views.post, name = 'post'), url(r'^(?P<slug>[\w|\-]+])/add_comment/$', views.add_comment, name = 'add_comment') ] This is the error message on django: Page not found (404) Request Method: POST Request URL: http://localhost:8000/blog/title-3/add_comment/ Using the URLconf defined in bloggy_project.urls, Django tried these URL patterns, in this order: ^admin/ ^blog/ ^$ [name='index'] ^blog/ ^add_post/ [name='add_post'] ^blog/ ^(?P<slug>[\w|\-]+)/$ [name='post'] ^blog/ ^(?P<slug>[\w|\-]+])/add_comment/$ [name='add_comment'] ^media/(?P<path>.*)$ The current URL, blog/title-3/add_comment/, didn't match any of these. You're seeing this error because you have DEBUG … -
How to use django ORM to join using prefetch_related
How to use django ORM to join using prefetch_related. A few days I'm trying to use django's ORM for simple relationship queries. I used examples from the documentation, but I did not succeed. I'm missing something I still do not know. There is a possibility of using raw SQL, but I would like to know and know how to simplify code with Django. Try to make it cleaner and readable. I thank you for your attention. Model class Survey(models.Model): name = models.CharField(max_length=100) created_at = models.DateField() user = models.ForeignKey(User) def __str__(self): return self.nome class Session(models.Model): title = models.CharField(max_length=100) created_at = models.DateField() survey = models.ForeignKey(Survey, on_delete=models.CASCADE) def __str__(self): return self.titulo class Quetion(models.Model): quetion = models.TextField() type = models.CharField(max_length=10) created_at = models.DateField() session = models.ForeignKey(Session, on_delete=models.CASCADE) def __str__(self): return self.quetion class Option(models.Model): option = models.TextField() created_at = models.DateField() quetions = models.ManyToManyField(Quetion) def __str__(self): return self.name expected output { survey: "Name", session: [ { title: "Session 01" questions: [ { question: "How do you... 01 ?", options: [ { option: "Option 01"}, { option: "Option 02"} ] }, { question: "How do you... 02 ?", options: [ { option: "Option 01"}, { option: "Option 02"} ] } ] }, { title: "Session 02" questions: … -
Django test runner failing with "relation does not exist" error
I'm seeing an error when running my tests, i.e. $ ./manage.py test --settings=my.test.settings django.db.utils.ProgrammingError: relation "<relation name>" does not exist This is after running ./manage.py makemigrations && migrate. -
Djano issues : Django ManagementForm data is missing or has been tampered with
I have been going through every question ever asked in regards to this issue but can't seem to find the solution. I am trying to allow a user to submit multiple objects and save to the data base using a formset with 2 foreignkeys. I can get the Forms to save that data into the database but cannot get the forms in the formset to save because of the ManagementForm error. The issue is not that I don't have it in the HTML. (check the HMTL code below.) I also have a prefix set for the formset. I don't know if i need to create a custom form and formset instead of using model's. Maybe I need to Validate the information in formsets better. The error I get is: /home/aking/signatureProject/signatureApp/views.py in signatures if formset.is_valid(): ... Variable Value DD <DDForm bound=True, valid=True, fields=(downdraft_id)> PR <PRForm bound=True, valid=True, fields=(report_id;report_desc)> SignatureFormSet <class 'django.forms.formsets.SigFormFormSet'> formset <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> request <WSGIRequest: POST '/signatureApp/signatures/'> views.py /usr/lib64/python2.7/site-packages/django/forms/formsets.py in is_valid forms_valid True self <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> /usr/lib64/python2.7/site-packages/django/forms/formsets.py in errors self.full_clean() self <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> /usr/lib64/python2.7/site-packages/django/forms/formsets.py in full_clean for i in range(0, self.total_form_count()): empty_forms_count 0 self <django.forms.formsets.SigFormFormSet object at 0x7f44601a4e10> /usr/lib64/python2.7/site-packages/django/forms/formsets.py in total_form_count return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max) … -
Unable to access MEDIA_ROOT in python file
I'm getting the following error 'function' object has no attribute 'MEDIA_ROOT' My settings.py file has the following for MEDIA_ROOT. PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(PROJECT_PATH, '/Client/media/') MEDIA_URL = '/Client/media/' I'm running the following code inside my views.py to see if a directory already exists. If it does not then create it. from django.conf import settings def uploadphoto(request, clientid): path = settings.MEDIA_ROOT + '/Orders/' + str(orderid) if not os.path.exists(path): os.makedirs(path) I have an old project using the same version of Django (1.10.2) that I use the same method and it works just fine. Though for this project I'm unable to run this if statement. Any idea what I'm missing? I've gone through my old project and from what I can tell everything is the same. -
How is "context" variable getting the data without applying query-set to it?
views.py from django.views.generic import DetailView from restaurants.models import Restaurant class RestaurantDetailView(DetailView): queryset = Restaurant.objects.all() def get_context_data(self, *args, **kwargs): context = super(RestaurantDetailView, self).get_context_data(*args, **kwargs) print(context) print(kwargs) return context urls.py urlpatterns = [ url(r'^restaurants/(?P<pk>\w+)/$', RestaurantDetailView.as_view()), ] Here, how is "context" variable getting the values from queryset corresponding to the key "pk" that is receives in "kwargs"? -
HTML: I need to do a sort of booking system
In the image (sorry for the bad drawing), I’m showing you what I need to do. I just drew a part of the front-end (notice the red lines as separators) but it’s a 24 hour system and 1 to N. Front-end of booking system Django gives all the different OBJ (NN) with an initial hour, final hour and name. Notice that the initial or final time can be 02:31. Besides, the number of columns(N) (N can be 1:99). The approach I used was to generate an HTML table and cards with absolute position for the OBJ (rectangle), but I have a problem, which is that I don’t know the length of the header cells, so I can’t automatically locate the cards in the position I need. My questions are: Is there a better way to do what I’m trying to do? (I don’t know about front-end). How can the position of the header cell be known automatically without setting a fixed value or without losing bootstrap container? Thank you. -
A general query about django / javascript patterns and how to best organize/encapsualte
I have been warned that this is subjective and likely to be closed, but seems an essential question that I haven't seen addressed. I am currently coding webapps in django and using a bit of javascript to so this and that. Naturally, I sometimes want my javascript apps from knowing the context of my Django template, so the way I've been doing it is hardcoding the js into the .html file. Example <script> var my_var = {{ my_var_from_context }} Clearly this is ugly as all hell as it forces me to keep my javascript code inside of the .html file. I'd like to make my .js file separate and load it. Clearly thee are some options like write a function that takes arguments that can be captured in the template then passed. e.g. var my_var = {{ my_django_var }} myFunctionFromScript(my_var) Is this the best way to be doing this? Is there a better pattern? What are others doing? Thanks for your help. -Joe -
Django bulk update for many to many relationship
I have and Event and EventCategory model with a many-to-many relationship. There are 2 event categories - past (id of 2) and future (ID of 1). I want to find all Events in the future via models = Event.objects.filter(categories__slug='future') And then update them so they are all in the past. What's the most efficient way to update my related table with the new ID? Many thanks