Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Model Inheritance OR Interface to share functionalities between different models?
In my application, I have two models: A: websites created by my company B: websites created by 3rd party My goal is to figure out whether A and B should share a common ancestor via the inherited model pattern or they should implement the same interface. Both A and B has a series of celery tasks defined for installing a plugin. A: CreateAWS, ConfigureCF, ExposeWP B: CreateAWS, SetupNode, ManualVerify, PurchaseDomain A and B implements implements their "ShutdownView" quite differently: A: looks up the AWS ID and shuts down the instance B: looks up the 3rd party associated with this site and sends an automated email. We are planning to add the following functionalities to both A and B: Analytics: Figure out total visitors, revenue for each A and B, etc Big Data: Analyze ROI for A and B with respective to their ad spend, etc As you can see, both A and B are somewhat similar. They each implement a similar interface. I want to build functionalities that works on A and B without necessarily forcing them to inherit from the same ancestor. Are there concepts such as interface defined in Django where I can delegate the implementations of each … -
django clean method on model form
I've only used the out-of-the box Django forms API. I'm now trying to validate form field data on a django model form - update_profile. My model contains the validators, where (and why) do I perform a clean or save in order to provide field level messaging for the end-user? Currently, my error dict is empty. class CustomUser(AbstractBaseUser): email = models.EmailField(_('email'), max_length=254, unique=True) username = models.CharField(_('username'),max_length=15, unique=True, validators=[RegexValidator('^[_a-z0-9]+$', message= '15 characters max. Username must be a-z(lowercase), 0-9, can contain underscore', code='invalid_username')]) about_me = models.CharField(_('about me'),max_length=140) avatar = models.ImageField(upload_to='avatars/', blank=True, null=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=50, blank=True) phone_regex = RegexValidator(regex='^\+?1?\d{9,15}$', message='Phone number must be between 9 and 15 digits') phone_number = models.CharField(_('phone_number'),max_length=15, blank=True, validators=[phone_regex]) is_active = models.BooleanField(_('active'), default=False) is_staff = models.BooleanField(_('staff'), default=False) views.py def update_profile(request): user=request.user if user.is_authenticated == True: if request.method == 'POST': form = CustomUserChangeForm(request.POST, instance=user) if form.is_valid(): form.save() messages.success(request, 'Your profile was successfully updated.') return redirect('update profile') else: messages.error(request, "Please correct the error below.") form = CustomUserChangeForm(instance=user) return render(request, 'profile.html', {'form': form}) forms.py class CustomUserChangeForm(forms.ModelForm): class Meta: model = CustomUser fields = ('email', 'first_name', 'last_name', 'about_me','phone_number') -
Placeholders Django Login page
<form method="POST" class="container is-responsive"> {% csrf_token %} <h1><font color="black">Log in</font></h1> <label for="username"><font color="black"><b>Email</b></font></label> <p><font color="black"> {{ form.username}}</font></p> <label for="psw"><font color="black">Password</font></label> <p><font color="black">{{ form.password}}</font></p> <button type="submit" class="btn">Login</button> {% if form.errors %} <p><font color="red"><b>Invalid username or password.</b> Please try again.</font></p> {% endif %} </form> need to add place holders for the default form.username and form.password fields -
Basic Django Help - Admin Static CSS 404 error
New to Django / Python. Installation (on Dreamhost) 'worked', see http://demo.theaipiphany.com/admin/ The static files have the proper path, they 'exist' but are coming up as 404 errors. http://demo.theaipiphany.com/static/admin/css/base.css I know I'm missing something. I'm new to 'compiling' and keep doing $ python manage.py runserver to compile files as I change them. Note: I am using an SFTP to edit the files like settings.py and urls.py but it keeps appearing as if the system is using cached files. Running on Webserver (not local) DB is Mysql and seems to be working fine. DEBUG=True -
Django rename default function on model
I had a Django model that looked like the following: class Foobar(models.Model): baz = models.CharField(max_length=12, default=some_func) some_func existed in a file /someproj/utils/utils.py This was fine, and all was well. I created my migration for this model and worked as expected. Roughly the migration looked like: from __future__ import unicode_literals from django.db import migrations, models import someproj.utils.utils class Migration(migrations.Migration): dependencies = [("someproj", "0008_auto_20180928_0002")] operations = [ migrations.CreateModel( name="Foobar", fields=[ ( "baz", models.CharField( default=someproj.utils.utils.some_func, max_length=12, serialize=False, ), ), ], ) ] Then I later realized I wanted to rename some_func to something else. I renamed the function in utils.py, and of course now the migration fails as some_func no longer exists. If I modify the migration by hand that works, but the rule of thumb that was explained to me is you (almost) never edit a migration by hand. What is a way to accommodate this change? Is it you have to edit the migration by hand? Wouldn't that be problematic if I had to run an older version of the code (ie say I had to checkout a previous commit to a point in time before the rename)? -
Untangle dictionary inside list
I need some help figuring out this complicated list. I am trying to print just the var_names. I have created a list from a mongo collection so that I can use it as a jSON object later. List format: [{ 'tags': {'variables': [{'value': '3x5', 'var_name': 's'}, {'value': '12:00AM', 'var_name': 'x'}, {'value': 'abc', 'var_name': 'y'}] } }] Expected Result: s x y Please help. I keep getting errors no matter what combinations I try to get the value -
Django - Encode video and audio files only when the file is changed
I'm using django-storages for storing media files on Amazon S3. I've developed an interface using boto3 to use Elastic Transcoder for encoding videos or audio files. Also for video files I'll add a watermark logo still using Elastic Transcoder. The flow is the following: The client app upload the file thought the REST API I developed -- DONE Django stores the file on Amazon S3 -- DONE If it's a video or audio, Django will launch a Amazon Elastic Transcoder Job to encode the file. The output file will be added to a different path on the same S3 bucket. Using Amazon SNS, Django will be notified when the encoded file will be ready To launch the encoding process, I was thinking to use the post_save. So I could check if the file has been uploaded, then launch Amazon Elastic Transcoder. Example: @receiver(post_save, sender=MyModel) def encode_file(sender, instance, created, **kwargs): if instance.content_type in ['video'] and instance.file: encode_file(instance.file) # Launch Amazon Elastic Transcoder Is there a better way to launch the encoding process only for video or audio files and only when the file is changed? -
how to use the category name as url suffix in Django
Now my url is like:https://mywebsite.com/newscategory_lists-5 I want change it to:https://mywebsite.com/categoryname Here is my model: class Category(models.Model): name = models.CharField(max_length=40) # 分类名 class Meta: verbose_name = "分类" verbose_name_plural = verbose_name def __str__(self): return self.name Here is the urls.py: path('category_lists-<int:category_pk>', views.categoryNewsList, name="category_news_list"), Here is my view.py: def categoryNewsList(request, category_pk): category = get_object_or_404(Category, pk=category_pk) news_list = News.objects.filter(category=category) return render(request, "categories_list.html", { 'news_list': news_list, 'category': category }) -
How do I fix this error? TypeError: expected str, bytes or os.PathLike object, not tuple
The error comes in importing the methods. from django.conf.url import patterns, include, url. from django.conf.url import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.contrib import admin from django.urls import path from django.views import View urlpatterns = [ path('admin/', admin.site.urls), url(r'^aula3/$', 'aula.views.index', nome ='aula3_index',) ] if settings.DEBUG: urlpatterns += patterns('', (u'^media/?p<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}), ) urlpatterns += staticfiles_urlpatterns() -
Django MEDIA_ROOT pointed to network drive
I'm trying to get files uploaded through the Django admin site to be placed on a network drive. Lets say the path to this drive is '\\FILESERVER\Django'. My initial thought was to just set my media root to the same path I'd use to access the drive via File Explorer: #settings.py MEDIA_ROOT = r'\\FILESERVER\Django' An Example Model: #models.py class Article(models.Model): title = models.CharField(max_length=128) pdf = models.FileField(upload_to='articles', blank=True, null=True) def __str__(self): return self.title But when I upload a file, It just creates the folder on my local C: drive. (e.g. C:\FILESERVER\Django\articles). Is there a way I can tell Django that this is supposed to be a path to a network drive? Note: This is a Django 2.0.4 app running on a windows machine. -
How to 'protect' an ajax view in django
I have various ajax views that accept data from jquery and work as follows: @csrf_exempt def update_view(request): if request.method == 'POST': process_data() My question is, how can I protect these views better? Should I pass something like a token in the ajax request in order to validate that it's a valid call? Otherwise, it seems pretty easy to spoof the above ajax views. -
Django - Pythonic way of extending parent and only changing child class fieldnames?
I'm working on some networking-related model mixins and I have two particular models that are supposed to be identical in every way except for their fieldname prefixes. Picture: class SrcEvent(models.Model): src_ip = models.GenericIPField... (...many more properties and methods...) class DstEvent(models.Model): dst_ip = models.GenericIPField... (...many more properties and methods...) Repeating everything twice (or even just extending one to get the methods on the other) doesn't sit well with me; what I'd like to end up with is a generic abstract class Event that just contains attributes like ip, hostname and such, then extend that with two child classes (SrcEvent and DstEvent) that append either "src_" or "dst_" to each field when the model is generated/migrated. (I can't just make Event and call it a day; some models mix in one, the other, or both sets of attributes, and the direction matters!) I do not know how to go about this within Django, or what to call it to look it up myself. Any tips would be appreciated! -
Django customizing admin templates did not always change them
Copied base_site.html from my defaults templates (project\Lib\site-packages\django\contrib\admin\templates\admin) to my app (project\mysite\polls\templates\admin) and it works with my custom version of it. But with 404.html it does not work so (I even changed it in original template, and still 404 is intact) -
Blender on IBM Cloud (Cloud Foundry)
I'm currently developing a web application (Django 2.0) application. My app will be deployed on IBM Cloud (Cloud Foundry) using python build-pack. One of my requirements is to install blender. Everything else is very well, but for blender installation. What I've tried so far was: I tried access my app using SSH connection, but surely I don't have root access to apt-get install blender!! And tried to include blender in packages.json file and push that file using cf push my-app. But nothing worked for me. In another shorter question: what is the main approach in Cloud Foundry Apps to install packages like when we use apt-get install in Ubuntu / Debian. Please correct me if I did anything wrong, or guide me with headlines to solve this problem!! -
Is it safe to send ajax post like this? If not, how to clean it?
All tutorias of how to use ajax with django said I should do something like this. But is that safe to do this? Cannot someone just change the values in the browser to some malicious SQL? If so, how to prevent it? javascript text = this.previousElementSibling.value; parent = this.parentNode.id; ajax.open('POST', '/post/comment/', true); ajax.onreadystatechange = function(){ if(this.readyState == 4) { reply = document.createElement("DIV"); reply.classList.add('post'); reply.innerHTML = this.responseText; document.getElementById('comments').appendChild(reply); } } ajax.setRequestHeader("X-CSRFToken", csrf_token); ajax.setRequestHeader('Content-Type', 'application/json'); ajax.send(JSON.stringify({'text': text,'parent': parent})); views.py def post_comment(request): if request.method == 'POST': body = json.loads(request.body.decode('utf-8')) parent = Post.objects.get(pk=body['parent']) comment = Comment.objects.create( author=request.user, parent=parent, group=parent.group, text=body['text'] ) -
Make disable user instead of delete in django
I try to disable the user instead of deleting it I make a boolean disable in the model but how to define it I try many ways but nothing work is there any ideas Thank you -
Django: Recommended Model definitions for Customers and Payments when handling recurring payments
Assuming I have two models, one for Customer and another for Payment. And that each month my customer should have made a payment no later that the 15th of each month. What is the best way to structure the models in order to easily get a report of customers who haven't pay for the current month? Customer model: class CustomerModel(models.Model): first_name = models.TextField() last_name = models.TextField() email = models.EmailField() Payment model: class Payment(models.Model): customer = models.ForeignKey( Customer, on_delete=models.SET_NULL, null=True) amount = models.FloatField() date_received = models.DateField(auto_now=False) -
Django CBV CreateView - Redirect from CreateView to last page
I'm learning Django and i have problem with redirecting back from CreateView I want to redirect to a BookDetail page which contains list of bookinstances which are created by CreateView. models.py: class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='Book availability', ) class Meta: ordering = ['due_back'] permissions = (("can_mark_returned", "Set book as returned"),) def __str__(self): """String for representing the Model object.""" return f'{self.id} ({self.book.title})' @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False views.py class BookInstanceCreate(PermissionRequiredMixin, CreateView): model = BookInstance fields = '__all__' permission_required = 'catalog.can_mark_returned' initial = {'Book': Book} success_url = reverse_lazy('book-detail') urls.py urlpatterns += [ path('book/create/instance', views.BookInstanceCreate.as_view(), name='book_create_instance'), ] path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), success_url seems to not work here since redirect url needs information about book primary key. I have already tried few options ex. ` next = request.POST.get('next', '/') return HttpResponseRedirect(next) return … -
Could not load Boto3's S3 bindings
I'm deploying to Heroku a Django==2.1.2 and Python==3.6.5 app and i would to manage media and static files with Amazon S3. Here's my settings.py: INSTALLED_APPS = ( ... 'storages', ) AWS_STORAGE_BUCKET_NAME = '****' AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_files_storage.StaticFilesStorage' MEDIAFILES_LOCATION = 'media' MEDIAFILES_STORAGE = 'custom_files_storage.MediaFilesStorage' Here's my custom_files_storage.py: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class MediaFilesStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION class StaticFilesStorage(S3BotoStorage): location = settings.STATICFILES_LOCATION I have runed: pip install boto pip install boto3 pip install django-storges I have tried with boto and boto3 but the error keeps Here's the error output: File "/app/.heroku/python/lib/python3.6/site-packages/storages/backends/s3boto3.py" in <module> 32. raise ImproperlyConfigured("Could not load Boto3's S3 bindings.\n" Exception Type: ImproperlyConfigured at /registro/ Exception Value: Could not load Boto3's S3 bindings. See https://github.com/boto/boto3 I don't know how to fix it Someone could help me please? Thanks in advance. -
geodjango return geojson and add it to a leaflet map through the django html template
I have a django view that takes the results of a SQL query and renders it to the index.html home page of my web map. the SQL is a POST request that returns acreage to the page. I am trying to also return geojson to and display it using the django template and not through an JSONResponse. here is html document, I included only the relevant JavaScript. <html> {% load static %} {% load leaflet_tags %} {% load bootstrap3 %} {% load geojson_tags %} <head> {% leaflet_js %} {% leaflet_css %} {% bootstrap_css %} <title>Our Home</title> <style type="text/css"> #gis {width: 80%;height:900px;} </style> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-search-master/src/leaflet-search.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'leafletgroupedlayercontrol/dist/leaflet.groupedlayercontrol.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'routing/dist/leaflet-routing-machine.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-control-osm-geocoder-master/Control.OSMGeocoder.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'Leaflet.Control.Layers.Tree-master/L.Control.Layers.Tree.css' %}"> <script type="text/javascript" src="{% static 'jquery/jquery-3.3.1.slim.min.js' %}" > </script> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> <script type="text/javascript" src="{% static 'turf/turf.min.js' %}" > </script> <script type="text/javascript" src="{% static 'leaflet-search-master/src/leaflet-search.js' %}" > </script> <script type="text/javascript" src="{% static 'leafletgroupedlayercontrol/dist/leaflet.groupedlayercontrol.js' %}" > </script> <script type="text/javascript" src="{% static 'leaflet-control-osm-geocoder-master/Control.OSMGeocoder.js' %}" > </script> <script type="text/javascript" src="{% static 'Leaflet.Control.Layers.Tree-master/L.Control.Layers.Tree.js' %}" > </script> </head> <body> <br> <div id="parcel search" class="col-md-2 … -
How to write forms.py and views.py for online MCQ Django applicatoin
I am newbie in django and doing an project on Online MCQ Examination where i have to write the forms.py and views.py for displaying question and choosing option .I have not connected database also. So i have to go with internal memory files process. I am very thankful for this help in advance. If possible help with models.py also -
Huge time difference between django profiler and actual http response
I'm using django-rest-framework to build an RESTful API. I'm having some response latency problems so I decided to use the silk library in order to profile the view's response. Here is the view's code: class ChecklistDetail(APIView): permission_classes = (permissions.IsAuthenticated, StaffPermission) @silk_profile(name='get ChecklistDetail') def get(self, request, pk, format=None): # pylint: disable=E1101 checklist = Checklist.objects.get(pk=pk) serializer = ChecklistSerializer(checklist, many=False) return Response(serializer.data) After making the request, I had the following results: Silk profilling result Postman timmings This is a difference of almost 50 times! Can someone help me to find and fix this difference? The StaffPermission class is: class StaffPermission(permissions.BasePermission): message = 'Only active staff can perform unsafe methods.' def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return request.user.is_authenticated and request.user.is_active else: return request.user.is_staff and request.user.is_active My nginx config: upstream atlas-intelligence-server { ip_hash; server atlas-intelligence-server:80; } # portal server { location / { proxy_pass http://atlas-intelligence-server/; } listen 80; client_max_body_size 100M; server_name localhost; # Avoid 504 HTTP Timeout Errors proxy_connect_timeout 605; proxy_send_timeout 605; proxy_read_timeout 605; send_timeout 605; keepalive_timeout 605; } My gunicorn command: gunicorn atlas_intelligence.wsgi -b 0.0.0.0:80 --workers 2 --log-level debug --error-logfile /var/log/gunicorn_err.log --log-file /var/log/gunicorn.log --timeout 300 Both nginx (nginx:1.15.4-alpine) and the django machines are containers. -
Why does form submit produce AttributeError: 'NoneType' object has no attribute 'filter' in Django
I can't figure out why this won't work. My form displays perfectly, but when I press submit, I get the following error: AttributeError at /cycles/new/ 'NoneType' object has no attribute 'filter' Request Method: POST Request URL: http://127.0.0.1:8000/cycles/new/ Django Version: 2.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'filter' Here are the corresponding file excerpts for reference. models.py: class Instructional_Cycle(models.Model): date_started = models.DateField(null=True) date_finished = models.DateField(null=True) standards = models.ManyToManyField(Standard, related_name="standards") class Meta: ordering = ['date_started'] def __str__(self): return str(self.date_started) + ' to ' + str(self.date_finished) def get_absolute_url(self): return reverse('student_progress:cycle_detail', args=[str(self.id)]) class Standard(models.Model): subject = models.CharField(max_length=14, choices=subjects) grade_level = models.IntegerField(choices=gradeLevels) descriptor = models.CharField(max_length=15) description = models.TextField() essential_status = models.BooleanField(default=False) class Meta: ordering = ["subject", "grade_level", "descriptor"] def __str__(self): return self.descriptor + ': ' + self.description[:100] def get_absolute_url(self): return reverse('student_progress:standard_detail', args=[str(self.id)]) views.py: class CycleCreateView(LoginRequiredMixin, FormView): model = Instructional_Cycle form_class = CycleForm template_name = 'cycle_new.html' success_url = reverse_lazy('student_progress:cycles') login_url = 'login' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet with extra items context['standards_list'] = Standard.objects.filter(essential_status=True) return context forms.py: class CycleForm(forms.Form): date_started = forms.DateField date_finished = forms.DateField standards = forms.ModelMultipleChoiceField(queryset=None) I'm pretty sure the form is returning the values … -
Django get and use instance and field name on upload_to
I'm trying to build a path for a FileField, getting and using the instance to get another data for the URL, plus the field name, to get something like: /media/documents/<instance_data>/<field_name>.pdf My best working approach is: class UserDocFileField(models.FileField): def get_fixed_folder_path(self, instance, filename): return 'documents/{}/{}.pdf'.format(instance.user.rfc, self.name) def __init__(self, *args, **kwargs): kwargs["upload_to"] = self.get_fixed_folder_path super(UserDocFileField, self).__init__(*args, **kwargs) And in my model: class Documents(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) file_1 = UserDocFileField() file_2 = UserDocFileField() # ... other documents Giving me what I'm looking for, i.e.: /media/documents/ABCD840422ABC/file_1.pdf However, this makes Django to generate a migration file every single time I run makemigrations, I have tried to set it as an inner class, rewriting the super as super(Documents.UserDocFileField, self).__init__(*args, **kwargs) But, I got this error: NameError: name 'Documents' is not defined So, is there a way to avoid the generations of migrations files or a better approach to solve this? -
How to set on settings.py date format, timezone?
How to set on settings.py date format, timezone? this affect to database?