Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Saving A Model With Form + Current User Data
I'm writing my first app in django and i have encountered a problem. I'm trying to make a booking system. I'm trying to save the reservation model. It works just fine while the user is logged out. But once i click submit while logged in nothing really happens. The site simply reloads. Can anyone point out what I'm doing wrong? That's my model code: class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) name = models.CharField(max_length = 100) surname = models.CharField(max_length = 100) phone = models.CharField(max_length = 9) class Reservation(models.Model): reservationID = models.AutoField(primary_key = True) name = models.CharField(max_length = 100) surname = models.CharField(max_length = 100) phone = models.CharField(max_length = 9) email = models.EmailField() bookIn = models.DateField('Book in date', default = timezone.now) bookOut = models.DateField('Book out date', default = timezone.now) roomType = models.ForeignKey(Room_type, on_delete = models.CASCADE) My form: class Booking(forms.ModelForm): class Meta: model = Reservation fields = ('name', 'surname', 'phone', 'email', 'roomType', 'bookIn', 'bookOut',) widgets = { 'bookIn': forms.DateInput(attrs={'class': 'datepicker'}), 'bookOut': forms.DateInput(attrs={'class': 'datepicker'}) } And my view: form = Booking() if request.method == 'POST': form = Booking(request.POST) if form.is_valid(): if request.user.is_authenticated: reservation = Reservation() guest = Profile.objects.get(user=request.user) reservation.name = guest.name reservation.surname = guest.surname reservation.phone = guest.phone reservation.email = guest.user.email reservation.bookIn = form.cleaned_data.get('bookIn') … -
How can I integrate the escrow process into a Django app?
Step 1: When Employer accepts a bid, he will pay the bid budget (example: $10) to Admin’s account. Step 2: After Employer accepts a bid, this project will change its status to “Processing”. If the employers “FINISH” this project, the Escrow process will move to step 3. Otherwise, the employers “CLOSE” or freelancers “QUIT” this project, it will turn the status into “dispute” and Escrow process will jump to step 4. Step 3: After the employer clicks “Finish” button, this project’s status will become into “Completed”. Step 4: The freelancer and employer will send their reports to Admin, and Admin will decide who the winner is in this case. -
How to query a django model using another model?
I'm new to django (and python) and I have a question. I have this model: class Material(models.Model): name = models.CharField(max_length=256, blank=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class Meta: abstract = True and class Experiments(models.Model): title = models.CharField(max_length=200) experiment = models.ManyToManyField(to=Material, through='ExperimentsMaterial', related_name='Experiments') def __str__(self): return self.title I want to query it so I have only have the Materials used in the Experiments model. I was reading about Q objects but I'm not sure how to use it. I appreciate any help! -
How pass a file to a js function in Django?
I will integrate the PhylD3 library in an Django Template. The css and js are integrated in django static directory. But i dont really know how process to efficiently load the xml file in the template. template phyD3.html {% extends "base.html" %} {% load static %} {% block title %} Test {% endblock %} {% block content %} <head> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://d3js.org/d3.v3.min.js"></script> <link rel="stylesheet" href="{% static 'css/phyd3/phyd3.min.css' %}" /> <script src="{% static 'js/phyd3/phyd3.min.js' %}"></script> <script> function load() { d3.xml("sample.xml", function(xml) { var tree = phyd3.phyloxml.parse(xml); phyd3.phylogram.build("#phyd3", tree, {}); }); }; </script> </head> <body onload="load()"> <div id="phyd3"></div> </body> {% endblock %} view.py def phyd3(request): return render(request, 'coregenome/phyD3.html') error in browser consol -
JSONField model field in django: How to make it editable in django admin
How do I go about making a django model field of type JSONField editable in django admin? Example Model: from django.contrib.postgres.fields import JSONField from django.db import models class AppModel(models.Model): name = models.CharField(max_length=50) data = JSONField() Example of data column in PostgreSQL: data = { "debug": "on", "window": { "title": "Sample Data", "name": "main_window", "attr":[{"width": 500},{"height": 500}] }, "widget": true } Examples, links to examples would be very much appreciated. -
Django ModelMultipleChoiceField doesn't display queryset
I would like to use ModelMultipleChoiceField with ModelSelect2MultipleWidget in order to display a dropdown menu with my widget. If I write this : publication_list = forms.ModelMultipleChoiceField(queryset=Publication.objects.all().order_by('pub_id')) It displays my queryset but the design is not good and if I want to select multiple objects, I have to highlight them. Then, I don't have search bar. That's why I would like to write this : publication_list = forms.ModelMultipleChoiceField( queryset=Publication.objects.all().order_by('pub_id'), label=_('Publication Choice'), widget=ModelSelect2MultipleWidget( model=Publication, queryset=Publication.objects.all().order_by('pub_id'), search_fields=['pub_id__icontains', 'title__icontains'], ) ) But with this code, this is the result : It doesn't work and I would like to understand why ? The expected result should be something like that : -
Is Django's create super user and Django's admin user creation same?
Is Django's create super user (command) and Django admin's user (in localhost) creation same? If yes, why doesn't the user which I created using localhost site is not available in auth_user table, whereas user created with superuser command is available If no, where does the details on the users created through localhost side(admin page) is saved. -
Django how to give a user input for writing email text
I have a template for sending custom emails: The template is as below: <p> Type here your email: </p> <input id="your_name" type="text" name="your_name" value="{{ mail_content }}"> {% csrf_token %} <input type="submit" value="Send the Request " name="_add_peer_confirm"> <input type="submit" value="Go back to Standard Email " name="_"> <input type=button value="Go back" onClick="javascript:history.go(-1);"> </div> How can I make it tidy and gives the user a big input where he can write his mail? any idea? -
Formating Pandas decimals in Django
I´m not able to format some numbers with fixed decimal positions on Pandas dataframe in Django. I´ve tryied several options: round(testdataframe["ticket_medio"], 1) Result: unsupported operand type(s) for *: 'decimal.Decimal' and 'float' np.round(testdataframe["ticket_medio"], decimals=1) Result: unsupported operand type(s) for *: 'decimal.Decimal' and 'float' testdataframe.round(1) Result: nothing seems to happen pd.options.display.float_format = '{:.1f}'.format testdataframe.round(1) Result: nothing seems to happen -
Django does not update with UpdateView
I have this view to show the previously populated data, which was only populated in the admin panel: from .models import (Token, Sell, LogisticCost, IncomeCost, FinalPayment, CustomerServiceCost, Fatura) def product_list(request): context = {'product_list': ProductList.objects.filter(client=request.user.id).all(), 'data_payment': Fatura.objects.all()} return render(request, 'Clientes/list_products.html', context) This is the view to update these values: class UpdateProduct(UpdateView): model = ProductList context_object_name = 'product_list' template_name = 'Clientes/update_product.html' fields = ['name', 'description', 'cost_price', 'sell_price', 'ncm'] My form in the update page is: <form method="post" action="{% url 'client:product_list' %}"> {% csrf_token %} {{ form }} <button class="btn btn-inverse" type="submit">Atualizar</button> </form> My update page is working as expected, showing every value related to the selected object, but when I submit the form the model has not changed. What is happening to not update the values? -
How to use validator in Django depending on the database data?
I'm making a web app that keeps tracks of a small business. For that purpose I have two models designed in my app. One of which is all the storage information and the other is for each selling orders, like: class Storage(models.Model): name = models.CharField('product name', max_length=64) quantity = models.DecimalField('inventory', max_digits=6, decimal_places=4, default=0) class Orders(models.Model): product = models.ForeignKey('Storage', on_delete=models.CASCADE) volumn = models.DecimalField('order volumn', max_digits=6, decimal_places=4, default=0) I want a validator for my Orders class so that the input value from the form doesn't exceed that from the corresponding Storage data. How can I achieve that? Thanks! -
Validating Upload file in django
Here I,m using Django-REST framework for file upload, I'm not using a model layer in Django. So I am using default_storage for the uploaded file to save. My question here is how would I validate the files. Uploaded file should not exixts 10mb.Thanks in Advance. class imageapi(APIView): def post(self, request): if request.method == 'POST' and request.FILES['file']: try: form = UploadFileForm(request.POST, request.FILES) #save_path = os.path.join(settings.MEDIA_ROOT, 'uploads', request.FILES['file']) save_path = str(settings.MEDIA_ROOT)+ '/uploads/'+str(request.FILES['file']) path = default_storage.save(str(save_path), request.FILES['file']) return Response({default_storage.path(path)}) except Exception as ex: return Response({"DATA": str(ex)}) -
Django download link pour file.apk
Bonjour, J'ai un souci, j'essaye de mettre un lien pour le téléchargement d'un fichier .apk, sans sucée! je débute avec django, je fais des modifications sur une application faite avec Django 1.11 L'idée c'est de mettre un lien ex : projet.entreprise.com/download/android/mobile.apk, après avoir tapé le lien faut que le mobile.apk se télécharge ou bien une popup pour le télécharger. J'ai fais ca: urls.py apk for Android url(r'^download/android/', download.apk),<br><br> puis ca : download.py import os from django.conf import settings from django.http import HttpResponse def apk(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(~/download/mobile.apk): with open(~/download/mobile.apk, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/vnd.android.package-archive") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 Ps: je suis vraiment nul en python & django, j'essaye de les apprendre, en même temps que les tâches demander par le chef de projet. Merci d'avance :):) -
Celery can't logging string errors in 'utf-8'. UnicodeDecodeError
Sometimes I need to create errors with params in russian language. For example: raise FooError(c_(u'Task %(name)s'), params = {'name': "курочка"}) And then I have this error: Traceback (most recent call last): File "/usr/lib/python2.7/logging/__init__.py", line 868, in emit msg = self.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 741, in format return fmt.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 465, in format record.message = record.getMessage() File "/usr/lib/python2.7/logging/__init__.py", line 329, in getMessage msg = msg % self.args UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) I use: Python 2.7.15rc1; celery 3.1.19; django-celery 3.1.17; Django 1.11.2. You can reproduce the bug: import logging from logging import getLogger l = getLogger() handler = logging.FileHandler('/tmp/fh') l.addHandler(handler) l.log(50, u'Task 1') l.log(50, u'Task %(name)s', {'name': "курочка"}) I think that there is problem in a Celery. If you open <your part>/lib/python2.7/site-packages/celery/worker/job.py, you will be able to see 100-124 lines. There are formed messages in which we will pass the parameters, for example: #: Format string used to log task failure. error_msg = """\ Task %(name)s[%(id)s] %(description)s: %(exc)s """ and it is expected that the data will be string in the English layout (см. function _log_error(<...>)): ... exception, traceback, exc_info, internal, sargs, skwargs = ( safe_repr(eobj), safe_str(einfo.traceback), einfo.exc_info, einfo.internal, safe_repr(self.args), … -
Update table records when session timeout without page load
Installed pip install django-session-timeout updated setting.py like this MIDDLEWARE_CLASSES = [ # ... 'django.contrib.sessions.middleware.SessionMiddleware', 'caccounts.middleware.SessionTimeoutMiddleware', # custom middleware # ... ] And also add the SESSION_EXPIRE_SECONDS = 3600 # 1 hour SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True I'm wrote some code in my custom middleware like below current_user = request.user user = User.objects.get(pk=current_user.id) user.is_online = False user.save() Its update status only when i load page but i want to update status automatically while timeout session -
write django multiple views in single template
Here Only Random_number Function is working Correctly, but random password function is not giving even console output I want to return Generated password to the html template. Is there is any problem with the code? Views def random_number(request): random_num = '' if(request.POST.get('Submit-Number')): min_number = int(request.POST.get('min_number')) max_number = int(request.POST.get('max_number')) random_num = random.randint(min_number,max_number) return render(request,'random_number/random-number.html'), {'random_num':random_num}) def random_password(request): random_pass = '' if(request.POST.get('Get-Password')): min_length = int(request.POST.get('min_length')) #max_length = int(request.POST.get('max_length')) all_char = 'abcdefghijklmnopqrstuvwxyz123456789!@#$%^&*()' for eve in range(min_length): new_word += random.choice(all_char) random_pass = new_word print(random_pass) return render(request,'random_number/random-number.html', {'random_pass':random_pass}) Templates </head> <body> <div class="container"> <div class="row"> <div class="col-md-6">1</div> <h3> Generate Random Number Here </h3> <form class="" action="#" method="POST"> <!-- method is posting and refreshing page with new Data over Random Number --> <input type="number" name="min_number" value="1"> <input type="number" name="max_number" value="10"> {% csrf_token %} <input type="submit" name="Submit-Number" value="SUBMIT"> </form> <!-- <h3> Random Number = {{ random_num }}</h3> --> </div> <div class="col-md-6">2</div> <h3> Generate Random Password Here </h3> <form class="" action="#" method="POST"> <!-- method is posting and refreshing page with new Data over Random Number --> <input type="number" name="min_length" value="8"> <input type="number" name="max_length" value="12"> {% csrf_token %} <input type="submit" name="Get-Password" value="SUBMIT"> </form> <h3> Password = {{ random_pass }}</h3> </div> </div> -
Restrict Django REST framework API calls to first-party apps
This has probably already been asked and answered, but after looking around a bunch I haven't found exactly what I am looking for. Suppose I have the following apps : Web client at https://example.com/ using the Django framework. Mobile client, basically my own iOS/Android apps. REST API at https://api.example.com/ using the Django REST framework. Third-party (web and mobile) apps are allowed to request the API thanks to the django-oauth-toolkit. QUESTION: Now I also need my own web and mobile apps to access the API. Since these apps aren't third-party apps, users should be able to login to their account using only their username and password after installing the mobile app. Simple token-based authentication could accomplish this task, but I guess third-party apps (or anyone) would be technically able to use this method to access data instead of creating an API application from the web app (OAuth2 method). What is the best method to achieve that? Is it possible to create a private API to allow my own apps to request the API? Thank you. -
Get full fields in nested model. Django Rest Framework
I have 2 models: class CustomUser(AbstractUser): username = models.CharField(max_length=30, unique=True) tags = models.ManyToManyField('events.Tag', related_name='user_tag', blank=True) class Tag(models.Model): name = models.CharField(unique=True, max_length=50) And Serializers: class UserSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: ... class TagSerializer(serializers.ModelSerializer): class Meta: lookup_field = 'name' model = Tag fields = ('id', 'name') When i do a get query i recieve something like this: "relationships": { "tags": { "data": [ { "type": "Tag", "id": "1" } ] } } What i want, is to get Tag 'name' field in user representation. **"type": "Tag", "id": "1", "name":"name"** And i want to make patch qurey for adding tag to user. I can use SerializerMethodField(), but this way i will not able to add tags -
Django group by as one single result
I have the following filter with annotations: results = (results.values('redirection_type', 'target__sharing_actions__medium') .annotate( amount=Count('redirection_type'), second=Count('target__sharing_actions__medium')) .order_by('redirection_type')) Which gives the following results: [ { 'redirection_type':'time_pre_event', 'target__sharing_actions__medium':'email', 'amount':1, 'second':1 }, { 'redirection_type':'time_pre_event', 'target__sharing_actions__medium':'facebook', 'amount':1, 'second':1 }, { 'redirection_type':'time_pre_event', 'target__sharing_actions__medium':'twitter', 'amount':1, 'second':1 }, { 'redirection_type':'time_rating_page_param_ctx_hash', 'target__sharing_actions__medium':'email', 'amount':2, 'second':2 }, { 'redirection_type':'time_rating_page_param_ctx_hash', 'target__sharing_actions__medium':'facebook', 'amount':1, 'second':1 }, { 'redirection_type':'time_rating_page_param_ctx_hash', 'target__sharing_actions__medium':'twitter', 'amount':2, 'second':2 } ] However, I'd like to have the data merged together to the same redirection_type to something like this: [ { 'redirection_type':'time_pre_event', { 'email': 1, 'facebook': 1, 'twitter': 1 } }, { 'redirection_type':'time_rating_page_param_ctx_hash', { 'email': 2, 'facebook': 1, 'twitter': 2 } }, ] Is it possible to adjust the query to get the desired result or do I have to parse into this form manually? -
how can i override date validation in django rest framework
in my model gst_date = models.DateField(blank=True, null=True) it is an optional field, from UI it sent as gst_date = "" gst_date = null OR remove the gst_date key is working fine my question is how can I handle the empty string from Django serializer itself ?? -
unexpected output while trying to convert html to pdf in django
here is my view to which converts html to django @api_view(['GET']) @renderer_classes((JSONRenderer,TemplateHTMLRenderer)) def admin_order_pdf(request, order_id, *args, **kwargs): # def admin_order_pdf(request, order_id): queryset=D.objects.all() # serializer= order = get_object_or_404(queryset, id=order_id) price=order.price discount=order.discount total=price-discount template=get_template('bill/bill.html') data={ 'order': order,'total':total } html = render_to_pdf('bill/bill.html', data) return HttpResponse(html, content_type='application/pdf') and this is the code for render_to_pdf from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None and my urls.py re_path(r'^bill/(?P<order_id>\d+)/pdf/$', admin_order_pdf, name='admin_order_pdf'), and my html template <html> <body> <h1>My Shop</h1> <p> {% for ord in order %} <li>{{ ord.name }}</li> {% endfor %} but whenever i tried to access the url i could load the pdf but there isnt any content in that particular pdf file except a single word "profiles" i dont even know where that word came from -
How to create session in django. Please give me few links
I am trying to create a session using python and django. Could anyone please provide me a sample code. Thanks in advance. -
Django: Alter table with migration without altering values
I have a form with a phone number field. I used to have a CharField where anyone could input virtually anything, but I've changed it, using this Widget That means that I now have a widget which allows the user to select a country code and then input his phone number, and the all validation is automatic. However, the use of this widget required that I change my CharField to a PhoneNumberField in my model. I had some tweaks to do but it works fine because both fields translate into a VARCHAR(255). However, when I migrated on my testing environment, all older values in the phone field were altered, and all values that didn't correspond to the format wanted by PhoneNumberField were deleted (or to be more precise, made worthless: 00336XXXXXXXX was turned into +NoneNone). I do not want to reproduce this behavior in production environment. Is there a way to edit my migration so that it doesn't alter any value already present in the table? If not, what tweak could I use to keep older values? -
Django: POST and GET within one form? Need to record users search terms
I'm trying to save a users search history whilst they are using my website. I have created a working search bar for users to search for items in the database. I am using a GET request in my views.py and HTML to receive search results: def project_search_results(request, project_query): query = project_query results = box.objects.filter(Q(project_assigned_to__project_name__icontains=query)) return render(request, 'main_app/project_search_results.html', {'query':query,'results':results}) And the HTML: <form class="search-button" action= "{% url 'main_app:search_results' %}" method="get"> <label for="form-control"> <input class="form-control" name = "q" value="{{request.GET.q}}" placeholder="Enter asset name here"> </label> <button id = "search-button" class="btn btn-dark" type="submit"> Submit </button> </form> I would like to save these results to a model that I have made: class user_search_history(models.Model): user = models.ForeignKey(User) search_history = models.CharField(max_length=300, blank=True, null=True) date_searched = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'user_search_history' Is there some way that I could record these searches in my model despite me using a 'GET' reqeust in the form? I'm unsure as to where to go from here so any help would be massively appreciated. -
how to set config of host in channel layers using django with aws ec2?
I am making a Chat app using django channel and I am also using AWS EC2. My socket is close when i using this type of channel layer : CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts":[("<my_aws_host>", 6379)], }, }, } please help me, where and how i put host key of aws in channel layer. Thanks,