Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django class based views and bulk importing data into models
I've got a toy Django (1.11) app where I've modelled a Family and a Person - there is a one-to-many relationship here: a Family can relate to many Person objects. Using class based views, I've got simple CRUD on individual instances of each. However, I'm stuck trying to implement the capability of importing a CSV file of Person records into an existing Family instance. My view class should represent a single instance of Family, so I figured an UpdateView would be the right approach, along with a custom Form that only shows a file input control. However, it's not clear whether its sensible for my view to be an UpdateView (I'm not really updating the Family, I'm just creating related Persons and attaching them), or what class my Form should be. Should the logic to parse the CSV and create the Person objects belong to the Form class or the View class? -
Django-pipeline doesn't find file or directyory when running collecstatic
I've installed django-pipeline package and it works perfectly on my local computer. The problem happens when I run collectstatic on production and I get this error: raise CompressorError(stderr) pipeline.exceptions.CompressorError: b'/usr/bin/env: \xe2\x80\x98yuglify\xe2\x80\x99: No such file or directory\n' I've also tried to use a different compressor and it does no work either. Here is my settings: STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) STATIC_URL = '/static/' STATIC_ROOT = '/home/user/app/static' MEDIA_ROOT = '/home/user/app/src/media' MEDIA_URL = '/media/' PIPELINE = { 'PIPELINE_ENABLED': True, 'STYLESHEETS': { 'main': { 'source_filenames': ( '/home/user/app/static/css/main.css', ), 'output_filename': 'css/main.css', }, }, 'JAVASCRIPT': { 'main': { 'source_filenames': ( '/home/user/app/static/js/main.js', ), 'output_filename': 'js/main.js', } } } PIPELINE['CSS_COMPRESSOR'] = 'pipeline.compressors.yui.YUICompressor' PIPELINE['JS_COMPRESSOR'] = 'pipeline.compressors.yui.YUICompressor' What am I doing wrong? Thank you so much! -
Using Axios how to send username in GET request
React-Django application. User signs in by providing username and password through Axios PUT, if correct JWT and username is returned, both are stored in sessionStorage. User is then automatically routed to /home which should populate with information specific to the user. /home has componentWillMount() that is supposed to GET via Axios the content for /home from the database. Some is static and some is relevant to the user, for example first_name. I'm trying to send the username along with the JWT to retrieve this information but not sure how to. This is what I have that is working in retrieving static content like the welcome message. Just want to send username along to so I can add logic server-side to retrieve information for this user and send back in the response. import axios from 'axios'; import { push } from 'react-router-redux'; import { ROOT_URL } from '../../config/config.json'; // Establish the different types export const WELCOME_MESSAGE = 'welcome_message'; export function getWelcome() { return function(dispatch) { axios .get( `${ROOT_URL}/api/home/`, { headers: { 'Content-Type': 'application/json', 'Authorization': 'JWT ' + sessionStorage.getItem('token') } } ) .then(response => { dispatch({ type: WELCOME_MESSAGE, payload: response.data }); }) .catch(error => { console.log("Broke"); }); } } Worst case, I … -
Django models ManyToMany relations mechanics
I need to create Profile model and Project model and don't really understand ManyToMany field mechanics. Now I've got: class Project(models.Model): title = models.CharField(max_length=20, unique=True) ... class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) projects = models.ManyToManyField(Project, related_name='profiles') ... Could I now call all profiles connected with project using project.profiles and how to add profiles field into Project admin form? I've tried to find some examples but not found any. -
How to join models in Python djangorestframework
I am trying to joint two models in django-rest-framework. My code isn't throwing any error but also it isn't showing other model fields that need to be joined. Below is my code snippet: class CompaniesSerializer(serializers.ModelSerializer): class Meta: model = Companies fields = ('id', 'title', 'category') class JobhistorySerializer(serializers.ModelSerializer): companies = CompaniesSerializer(many=True,read_only=True) class Meta: model = Jobhistory fields = ('id', 'title', 'company_id', 'companies') Thanks in advance. Any help will be appreciated. -
Pass user's primary key (pk) from previous page to current page
I'm building a review page, where an annoymous user leaves a review on a user's page (my user is called Agent). The Review model has an agent field, specifying a ForeignKey relationship with Agent. urls url(r'^(?P<pk>\d+)/review/$', views.leave_review, name='leave_review'), HTML code to get to the leave_review page: <form action="{% url 'leave_review' pk=agent.pk %}" method="post"> {% csrf_token %} <button class="button3"><span>Leave review</span></button> </form> Leave review views.py def leave_review(request, pk): if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): form.agent = Agent.objects.get(pk=pk) form.save() return redirect('review_success.html') else: form = ReviewForm() return render(request, 'leave_review.html', {'form': form}) models.py class Review(models.Model): # ... Other fields agent = models.ForeignKey(Agent, on_delete=models.CASCADE) def save(self, *args, **kwargs): if self.agent is None: # Set default reference self.agent = Agent.objects.get(id=1) super(Review, self).save(*args, **kwargs) I'm currently getting a ValueError, Cannot assign "''": "Review.agent" must be a "Agent" instance. I believe I specified the 'pk' correctly in this case,but it is not being picked up. What's wrong here? -
Callback buttons trouble
Heey guys! I have some problem. I write bot for telegram with telebot and use for this mission Django . And now I was destroy my mind :( this is my views.py code: i = 0 keyboard = telebot.types.InlineKeyboardMarkup() for fish in Calculator.objects.all(): keyboard.add( telebot.types.InlineKeyboardButton(text=fish.NameFishRus, callback_data='Lfish' + str(fish.IDfish))) bot.send_message(chat_id, mes, reply_markup=keyboard) This is callback button. Buuuuut, when i run my bot i see next : screen When i click in buttons, they don`t response me :( Heelp pls! P.S i can not attach tag telebot -
python-social-auth password change
I am working on Django webapp and I use python-social-auth to authenticate with Google account. Everything is working well (registration, login, logout) but there is a problem with password change. If the logged-in user changes his password (through Google account settings) django session is still valid and user can call "login_required" methods. I would expect that session is no more valid (like it is in simple Django auth system) and user should be prompted to login again. I've tried to find solution using Google and official python-social-auth documentation but I haven't found anything. Am I doing something wrong or it is my responsibility to check session validity each time? This is part of my "settings.py": AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', ) SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'approval_prompt': 'auto', } SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' thanks for answers. -
"TypeError: an integer is required (got type str)" when applying migrations
After adding some models, I used makemigrations to generate a migration : # -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-10 18:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): dependencies = [ ('restaurants', '0011_auto_20171024_1428'), ('shop', '0003_auto_20171110_1505'), ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('email', models.CharField(max_length=255, unique=True)), ('newsletter', models.BooleanField(default=False)), ('key', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='clé')), ], ), migrations.CreateModel( name='Order', fields=[ ('number_of_guests', models.PositiveSmallIntegerField()), ('key', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='clé')), ('date_created', models.DateTimeField(auto_now_add=True)), ('date_changed', models.DateTimeField(auto_now=True)), ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shop.Customer')), ('deal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='restaurants.Deal')), ], ), migrations.AddField( model_name='payment', name='date_created', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), migrations.AddField( model_name='payment', name='stripe_token', field=models.CharField(default=django.utils.timezone.now, max_length=5000), preserve_default=False, ), migrations.AddField( model_name='payment', name='order', field=models.ForeignKey(default=django.utils.timezone.now, on_delete=django.db.models.deletion.CASCADE, to='shop.Order'), preserve_default=False, ), ] This seems fine, but when I run the migration, it fails with the following traceback : Applying shop.0004_auto_20171110_1910...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "{virtualenv}\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "{virtualenv}\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "{virtualenv}\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "{virtualenv}\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "{virtualenv}\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "{virtualenv}\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "{virtualenv}\lib\site-packages\django\db\migrations\executor.py", line 145, … -
Django - pass parameters into url after render()
I'm trying to use Google's Custom Search Engine product to display results from a query on a page for a personal web app. I'm on Python/Django. How CSE is working is that it takes parameters from the URL as search terms: i.e., www.mydomain.com/results.html?q=hello+world would return results for a "hello world" query on the page. You put some JS code they give you on your page, so it's a bit of a black box. However, with URL routing and render() on Django, I'm guessing the basics is that www.mydomain.com/results gets routed to a views.results call which renders results.html as www.mydomain.com/results What is the best-practice for submitting a query through a form, and passing it to www.mydomain.com/results.html?q=hello+world instead of redirecting to www.mydomain.com/results and having Django render the results/html file? Sorry, I'm relatively new. I can try to piece things together, but I feel there has got to be a very efficient way of handling this situation. -
Django ALLOWED_HOSTS vs CORS(django-cors-headers)
What is the difference between ALLOWED_HOSTS and CORS. If I have defined ALLOWED_HOSTS do I need to define also CORS? I am not using django templates. Also do I have the possibility to define those two dynamically?(I think not) -
Django, React, Redux: Serving up images
I'm using a React/Redux frontend and a Django backend for a little project. I'm not using anything but the standard Django server for development. I'm trying to add an image field to an already existing UserProfile model. Currently I've got everything working except that Django won't properly serve up my images to either to the main React site or the admin site. When I either attempt to navigate to the url in question or use the Python requests library to directly request the media, the response is of type 'text/html'. Currently my model has the following field: models.py class UserProfile(models.Model): ... ... profile_image = models.ImageField(upload_to='path_to_media') project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/account/', include('account.urls')), url(r'^api/post/', include('post.urls')), url(r'.*', views.root, name='root') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'nattr'), ) account urls.py urlpatterns = ( ..., url(r'^edit_profile/(?P<user_id>[^/]+)/$', views.edit_profile, name='edit_profile'), ) account views.py def edit_profile(request, user_id): try: user = User.objects.get(pk=user_id) form = UserProfileForm(request.POST, request.FILES, instance=user.profile, user=request.user) valid = form.is_valid() if valid: profile = form.save() return JsonResponse(profile.to_user()) else: return JsonResponse({'errors': form.errors}, status=400) except User.DoesNotExist: return JsonResponse({'errors': 'cannot find user with that id'}, status=400) What am I doing wrong? I've assigned my media_url … -
Delete a from from a formset with jquery
I am trying to create a dynamic Django formset, where a user can add or delete forms from the formset. Currently I can successfully add a form but I am struggling to get the delete button to successfully delete a form. My most successful attempt actually did delete but not just the form I wanted to delete but all the forms in the formset. I am currently adding forms by adding an empty-form (provided by the formset) when a user presses the add button. Here is my current template: {% block content %} <div> <h1 class="text-center">Create New Activity</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <div id="formset"> {{ activitykeycharacteristics_formset.management_form }} {% for form in activitykeycharacteristics_formset.forms %} <div id="{{ activitykeycharacteristics_formset.prefix }}-form"> {{ form|crispy }} </div> <div id="form-controls"> <button type="button" class="btn btn-primary" id="add-form"><i class="fa fa-plus"></i></button> </div> <div id="empty-form" style="display: none;"> {{ activitykeycharacteristics_formset.empty_form|crispy }} <button type="button" class="btn btn-danger" id="delete-form"><i class="fa fa-minus"></i></button> <hr> </div> {% endfor %} </div> <hr> <button class="primaryAction btn btn-primary pull-right ml-1" type="submit">{% trans "Submit" %}</button> <a class="btn btn-secondary pull-right" href="{{ request.META.HTTP_REFERER }}" role="button">{% trans "Cancel" %}</a> </form> </div> <div class="col"></div> </div> </div> {% endblock content %} {% block javascript %} <script … -
Django pass post form data to another view
Test model have name and result fields. I get name from user, and call a function (a function or b function) to get tests result. but the function takes too long to finish so I want to start it after redirect /dashboard and while its working populate synchronously some pie chart etc. I cannot save test form with empty fields. how can i pass post fields to dashboard view? Thanks for your help. my view is something like : def aview(requests): if request.method == 'POST': form = MyForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] test = Test(name=name) test.save() #this gives error IntegrityError: null value in column "result_id" violates not-null constraint return HttpResponseRedirect('dash') else: form = MyForm() return render(request, 'a.html', {'form': form}) def bview(requests): if request.method == 'POST': form = MyForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] test = Test(name=name) test.save() return HttpResponseRedirect('dash') else: form = MyForm() return render(request, 'b.html', {'form': form}) def dashboard(request): referer = request.META.get('HTTP_REFERER') if referer.split("/")[-1] == "a": functiona(name) elif referer.split("/")[-1] == "b": functionb(name) -
Django admin :: I want to keep last selected value on adding another item
Context in django administration site I am adding a new item in a model via add button when the form is displayed, I have a dropDown with some options to choose, I choose option B and I fill other fields to complete the form I click on button save and add another When the new "add form view" is displayed I want my dropdown to set on the last choice (B option) I selected before What is your suggestion to implement that as simple is possible? Thank you -
Setting regex pattern for mongoengine 0.9.0 StringField
I use python 2.7.12 with pymongo 2.8.1, django 1.11.7, mongoengine 0.9.0 and mongodb 3.4.10. I am creating a custom user model which inserts documents in a regular mongodb collection. I inherited the 'Document' class from mongoengine to create the string password field. I've been trying to create a regex pattern for the following conditions: Length: 8-25 characters At least 1 uppercase letter At least 1 lowercase letter At least 1 number At least 1 special character I tried using re.compile() in the following way: import re regexp = re.compile('[A-Za-z0-9@#$%^&+=]', max_length=25, min_length=8) password = StringField(regex=regexp) I sent HTTP POST requests with invalid passwords and it only throws an error when the length is lesser than 8 or greater than 25, otherwise they pass. I'm new to mongoengine and I'm not really sure what kind of input the regex parameter takes, neither have I been able to find examples for StringField. So what am I doing wrong? -
Django Autovalidation mixin does not work with Decimal
Following a well know pattern in Django, I created a mixin to ensure full_clean() is called whenever the save() method is triggered. class AutoValidable(models.Model): """ Will force the validation process on save. """ def save(self, *args, **kwargs): self.full_clean() super(AutoValidable, self).save(*args, **kwargs) class Meta: abstract = True Then, I use it in this class: class TaxRate(AutoValidable, models.Model): percentage = models.DecimalField( unique=True, max_digits=4, decimal_places=3, validators=[MinValueValidator(0), MaxValueValidator(1)]) However, creating a TaxRate object raise an Error: >>> TaxRate.objects.create(percentage=0.055) django.core.exceptions.ValidationError: {'percentage': ["Assurez-vous qu'il n'y a pas plus de 4 chiffres au total."]} If I remove the autoValidable class, no problem. -
How to change the form of GCBV?
I have GCBV @method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post fields = ('message', ) template_name = 'edit_post.html' pk_url_kwarg = 'post_pk' context_object_name = 'post' def get_queryset(self): queryset = super(PostUpdateView, self).get_queryset() return queryset.filter(created_by=self.request.user) def form_valid(self, form): post = form.save(commit=False) post.updated_by = self.request.user post.updated_at = timezone.now() post.save() return redirect('topic_posts', pk=post.topic.board.pk, topic_pk=post.topic.pk) I need to add pagedown widget to the form, where cad I add it? I know how to do it with FBV but with GCBV we dont define the form which we need, How can I define and change it? -
The difference in functions of `**kwargs` and `**initkwargs`
In Django's source code, there are **kwargs and **initkwargs. django/base.py at master · django/django class View: def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value) and @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) What's difference of them in usage? -
Fill Django CreateView form with read only foreignKey value
When showing a CreateView form I would like to fill a foreignKey value using data from the logged in user. I want this to be read only. My models are: # User profile info class Profile(models.Model): # Relationship Fields user = models.OneToOneField(User, on_delete=models.CASCADE) school = models.ForeignKey('eduly.School', default=1) notes = models.TextField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class School(models.Model): # Fields name = models.CharField(max_length=255) address = models.TextField(max_length=500, blank=True) email = models.CharField(max_length=30) phone = models.CharField(max_length=15) contactName = models.CharField(max_length=30) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def __str__(self): return self.name def get_absolute_url(self): return reverse('eduly_school_detail', args=(self.slug,)) def get_update_url(self): return reverse('eduly_school_update', args=(self.slug,)) class Teacher(models.Model): SCHOOL_ADMIN = 0 CLASS_ADMIN = 1 TASK_ADMIN = 2 ROLES = { (SCHOOL_ADMIN, "School administrator"), (CLASS_ADMIN, "Class administrator"), (TASK_ADMIN, "Task administrator") } # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) email = models.CharField(max_length=30) roles = models.IntegerField("Role", choices=ROLES, default=1) # Relationship Fields school = models.ForeignKey('eduly.School', ) class Meta: ordering = ('-created',) def __str__(self): return self.name def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('eduly_teacher_detail', … -
Why django models changes column to INT automatically
This is my models file: class BC_list(models.Model): Bc_id = models.CharField(max_length=25, verbose_name="BC ID") def __unicode__(self): return str(self.Bc_id) class cdList(models.Model): BC = models.ForeignKey( BC_list ) ProcessName = models.CharField(max_length=25, verbose_name="ProcessName") def __unicode__(self): return str(self.BC)+'-'+str(self.ProcessName) And can anyone tell me why the BC column is a INT instead of Varchar ? As you can see, Bc_is is a charfield. I don't understand it, Thanks in advance, Dawid -
Doesn't Nginx support Django admin static files
My django site user-end is running good with the static files but don't know why all the admin panel static files is not working. While it's working normally but not with linux any idea ?? nginx .conf file upstream sample_project_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/me/SPEnv/run/gunicorn.sock fail_timeout=0; } server { listen 800; server_name <your domain name>; client_max_body_size 4G; access_log /home/me/logs/nginx-access.log; error_log /home/me/logs/nginx-error.log; location /static { root /home/me/DjangoProjects/SP/SP; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; # set "proxy_buffering off" *only* for Rainbows! when doing # Comet/long-poll stuff. … -
Deploy Heroku app with package that is not available in pip
I am trying to deploy a new version of my Django application to Heroku, but I am using a package that is not available in pip. So when I put this package in the requirements.txt the deploy fails with the message that this requirement cannot be found by pip (logically). Then I tried to push the directory containing the package to the heroku git repo and istalled the package using the heroku bash and the setup.py file (and removed it from the requirements file). This installation was successful, but when I deploy the application I get the error that this package cannot be found. So my question is: How to properly use python packages not available in pip on Heroku? -
Django: handle CSRF error as form error
When a Django form has a CSRF error, it redirects to a 403 page. Is there any way to handle that as a form error (i.e. showing an error message in the form page) instead of redirecting? -
Load pdf on template django with security
How to load a pdf file that is in a private directory in an embed tag that is not accessible by url ??? <div class="object-file"> <embed class="pdf403" src="{{ object.file.url }}#toolbar=0&navpanes=0&scrollbar=0" style="width:100%;" height="780" Enable comment_users = CourseEntry.list_course_progress_users( ContextMenu='0' type='application/pdf'> </div>