Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to raise custom error message via a django signal?
I have a model class myModel(models.Model): name = models.CharField(max_length=100) type = models.CharField(max_length=100) nums = JSONField(null=True, blank=True) I need to save numbers in the nums field. But, no two instances of myModel that have same typecan have same numbers (intersection of nums fields should be null). I have tried writing a signal for it @receiver(pre_save, sender = myModel) def check_duplicate_nums(sender, instance, **kwargs): all_records = myModel.objects.filter(type = instance.type) for record in all_records: common_nums = list(set(record.nums).intersection(instance.nums)) if len(common_nums) != 0: raise Exception("nums "+str(common_nums)+ " are repeated in " +str(record.name)+ " and "+instance.name) But doing this opens the debug window of django admin. I want the error to be displayed right there. For example, when we save a model with an empty field and it throws an error saying 'This field is required' in red-highlighted line. I need to to display the error in that manner. Please suggest a way. Thanks! -
Django admin save and continue editing using ajax
I want to implement the save and continue editing button functionality in change form page of admin model, using ajax. I used the code in this link: https://gist.github.com/MadLittleMods/3c8c531e10906fc16f5c this link is for save button. I modified that to change the model by changing ajax url to django change url(like /admin/my_model/120/change). the problem is every time I press my custom button it appends all the previous records to my model. If my first record is '1' and the second is '2' when I create second record I get '1','1','2' and when I save third I get '1','1','2','1','2','3' and so on. I can change save_model method in my admin model to prevent saving repeated data but I don't want to send extra data over ajax. thanks for helping -
django create file download url
I'm trying to create a custom download link for a file stored in S3. My url.py looks like this: ... url(r'^s3download/(?P<filename>[\w.]{0,256})$', FileFormatErrorView.cbs3download, name='s3download'), ... In my template I have <a href="{% url 's3download' filename=file.filename %}" rel="external">Download</a> And in my views.py I got class FileFormatErrorView(TemplateView): ... def cbs3download(request): ... When trying to access the page I receive the error django.urls.exceptions.NoReverseMatch: Reverse for 's3download' not found. 's3download' is not a valid view function or pattern name. What am I missing? -
DetailView redirect when object DoesNotExist
I have started working on converting some old code that uses function based views to try to use class based views where applicable. I have the below class that grabs a profile object based on a set of parameters. My questions is if I get a DoesNotExist error I want to redirect to a specific url in my application. How would I go about that? class ProfileView(generic.DetailView): model = Profile template_name = 'area51/profile.html' def get_object(self, queryset=None): return Profile.objects.get(**self.kwargs) -
How to display toaster notification in box in Django?
Expected output is like Expected output image Views.py def UpdateProducts(request,id): if request.method == 'POST': form = ProductsForm(request.POST, request.FILES) if form.is_valid(): data = Product.objects.get(pk=id) form = ProductsForm(request.POST,request.FILES, instance=data) form.save() messages.success(request, "The Subscriber has been successfully added") return redirect('/') else: messages.error(request, "Sorry the data has not been entered to the database") Html {% for message in messages %} toastr.{{ message.tags }}({{ message }}); {% endfor %} please tell me how to do it? -
Site serving static files but not media files in Prod
Settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media/") My local server is able to pick them using ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) but site is not able to find them, and give error 404. Folder /etc/apache2/sites-enabled contains site.conf File /etc/apache2/sites-available/site.conf contains: Alias /static /www/site/static <Directory /www/site/static> Require all granted </Directory> Alias /media /www/site/media <Directory /www/site/media> Require all granted </Directory> I can find a static files on url generated as http://site/static/imgs/img.png but getting error 404 with url generated as http://site/media/imgs/img.png In second scenario: all the files look same, but from file /etc/apache2/sites-available/site.conf I removed the media part and left with Alias /static /www/site/static <Directory /www/site/static> Require all granted </Directory> Now server serves the media files with debug turned on, but gives 404 with debug turned off. which is even more confusing. How can I serve media files on server, with debug turned off? The image files are dynamically getting generated and getting uploaded in the folder in both the scenarios. Static files are also served perfectly in both scenarios. -
trouble in django staticfiles
I am having trouble serving my staticfiles. Using django 2.0 This is the settings file, STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),'static') STATIC_URL = '/static/' I ran collectstatic and then every static file was copied in the STATIC_ROOT folder. The thing is the admin static files and rest framework are being served, but not the ones which I have added. (env) luvpreet@nfs:~/myntracms/myntracms$ python manage.py shell Python 3.6.5 (default, Mar 29 2018, 03:28:50) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.conf import settings >>> settings.BASE_DIR '/home/luvpreet/myntracms/myntracms/myntracms' See this, luvpreet@nfs:~/myntracms/myntracms/static$ pwd /home/luvpreet/myntracms/myntracms/static luvpreet@nfs:~/myntracms/myntracms/static$ ls admin debug_toolbar djcelery images js rest_framework luvpreet@nfs:~/myntracms/myntracms/static$ Admin static files work, But my files are not being served, Even if I paste my files in the admin folder, still they are not being served. luvpreet@nfs:~/myntracms/myntracms/static/admin/js$ ls | grep home home.png But still, -
Only apply a filter if the list count in the query is greater than 0
In the following case I only want to apply the filter(departments__in=depts) if the count of depts is greater than 0. sites = Site.objects.for_user(request.user)\ .filter(departments__in=depts)\ .filter(archived=False) Aside from wrapping the entire block in an if else, is there a nicer way of doing this within the filter? -
List Serializer with dynamic fields in Django Rest Framework
I'm trying to add fields dynamically to a serializer of Django Rest Framework, by overwriting the __init__ method. The approach is similar to the one described here: http://masnun.com/2015/10/21/django-rest-framework-dynamic-fields-in-serializers.html The reason I'm doing this is, because I want to change the field type dynamically to a one, determined by the property type_ of the instance to be serialized. This works pretty well, if I serialize one instance at a time: from rest_framework import serializers from rest_framework.fields import empty class VariableDetails: def __init__(self, name, type_, value): self.name = name self.type_ = type_ self.value = value class VariableDetailSerializer(serializers.Serializer): TYPE_FIELD_MAP = { 'string': serializers.CharField, 'integer': serializers.IntegerField, 'float': serializers.FloatField, } name = serializers.CharField() type_ = serializers.CharField() def __init__(self, instance=None, data=empty, **kwargs): # this is where the magic happens super().__init__(instance, data, **kwargs) if instance is not None: field_type = self.TYPE_FIELD_MAP[instance.type_] self.fields['value'] = field_type() string_details = VariableDetails('character value', 'string', 'hello world') integer_details = VariableDetails('integer value', 'integer', 123) print(VariableDetailSerializer(string_details).data) # {'name': 'character value', 'type_': 'string', 'value': 'hello world'} print(VariableDetailSerializer(integer_details).data) # {'name': 'integer value', 'type_': 'integer', 'value': 123} If I want to serialize multiple instances of VariableDetails that are related to a parent instance (calling it Parent for the example), the value field is missing: class Parent: def __init__(self, … -
Django Data Migration: Access data in a separate file
I'm trying to run a migration that loads my tables with information in a list. My question is How do I access that list if I put it in a separate file? I don't want to have to copy and paste the entire list into my migration file every time I run a migration. Plus, when my program expands I will have a lot more lists to copy and paste. migration file from django.db import migrations """ ['ABC', 'Alphabet'], """ countries = [ ['CAN', 'CANADA'], ['USA', 'UNITED STATES'], ] def import_countries(apps, schema_editor): Country = apps.get_model('service', 'Country') for c in countries: country = Country.objects.get_or_create( country_code=c[0], country_name=c[1] ) print(country) class Migration(migrations.Migration): dependencies = [ ('myapp', '0012_auto_migrate'), ] operations = [ migrations.RunPython(import_countries), ] -
Menu appearing after a choice is made
I'm pretty new to Django and I'm unsure of whether I'm going in the right direction with this. What I'm trying to do is, when the user is creating a Character in the Admin menu, if the user chooses faction Alliance, to bring up the Alliance_Races, and if not, the Horde_Races. models.py Factions = ( ('Choose', 'Choose...'), ('Alliance','Alliance'), ('Horde', 'Horde'), ) Alliance_Races = ( ('Human','Alliance'), ('Dwarf', 'Horde'), ('Night Elf', 'Night Elf'), ('Gnome', 'Gnome'), ('Draenei', 'Draenei'), ('Worgen', 'Worgen'), ('Pandaren', 'Pandaren'), ) Horde_Races = ( ('Orc','Orc'), ('Undead', 'Undead'), ('Tauren', 'Tauren'), ('Troll', 'Troll'), ('Blood Elf', 'Blood Elf'), ('Goblin', 'Goblin'), ('Pandaren', 'Pandaren'), ) class Character(models.Model): character_name = models.CharField(max_length=100, default="") faction = models.CharField(max_length=8, choices=Factions, default='none') race = "" def __str__(self): return self.character_name def race_options(self): if self.allied_with == "Alliance": self.race = models.CharField(max_length=8, choices=Alliance_Races, default='none') else: self.race = models.CharField(max_length=8, choices=Horde_Races, default='none') I'd appreciate any help. Thanks in advance! -
Remove user endpoints in Django rest auth
I am using Django rest auth for user account handling. For updating user info i have created custom endpoints, So i don't need the djnago-rest-auth generated endpoints /rest-auth/user/ (GET, PUT, PATCH). How can i remove these endpoints? -
Angular5 front-end, Django back-end and OIDC
currently I am working on web application described by this scheme: app scheme I want the user to log in using my angular client which then asks django app and django app will handle loging by custom OIDC provider (similar to Google). I am looking for some library or github repo that can help me solve this case. Thank you. -
DjangOAuthToolkit - How to have different read/write scope for a View?
I'm using DRF and OAuthToolkit. Here is my view:- class UserDetailView(RetrieveUpdateDestroyAPIView): serializer_class = UserUpdateSerializer permission_classes = [TokenHasResourceScope] required_scopes = ['user_detail'] Now, the above view will support GET, PUT, PATCH, and DELETE methods. Now, if I create a token with a scope as user_detail, it will give access to all the methods. However, I want different read/write scopes for SAFE and UNSAFE methods. Upon reading OAuthToolkit code for TokenHasResourceScope, it create scopes for SAFE and UNSAFE methods, ie user_detail:read and user_detail:write. Now, if the client request for user_detail:read scope, the library returns invalid scope. How do I support scopes for read and write of a particular view differently? -
post separately form in formset via ajax in Django
is it possible to submit separately the form in a django formset via ajax ? so far i am able to submit the whole formset via ajax <form ajax_url="{% url 'main:add_example_sentence' %}" method="post" id="ajax-form"> {% csrf_token %} {{ formset.management_form }} <table> <tr><th>{% trans "one field" %}</th></tr> {% for form in formset %} <tr><td><i>{{ form.one_field.value}}</i></td></tr> {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% endfor %} </table> <input class="btn btn-primary" type="submit" value="{% trans "Submit" %}" /> </form> here's the script part <script> $('#ajax-form').on('submit', function(event){ event.preventDefault(); form = $(this); $.ajax({ type: "POST", url: form.attr("ajax_url"), dataType: 'json', data: form.serialize(), success : function(json) { // handle successful response }, error : function(xhr,errmsg,err) { // handle a non-successful response } }); }); </script> -
Django: How to combine multiple AccessMixins?
UserProfile can be (for now) in two groups (in group_A, group_B, and both at once). I've created a mixin which redirects user from a forbidden page (for their group) to allowed (default url). The mixin above will check, if user is in Group_A. If not, their will be redirected to the default Group_B url if they are in this group otherwise returns 403. class Group_AAccessMixin(UserPassesTestMixin): redirect_url = None def test_func(self): try: return self.request.user.profile.is_group_A except: return False def handle_no_permission(self): if self.request.user.profile.is_group_B: messages.info(self.request, "...") return HttpResponseRedirect(reverse_lazy("group_B:list")) return super(Group_AAccessMixin,self).handle_no_permission() The problem is that I need to use these mixins with LoginRequiredMixinbecause, Group_AAccessMixin and Group_BAccessMixin works only for authenticated users. If I do this: class IndexView(LoginRequiredMixin, Group_AAccessMixin, TemplateView): template_name = 'main/index.html' The handle_no_permission method from AccessMixin which is a superclass of LoginRequiredMixin and Group_A/BAccessMixin if being overriden by Group_A/BAccessMixin. I want to first check authentication, redirect to login and then check group_A or group_B attributes. Is it possible to somehow combine it or do I have to create new methods? -
Don't target child model class
So I'm trying to make a queryset of Post excluding AdvertisePost. Here's my models: class Post(models.Model): ... class AdvertisePost(Post): ... My current queryest: posts = Post.objects.all() targets both models. However I only want to target the Post model, not AdvertisePost - how can I do this? -
VueJS select not updating when model updates
So I have a data variable struct in a vuejs-store: <select class="ui dropdown" v-model="struct" @change="split_consumption_over_tariff()" id="tariff_struct_select"> {% verbatim %} <option v-for="tstruct in tariffstructs" :value="tstruct.key" :key="tstruct.key"> {{gettext(tstruct.name)}} </option> {% endverbatim %} </select> {% verbatim %}{{ struct }}{% endverbatim %} The final line updates fine, whenever struct changes, but the select doesn't update itself. Any idea what I might be doing wrong? -
Elastic Beanstalk (Django) deployment fails because of RDS InvalidParameterCombination
I have a django app running on AWS using elastic beanstalk. Has been running for quite a while without any problems. Just now upon deploying via CLI (eb deploy) I'm running into the following error: ERROR: ...Reason: The following resource(s) failed to update: [AWSEBRDSDatabase]. ERROR: Updating RDS database named: [...] failed. Invalid storage size for engine name postgres and storage type standard: 15 (Service: AmazonRDS; Status Code: 400; Error Code: InvalidParameterCombination; Request ID: [...]) The error message contains the value 15, and indeed, in the django application database configuration it says: When I try to change that number to an arbitrary 25 GB and apply those changes, I run into yet another error: ... Cannot upgrade postgres from 9.5.10 to 9.5.4. ... So there are two things I don't understand: Why is the 15GB a problem all of a sudden? Why would it attempt to "upgrade" from 9.5.10 to 9.5.4? Explanations and solution suggestions much appreciated! -
Django 2.0 Retrive data from model with field array
I have a model having name, branch, section. class Student(models.Model): name = models.CharField(max_length=20) branch= models.CharField(max_length=20) section = models.CharField(max_length=5) I can retrive data from the model using 2 option, tuple and list. model.objects.values_list('name', 'branch') model.objects.values('name', 'branch') But If I have array of fields it doesn't work. a = ['name', 'branch'] model.objects.values_list(a) model.objects.values(a) I need some way if I have array of fields then I need to retrieve the data. -
Django StreamingHttpResponse not setting correct filename
Struggling with this one... I am trying to use StreamingHttpResponse to output a csv of data. The file itself is constructed fine, but for some reason the filename is being set incorrectly across different browsers. I'm using Django Rest Framework with a custom csv renderer. The CSVRenderer takes the standard data from a Django Rest Framework ReadOnlyModelViewsetand renders it using StreamingHttpResponse. The CSVRenderer was written based on Django docs explaining how to output a csv import csv from rest_framework.renderers import BaseRenderer from django.http import StreamingHttpResponse class Echo(object): '''An object that implements just the write method of the file-like interface. ''' def write(self, value): '''Write the value by returning it, instead of storing in a buffer. ''' return value class CSVRenderer(BaseRenderer): '''Renderer class to generate basic csvs of the data supplied by the serializer ''' media_type = 'text/csv' format = 'csv' def render(self, data, media_type=None, renderer_context=None): rows = [] first_data_row = next(iter(data['results']), None) # Create header rows if data present if first_data_row: rows.append(list(first_data_row.keys())) # print the data to rows for row in data['results']: rows.append(list(row.values())) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in rows), content_type='text/csv') response['Content-Type'] = 'text/csv; name="export.csv"' response['Content-Disposition'] = 'attachment; filename="export.csv"' return response So when I … -
Python (Django) Error importing a module into a bat
I have a problem running my bat file or I'm using a python program (Django). Here is the error message at runtime: Traceback (most recent call last): File "chemin\import_engagementD.py", line 5, in <module> from postes.models import EngagementD ImportError: No module named 'postes' FIN du Scripthere Here is my bat file: @ECHO OFF ECHO Script en cours python chemin\import_engagementD.py ECHO FIN du Script pause And finally the tree of my project: Picture -
Applying Search/Filter Dropdown For Django CreateView
I am trying to apply a search/filter in dropdown menu on the field that has a selector (in this case the "item_selector") which can easily contain at least a thousand entry. models.py from django.db import models class Model_Model01(models.Model): item_selector = ( ("item_0001", "item_0001"), ..., ..., ("item_9999", "item_9999"), ) item_01 = models.CharField(max_length = 50, null = True, blank = True, choices = item_selector) def __unicode__(self): # or __str___ return self.item_01 forms.py from django import forms from .models import Model_Model01 class Form_Model01(forms.ModelForm): class Meta: model = Model_Model01 fields = ["item_01"] views.py from .models import Model_Model01 from .forms import Form_Model01 from django.views.generic import CreateView class View_Model01_CV(CreateView): form_class = Form_Model01 def form_valid(self, form): instance = form.save(commit = False) instance.user = self.request.user return super(View_Model01_CV, self).form_valid(form) html {{ form.item_01 }} I wondering if there is a way to do this in Django, either using Django 3rd party app or with a Bootstrap. -
"UNIQUE constraint failed: users_user.username" error?
I'm studying user registration with Django, but I don't know why I get this error: UNIQUE constraint failed: users_user.username after trying to fill in the form. I have deleted the database and every migration/cache. It's with a custom user model where I use email as identifier. Is there something wrong with the code below, or do you have any suggestions? views.py class RegisterView(CreateView): template_name = 'users/registration.html' form_class = RegisterForm success_url = '/' forms.py class RegisterForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ('email', 'password1', 'password2',) -
use rest framework beside render in django
I want to create a research page but I've few problem because I want to separate the server side and client side, and for that I want to use render, to show the render form and Response to return a json that can be request using an api rest but when I do that there is lot of problem, so do you knows how to return in an api rest only the answer of the form ? can I use render beside Response ?