Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a django password in a simple python script
I need to generate an encrypted password that can be used within Django in a simple python script. What package/module would I need to import to achieve that? I am looking for something like: from django.auth import create_password_from_string django_password = create_password_from_string('coolpassword') The background is, that I have a PHP application on server1 which should share the accounts with a Django application on server2. When an account is created in the PHP application, I want to fire up a python script that generates the encrypted password for the django application and transfers it to server2. -
Optimizing a large Django project by moving certain process to dedicated machine (microservice?)
I'm working on a large Django project that uses application server(s) to process Latex. As our site grows, the Latex processing is affecting performance when site traffic is high. One idea I had was to move the Latex processing to a separate EC2 instance optimized for: processing Latex using TexLiv, creating a PNG, saving PNG to S3, and then returning a URL for the image. I also need to communicate with my existing Django ORM to update the object's image URL with the one just created on the dedicated machine. I have several questions: 1) what kind of EC2 instance should I use (computer or memory optimized?) 2) what kind of web server should I use on this dedicated Latex processing machine (is this a microservice?) Django, Tornado, Flask? 3) How do I get my existing project to communicate with new, dedicated Latex processing machine. 4) anything else I might be missing Thanks -
Django debug toolbar 1.8 offline mode
I started using django debug toolbar 1.8 in project with django 1.11.17, everything goes well until I tried to used it from home (is not showing at all) where I don't have internet, that is the only difference I can think off. Any ideas? -
AttributeError: 'TestimonyForm' object has no attribute 'save'
Help needed. I have no idea what is error-ed in the line of code. The traceback points to the form.save() line. #views.py class TestimonyFormFunction(View): form = TestimonyForm template = 'variablized_form.html' @method_decorator(login_required) def get(self, request): form = self.form_class(None) return render(request, self.template, {'form':form}) def post(self, request): if request.method == 'POST': form = TestimonyForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'testimony_post.html', {'Testimony':Testimony}) else: form = TestimonyForm() return render(request, 'variablized_form.html', {'form': form}) -
django-tables2: Table.render_Foo naming
I got the following Table and want to implement a render_foo() function for the modelField.ST and modelField.ZF fields. 34 class MyTable(Table): 35 class Meta: 36 model = MyModel 37 fields = ('modelField.ST', 'modelField.ZF', 'score' ) How are they named? def render_modelField_ST(self,record) and def render_modelField__ST(self,record) did not work Thank you! -
validation for date field
i have override date format in django modelform widget and jquirey datepicker, it given error that field is not valid class Sale_Invoice_Main_Page(forms.ModelForm): class Meta: model = SaleInvoice fields = '__all__' exclude = ['created_at','updated_at','transiction_type'] widgets = {'description' : forms.TextInput(attrs={ 'placeholder' : 'description'}), 'invoice_no' : forms.TextInput(attrs={ 'readonly' : 'True'}), 'total_amount' : forms.TextInput(attrs={ 'readonly' : 'True'}), 'invoice_date' : forms.DateInput(attrs={ 'class' : "vdate" },format=('%d-%m-%Y')), 'due_date' : forms.DateInput(attrs={ 'readonly' : "True" },format=('%d-%m-%Y')), } class SaleInvoice(models.Model): customer = models.ForeignKey(Customer_data , on_delete=models.CASCADE) invoice_date = models.DateField(null=True,blank=True) invoice_no = models.PositiveIntegerField(unique=True) due_date = models.DateField(blank=True,null=True) address = models.TextField() total_amount = models.PositiveIntegerField(null=True,blank=True) description = models.TextField(null=True,blank=True) transiction_type = models.CharField(max_length=50,blank=True) author = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.address jquirey date picker {# Date Picker#} <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( ".vdate" ).datepicker({ dateFormat: "dd-mm-yy" }); } ); </script> i want to find what is i am doing wrong that it is given validation error -
Referencing search groups in Django's RegexValidator
I have a regex validator which has a named search group. Something like this: my_validator = RegexValidator(r'^[a-zA-Z0-9]*/(?P<pk>[0-9]*)$') Now, I use this to check patterns. Something like this: search = my_validator('articles/421') search.group('pk') The last line returns an error: AttributeError: 'NoneType' object has no attribute 'group' Why is this? Is a RegexValidator different from normal regexes, in the sense that it does not have groups? -
customize implementation of multiple databases in django
i am begginer in django. i wanted to develop an web app that choose database after user authentication or at user authentication.. ie. i am having a business which have multiple branches so i would like to give functionality that each branch can have different database so that my database could be distributed.. and one master login which can access all the databases united... so models, templates even all databases will have same tables but the only data will be distributed.. i want dropdown for selection of branch at user authentication page.. or it will do automatically recognized which user is from which branch is there any way to do these kind of functionality?? -
Django-Python strategic game between human and computer
I am working on a project which aims to develop a web-based game. My plan is to use Django framework along with some other Python APIs such as gurobi, cplex, or ortools. The game is played as follows: There are two players: the human user and the computer. The user chooses a game setting, including the number of rounds the game will be played. Before the game begins, the computer receives the game setting and generates its prior belief about the user's certain preferences on the game. Moves in each round are made simultaneously. In each round, the user chooses his/her strategy and the computer generates its strategy by solving a linear programming problem. The computer makes use of previous moves of the user to update its prior belief to generate better strategies. The computer's belief is an input for the linear programming problem in each round. As the round played, the user is informed about the computer's strategy, so he/she can adjust his/her strategy accordingly. During the game, the page will not be loaded again. Apparently, for each round, two way information flow occurs. In a given round, server needs to solve the linear programming problem that triggered by … -
amazon elasticbeanstalk vs s3 for django static files
As I see in aws django guides, I should configure django collectstatic command to copy static files to amazon s3 storage. I see that in the elastic beanstalk configuration I can set a static path to configure a the proxy server to serve static files directly from the webapp folder. As described here under "static files": https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html The question: what is the difference between the two methods, i.e serving static files from s3 or using the eb configuration. Does one method has a better performance over the other? -
How should I POST and serialize and array of arrays with DRF?
I'm having an issue POST-ing a JSON object that contains and array of arrays and deserializing it using Django Rest Framework. The idea here is that there can be a dynamic number of players (players: 2) and a list of lists/array of arrays of weapons that the players have (player_weapons [[], []]). //javascript on client var post_data = { players: 2, player_weapons: [ ["sword", "shield"], ["mace", "slingshot"], ]}; var results = jQuery.post( url, post_data ); #serializers.py class GameSerializer(serializers.Serializer): players = serializers.IntegerField(min_value=1) player_weapons = serializers.ListField( child=serializers.ListField( child=serializers.CharField(min_length=1, allow_blank=True), min_length=0, required=False), min_length=0, required=False ) The request.POST I get is: <QueryDict: {'runs': ['1000'], 'additional_players': ['2'], 'player_weapons': ['sword,shield', 'mace,slingshot']}> What's really weird is that when I do request.POST['player_weapons'] I get: mace,slingshot whereas I'm expecting/hoping to get: [['sword', 'shield'], ['mace', 'slingshot']] Any help on how I should be structuring the POST and handling it in DRF would be awesome. -
Django - create CSV on the fly and save it to filesystem and model file field
In my django app, I have a management command which I want to use to process some data and create a model instance as well as file in filesystem and save its path to above instance's file field. My management command: import datetime import timy from django.core.management.base import BaseCommand import tempfile from core.models import Entry from np_web.models import Dump import calendar import csv class Command(BaseCommand): help = 'Create dump and file for current day' def handle(self, *args, **options): with timy.Timer() as timer: today = datetime.date.today() dump_title = '{}.{}.{}.csv'.format(today.day, today.month, today.year) entries = Entry.objects.all() dump = Dump.objects.create(all_entries=entries.count()) dump.save() print('Dump created with uuid:', dump.uuid) print('Now create data file for dump') with tempfile.NamedTemporaryFile() as temp_csv: writer = csv.writer(temp_csv) writer.writerow([ 'Column1', 'Column2', ]) for entry in entries: writer.writerow([ entry.first_name, entry.last_name ]) dump.file.save(dump_title, temp_csv) My Dump model: class Dump(BaseModel): created = models.DateField(auto_now_add=True) all_entries = models.PositiveIntegerField() file = models.FileField(verbose_name=_('Attachment'), upload_to=dump_file_upload_path, max_length=2048, storage=attachment_upload_storage, null=True, blank=True) Anyway, it doesn't work. It is throwing an error: TypeError: a bytes-like object is required, not 'str' I am also not sure if using temporary file is a best solution out there. -
ajax django form to submit just a partial of data
I have a form, that is standard django. Fill it out send it off goes to a different page upon success..shows errors if you don't fill out portions. Now I have a modal form that will pop up to fill out some extra data. I have decided to try to my hand at ajax for this. I have some of it working: Inside the class that is an UpdateView: def post(self, request, *args, **kwargs): if self.request.POST.has_key('group_info_submit') and request.is_ajax(): print("YOU SURE DID SUBMIT") return HttpResponse("hi ya!") The problem is it always redirects to a different page, and fails validation anyway because the form the modal pops over is not complete and trying to be submitted. I saw this post here: Ajax Form Submit to Partial View This seems overly complicated, I just have a small div in my form that is a modal div that I would like to submit sort of separately from the rest... The java script I have in the code: $.ajax({ data: $("#groupinfoForm").serialize(), success: function(resp){ alert ("resp: "+resp.name); } }) Then the little modal html snippet is: <div class="container"> <div id="groupinfo-dialog" class="modal" title="Group Information" style="display:none"> <div class="modal-dialog"> <h1> Group Information </h1> <div class="modal-content"> <div class="modal-body"> <form action="." … -
Reroute import pathes in django
I want to use a django app (newapp) in my django project. To keep it simply updated, I would like to include it as git submodule, but this will lead to a folder structure like: myproject |-app |-newapp-git |-newapp |-settings.py |-urls.py |-... |-README.md That is because, newapp is unfortuntely not only the appfolder but also some files (like readme) and the subfolder newapp. I can add this in INSTALLED_APPS with newapp-git.newapp, but the app itself imports models etc. with import newapp which does not work, and I cannot change it because I dont want to modify the content in newapp to keep it updated simply. So, is there a chance to tell django, that imports from newapp should be rerouted to newapp-git.newapp? -
How to set tag max length
Have my app up and running with django (1.11), django-taggit (0.22.2) and taggit-selectize (2.6.0). However, some users seem to prefer long sentence like tags instead of using multiple short tags. Anyway of limiting the tag length? -
Django: correct way to pass AJAX
I've a view that recives parameters from the frontend via AJAX. I've passing AJAX parameters in a maner, but this time my way didn't work. I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work: Why? My friend's AJAX: <script> $("#id_shipping_province").change(function () { var val_d = $("#id_shipping_department").val() var val_p = $("#id_shipping_province").val() $.ajax({ url: "/district/?d_name=" + val_d + "&p_name=" + val_p }).done(function (result) { $("#id_shipping_district").html(result); }); }); </script> My AJAX: <script> $("#id_shipping_province").change(function () { var val_d = $("#id_shipping_department").val() var val_p = $("#id_shipping_province").val() $.ajax({ url: "/district/", d_name: val_d, p_name: val_p }).done(function (result) { $("#id_shipping_district").html(result); }); }); }); </script> View def get_district(request): d_name = request.GET.get("d_name") p_name = request.GET.get("p_name") data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True) # data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True) return render(request, "accounts/district_dropdown.html", { "districts": set(list(data)) }) -
Postgres query to Django ORM
I want to do this query bellow in django orm, i've tried to do with the queryset example and it doesn't work, always returns the error, i want to know if is possible to solve this. I think the problem migth be GROUP BY, and the Django ORM doens't do the GROUP BY, but this it is just a guess. error: Traceback (most recent call last): File "C:\Python35\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python35\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python35\lib\site-packages\rest_framework\viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "C:\Python35\lib\site-packages\rest_framework\views.py", line 495, in dispatch response = self.handle_exception(exc) File "C:\Python35\lib\site-packages\rest_framework\views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python35\lib\site-packages\rest_framework\views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "C:\Python35\lib\site-packages\drf_multiple_model\mixins.py", line 112, in list data = query_data['serializer_class'](queryset, many=True, context=context).data File "C:\Python35\lib\site-packages\rest_framework\serializers.py", line 765, in data ret = super(ListSerializer, self).data File "C:\Python35\lib\site-packages\rest_framework\serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "C:\Python35\lib\site-packages\rest_framework\serializers.py", line 683, in to_representation self.child.to_representation(item) for item in iterable File "C:\Python35\lib\site-packages\django\db\models\query.py", line 268, in __iter__ self._fetch_all() File "C:\Python35\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File … -
NoReverseMatch: Reverse for 'details' with arguments '('',)' not found. 2 pattern(s) tried:
I can't seem to spot the error in my code and I have tried everything. It is probably something simple that is escaping my eye. Please help! Any imput is appreciated. New Django learner here. #views.py def details(self, Testimony_id): Testimony=get_object_or_404(Testimony, pk= Testimony_id) return render(request, 'details.html', {'Testimony': Testimony}) #template <header class="w3-container w3-blue"> <h1><a href="{% url 'Testimony:details' Testimony.id %}">{{Testimony.Title}}</h1> </header> #urls.py app_name='Testimony urlpattern=[ ... re_path('<int:id>/', views.detail, name='details'),] #models.py class Testimony(models.Model): ... def get_queryset(self): return Testimony.objects.all() def __str__(self): return self.title def __str__(self): return str(self.id) -
postgresql backup DB linked to django restore error
PostgreSQL 10 with PostGIS 2.4 linked to a Django (1.11.18). Currently moving my DB to a remote server and going through the backup and restore process. Backup Process PGAdminIII - backing up with tar format. All the dump options are default (only blobs are selected in Dump Options #1, verbose messages in Dump Options #2). I back it up and there are no errors. Restore Process Using default settings in PGAdminIII. I get this error for every single table in the DB. These errors are causing issues in my application querying for data from the DB -
Why am I getting a key error in my Django code given below?
from django import forms from django.core import validators class FormName(forms.Form): name=forms.CharField() email=forms.EmailField() verify_email=forms.EmailField(label='Confirm your email') text=forms.CharField(widget=forms.Textarea) def clean(self): #Allows us to grab all the clean data at once all_clean_data=super().clean() #This will clean the entire Form email=all_clean_data['email'] vmail=all_clean_data['verify_email'] if email != vmail: raise forms.ValidationError("Make sure your emails match") In this code, I am getting a key error at verify_email vmail=all_clean_data['verify_email'] KeyError: 'verify_email' -
Django JSONField list of dicts "contains" filter inside Subquery
I'm trying to filter model objects which contain key-value pair from OuterRef in their JSONField with list of dicts. I have a model EntityObject with fields "type" and "data". It works witout Subquery: EntityObject.objects.filter( type='child', data__list_of_dicts__contains=[{'some_key': 'value'}] ) Also it works inside Subquery without __contains (but needs values from JSONField to be annotated). For example I can count entities which have data.some_other_key equal to data.some_key of parent entity: (EntityObject.objects .filter(type='parent') .annotate(data_some_key=Cast( KeyTextTransform('some_key', 'data'), models.CharField()) ) .annotate(cnt=Subquery( EntityObject.objects .filter(type='child') .annotate(data_some_other_key=Cast( KeyTextTransform('some_other_key', 'data'), models.CharField()) ) .filter(data_some_other_key=OuterRef('data_some_key') .values('type') .order_by() .annotate(cnt=Count('*')) .values('cnt')[:1], output_field=models.IntegerField() )) Now I try to combine both queryies like this: (EntityObject.objects .filter(type='parent') .annotate(data_some_key=Cast( KeyTextTransform('some_key', 'data'), models.CharField()) ) .annotate(data_some_other_key=Cast( KeyTextTransform('some_other_key', 'data'), models.CharField()) ) .annotate(cnt=Subquery( EntityObject.objects .filter(type='child') .annotate(data_list_of_dicts=KeyTransform('list_of_dicts', 'data')) # not sure if this is correct .filter(data_list_of_dicts=[{OuterRef('data_some_key'): OuterRef('data_some_other_key')}] .values('type') .order_by() .annotate(cnt=Count('*')) .values('cnt')[:1], output_field=models.IntegerField() )) But it throws an error: TypeError: OuterRef(data_some_key) is not JSON serializable Is there any way of doing it without using RawSQL or looping? -
In the Django admin interface, is there a way to check a few list items and trigger an action to copy field contents to clipboard?
For example, if I had a model: StoragePosition(models.Model) which has a field, 'name'. I would want to enter the model's list/change view. Then select a few items, choose a 'copy names to clipboard' action. Then be able to paste in the format: name_1 name_2 name_3 I would especially want it to be able to paste contents into an excel spreadsheet, each name in its own cell. -
When I include a template in another template how can I pass the path of a source file?
I have two templates that go together, one inside the other. The inner one has an icon that needs to change according to the content of the parent template. I've tried to pass the icon path using a variable: src="{% url 'main_bar_icon' %}"> and I added this line of code in the parent template: {% with main_bar_icon='../static/dist/img/logout-icon.svg' %} {% include 'main_bar.html' %} {% endwith %} So, this is my inner template: {% block main_bar %} <a href=""> <img class="app-main-bar-icon" src="{% url 'main_bar_icon' %}"> </a> {% endblock main_bar %} And this is my parent template: {% block content %} {% with main_bar_icon='/dist/img/logout-icon.svg' %} {% include 'main_bar.html' %} {% endwith %} {% endblock content%} In the browser I get this: <img class="app-main-bar-icon" src(unknown) alt="icon"> -
Django 2 Many to Many relationships
I'm working on a project using Python(3.7) and Django(2.1) in which I need to build a relationship between users and organizations. I'm using the default Django User model and a profile model to add extra information to users. Many users can join an organization and an Organization can have many members, a user can create an Organization, these behaviors I need to implement, according to my understanding we need to build a ManyToMany relationship for Organizations model, but don know how to use this relationship to display the information, e.g display a user's organizations on his profile page. Here are my models: class Organization(models.Model): name = models.CharField(max_length=255, blank=False) users = models.ManyToManyField(User, related_name='members', null=True) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='media/default.jpg', upload_to='profile_pics') goals = MultiSelectField(choices=goals_choices, default='') def __str__(self): return f'{self.user.username} Profile' -
How to build a shopify application with django
I have a homework : The objective is to create a Shopify app. The app will allow a customer to login to the shop using his Twitter account. Stack using : Django + DRF + Vanilla Js (for the front end). But i have never build an app for shopify apps store, and all tutorials found about django an shopify are very old and not updated. And others are only about Ruby... So i post here to hope find somebody to explain (not necessary in details) how can i setup my django app and make it reachable on shopify app store. Where an customer can try to login in his shop with a twitter account. Ps: I want just the step to follow and configure the entire app... Thank for reading and trying to help me !