Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django datepicker in ModelForm shows incorrect date with instance
I have a ModelForm in forms.py as - class MyForm(forms.ModelForm): from_date = forms.DateField(input_formats=['%d-%m-%Y'], label='From Date', widget=forms.TextInput( attrs={'placeholder': 'Select a date', 'class': 'datepicker'}) ) to_date = forms.DateField(input_formats=['%d-%m-%Y'], label='To Date', widget=forms.TextInput( attrs={'placeholder': 'Select a date', 'class': 'datepicker'}) ) class Meta: model = MyModel fields = ['from_date', 'to_date', 'reason'] And the related js - $('.datepicker').flatpickr({ dateFormat: "d-m-Y", allowInput:true, }); With a create form, everything works fine and object gets created successfully. However, on editing the object, the initial date shown on the form is incorrect (Probably the %Y-%m-%d gets parsed as %d-%m-%Y). How to show the correct date in the update form? I tried setting the initial in __init__ but it didn't work. -
ModuleNotFoundError: No module named 'impassionuser'
I'm using django on vscode, and typed this on terminal: (impassion) Subinui-MacBook-Pro:impassion_community subin$ python3 manage.py makemigrations but can't use makemigrations got this error message ModuleNotFoundError: No module named 'impassionuser' how can I solve this problem? I'm using MacOSX, VSCode, django and setup virtualenv I expected to see follow messages Migrations for 'impassionuser': impassionuser/migrations/0001_initial.py -Create model impassionuser -
How to scale y-Axis in d3.js according to data input correctly
I created a small Barchart. My problem is that the y-axis doesn't scale according to my dataset. Here is a screenshot: So as you can see the 313 is a little bit above the 800 scale. I would like the 300 to be at the 300. I tweaked with the scalings but I just end up messing it up completely. I am very new to D3.js so I hope someone can help. Here is my code: var svgWidth = 1000, svgHeight = 800; var barWidth = svgWidth / month_description.length; var barPadding = 5; var svg = d3.select('svg') .attr("width", svgWidth) .attr("height", svgHeight); var barChart = svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("y", function(d) { return svgHeight - d - 20 }) .attr("x", function(d, i) { return i + 10; }) .attr("height", function(d) { return d; }) .attr("width", barWidth - barPadding) .attr("class", "bar") .attr("transform", function (d, i) { var translate = [barWidth * i, 0]; return "translate("+ translate +")"; }); var text = svg.selectAll("text") .data(data) .enter() .append("text") .text(function(d) { return d; }) .attr("y", function(d, i) { return svgHeight - 20; }) .attr("x", function(d, i) { return barWidth * i + 35; }) .attr("fill", "white"); var xScale = d3.scaleLinear() .domain([0, d3.max(month_description)]) .range([0, svgWidth]); var yScale … -
Sphinx automodule: failed to import module
I'm learning Sphinx to document my Django project. My project structure is like app |- docs |- build |- source |- conf.py |- index.rst |- make.bat |- Makefile |- src |- authentication |- __init__.py |- models.py |- ... |- myapp |- __init__.py |- settings.py |- wsgi.py |- manage.py in the `app/docs/source/conf.py, the path to find doc is set as import os import sys sys.path.insert(0, os.path.abspath('../../src')) and index.rst has content App's documentation! ============================================= .. automodule:: manage :members: .. toctree:: :maxdepth: 2 :caption: Contents: Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` on running make html It generates blank documentation page with default content and no content from the Django application. I have many applications created and each application contains many files. I want to auto-generate documentation from the docstring throughout the Django application. -
How to rewrite serializer in Django for custom models?
I want to write my own serializer for my model with a list objects.I'm using Djongo. I've search a lot and got examples for ModelSerializers. Not working on my own model. -
Loading failed for the <script> with source “http://127.0.0.1:8000/static/js/bootstrap.min.js”
I'm getting the error "Loading failed for the with source “http://127.0.0.1:8000/static/js/bootstrap.min.js”." and my ajax is also not working. I want to delete a django form without refreshing my page def client_delete(request, pk): data = {'success': False} client = Client.objects.get(pk=pk) if request.method == 'GET': try: client.delete() if client: data['success']=True else: data['success'] = False data['error'] = "unsuccessful!" except Client.DoesNotExist: return redirect('/NewApp/clientlist') return JsonResponse(json.dumps(data)) In my client_list.py file, {% block javascript %} <script src="{% static '/js/app.js' %}"></script> <script src="{% static '/js/jquery-3.2.1.js' %}"></script> <script src="{% static '/js/bootstrap.min.js' %}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4 /jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/jquery.marquee@1.5.0 /jquery.marquee.min.js"></script> {% endblock %} <script> document.getElementById("print").addEventListener("click", function() { console.log("deleted") alert('ok'); var id = $(this).attr('name'); $.ajax({ type:'GET', url: 'NewApp/clientdelete' + id, data:{ csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(data){ if(data.success == true){ alert("success"); } } }); return(false); }); -
how to solve django.core.exceptions.FieldError?
I have 3 models class Car(models.Model): owner = models.ForeignKey(Driver, on_delete=None) car_type = models.CharField(max_length=3, choices=car_type_choices) class Ride(models.Model): pickup_time = models.IntegerField() dropoff_time = models.IntegerField() car = models.ForeignKey(Car, on_delete=models.CASCADE) class Payment(models.Model): ride = models.ForeignKey(Ride, on_delete=models.CASCADE) amount = models.FloatField() and i have to write a query with 3 conditions: if car_type is A, do A` if car_type is B, do B` if car_type is C, do C` I write the queries but get the this exception: django.core.exceptions.FieldError: Expression contains mixed types. You must set output_field. also when i comment first and second queries, third works and when i just comment third one, first and seconds works but all at the same time does not work. q = Car.objects.annotate( extras=Case( When(car_type='A', then=Count('ride')), When(car_type='B', then=Sum(F('ride__dropoff_time') - F('ride__pickup_time'), output_field=FloatField())), When(car_type='C', then=Sum(F('ride__payment__amount'), output_field=FloatField())) ) ) -
Nested models in Django
Sorry for my English. I want to know how I can build my model so that there is an nesting in the admin panel: House1 -> Apartment-> Room-> Person -> Apartment2 -> Room-> Person House2 -> Apartment-> Room-> Person -> Apartment2 -> Room-> Person House3 -> Apartment-> Room-> Person -> Apartment2 -> Room-> Person and so on. models.py from django.db import models class Alex(models.Model): #first page class title = models.CharField(max_length=300, verbose_name = 'table of contents') titletwo = models.CharField(max_length=300, null=True, verbose_name = 'Description') content = models.TextField(null=True, blank=True, verbose_name='url img') foto = models.ImageField(blank=True, upload_to="images/body/%Y/%m/%d", help_text='150x150px', verbose_name='Ссылка картинки') class Meta: verbose_name_plural = 'body' verbose_name = 'body' #should be inside the Alex tab class Bdtwo(models.Model): #for the second page title = models.CharField(max_length=300, verbose_name='table of contents') content = models.TextField(null=True, blank=True, verbose_name='Description') foto = models.ImageField(blank=True, upload_to="images/body/%Y/%m/%d", help_text='150x150px', verbose_name='url img') class Meta: verbose_name_plural = 'body2' verbose_name = 'body2' admin.py from django.contrib import admin from .models import Alex, Bdtwo class BdAdmin(admin.ModelAdmin): list_display = ('title', 'content', 'foto') list_display_links = ('title', 'content', 'foto') search_fields = ('title', 'content',) admin.site.register(Alex, BdAdmin) admin.site.register(Bdtwo, BdAdmin) Want to see: Admin panel "Alex->(inside)Bdtwo" -
Adding of Songs to an Album in Buckky's Django tutorial
Hy guys, I am following #Bukky's tutorial on django, he taught us how to add albums to our website, but not songs to specific album, i tried doing that, but I am having a bit of challenge doing that. How do i go about writing the view for adding songs. -
django-allauth google callback url not working on production
I have integrated google login using django allauth. For my local it works fine. But for production url it is not working. For production it redirect to localhost:8054/accounts/google/login/callback/?state=U0Y1kkth3jNB&code=4%2FbQFuzMf9I-RTXYJUJ-IhUyx36O-gAV00qFvtQHl3nNHzP_QVDJCfe-5f4a1zR12t_P8PgizD-cc95Hhk497fRyY&scope=profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile expected : mysite.com/accounts/google/login/callback/?state=U0Y1kkth3jNB&code=4%2FbQFuzMf9I-RTXYJUJ-IhUyx36O-gAV00qFvtQHl3nNHzP_QVDJCfe-5f4a1zR12t_P8PgizD-cc95Hhk497fRyY&scope=profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile local (working): in google api Authorised redirect URIs = 127.0.0.1:8000/accounts/google/login/callback/ production : Authorised redirect URIs = mysite.com/accounts/google/login/callback/ -
Stored boolean value isn't showing. - Django
By reading the title, it sounds pretty straight forward, but for me, I'm doing a lot of head scratching wondering where I've gone wrong. Rewinding some, I have a form with a list of checkboxes. The checkboxes which apply are selected and stored once the submit button is pressed. The data is stored, no problem. I see 1s and 0s in the DB. However trying to fetch the value has been tricky. All I want to do is see if the Boolean value for a column equals 1 and if so, show a message to the user. That's it, but none of the Boolean values show at all. If try to see a value in a column that isn't a Boolean field, everything works fine. HTML file: {% if app.checkbox_var1 == '1' %} <li> // Message goes here. </li> {% endif %} I've also tried: {% if app.checkbox_var1 == 1 %} <li> // Message goes here. </li> {% endif %} {% if app.checkbox_var1.value == 1 %} <li> // Message goes here. </li> {% endif %} {% if app.checkbox_var1 == True %} <li> // Message goes here. </li> {% endif %} Not forgetting a simple {{ app.checkbox_var1 }} // Nothing appears … -
Django: Transform dict of queryset
I use the following code to get my data out of the dict. test = self.events_max_total_gross() events = organizer.events.all() for event in events: test.get(event.pk, {}).values() [...] I use this query set to get the data. My question is: Does the transformation at the end makes sense or is there a better way to access the dict (without transforming it first). As I have several of these my approach doesn't seem to follow the DRY principle. def events_max_total_gross(self): events_max_total_gross = ( Event.objects.filter( organizer__in=self.organizers, status=EventStatus.LIVE ) .annotate(total_gross=Sum(F('tickets__quantity') * F('tickets__price_gross'))) .values('pk', 'total_gross') ) """ Convert this [ { 'pk': 2, 'total_gross': 12345 }, { 'pk': 3, 'total_gross': 54321 }, ... ] to this: { 2: { 'total_gross': 12345, }, 3: { 'total_gross': 12345, } ... } """ events_max_total_gross_transformed = {} for item in events_max_total_gross: events_max_total_gross_transformed.setdefault( item['pk'], {} ).update({'total_gross': item['total_gross']}) return events_max_total_gross_transformed -
how to exclude some specific django permissions in django html template
I am trying to display the user permissions which are relevant to my project excluding some default django user permissions. I am implementing the following code. I want to exclude permissions like sessions, content_type, groups from my html template. How can i do it?? views.py permissions = Permission.objects.all() template I want to remove user can add group,user can change group in template {% for permission in permissions %} {{permission.name}} {% endfor %} -
Django taking very long time to serve generated static files
In my view I generate 5 images (they are generated by pyplot.) Everything seems to work fine. The files are generated correctly in the right directory. But the browser only shows one of the five images, and the requests for the other 4 usually timeout. Looking at the django server output, the GET requests will often take five minutes to finish. These images are ~100kb, and are present and correct on the drive immediately after being generated. Am I missing a call for Django to update the new static files? Something else? Please help! -
Sometime on Django after ajax get compleate they show page like Jsonrespone
I using django==1.11 djangorestframework==3.8.2 and my view have a two class of api view like this Class NormalReaderHTML(APIView): def get(self,request): .. do_something .. return render('my_html.html',{}) Class AjaxView(APIView): def get(self,request): #we using cache for database like this my_cache = cache.get(cache_engagement_key) if my_cache is not None: return JsonResponse(cache_context, status=200) .. do_something .. .. do_something .. cache.set(my_cache*60*60*6) return JsonResponse({my_data},status=200) and on html page I execute file javascript to call Ajax on documeny ready like this $.ajax({ type:"GET", url:"my_endpoint", success:function(data){ $(".Dothisclass").text(_.get(data,'my_target',"")) }) }) after that we I call to my endpoint of NormalReaderHTML will show html page like normal. and after that my html and javascript will working to call Ajax and do a lot thing like insert value adjust value but sometime we found we got Jsonresponse from ajax to render page like {my_data:my_data,my_data:my_data} I already have no idea what happen and where they from. we only found it's happen in Chromes and Safari (safari it's found more than chrome) -
How can I sync MySQL Data to Google Spreadsheets?
Till now, I'm able to fetch data from Google Spreadsheets to MySQL DB. Now what I want is if I submit my form then it should get stored in MySQL DB also and Google Spreadsheets also. I'm using Django framework for my work. You can refer: https://github.com/vanthoff10/django-sqlsearch-engine Please, it's urgent for my work. Thanks in advance. -
Prepare a string representation of a command and then execute id
Django==2.2.2 Now I have this code: Model class YandexResponse(models.Model): time = models.DateTimeField(auto_now=True) campaigns = models.TextField() ad_groups = models.TextField() ads = models.TextField() keywords = models.TextField() sitelinks = models.TextField() View yandex_response_record, created = YandexResponse.objects.get_or_create(id=1) if what_to_update == "campaigns": yandex_response_record.campaigns=json.dumps(data) yandex_response_record.save() elif what_to_update == "ad_groups": yandex_response_record.ad_groups=json.dumps(data) yandex_response_record.save() ... I'd like to have something like: tmp = "yandex_response_record.{}=json.dumps(data)".format(what_to_update) execute(tmp); yandex_response_record.save() Could you tell me whether is is somehow possible? If it is not possible, could you suggest me some elegant solution here? -
django: Threads does not close after performing the function
[Simple approach to launching background task in Django refering to this I am using threading to do background processing. It perfectly renders a html page but the thread used for background processing does not stop even after performing its function how can i stop this thread after it has done its job(it only stops when i press Ctrl+C)? Note: The output of the function called by thread is fine its just that thread does not stop.I think its because this function does not return to its calling function. i have tried using threadname._stop but it gives assert error also i don't want to use thread.join() as it will wait until processing is done before rendering the html page . Here is the code(args in thread has no functionality) calling function in views.py def callmepls(request): if request.method=="POST": global x x=threading.Thread(target=theds,name="abcd", args=(1,),daemon=False) x.start() return HttpResponse("background process started working") else: return render(request,"callthis.html",{}) Performing function in view.py def theds(name): for i in range(5): print(i) time.sleep(10) x._stop() Template(callthis.html) {%extends "base.html"%} {%block content %} <form method="POST" action=""> {%csrf_token%} <p> Run the it: <input type="submit" value="Start" > </p> </form> {%endblock%} -
Why doesn't this group by work how I want or expect it to
I am new to Django.I am trying to make this this query return count by group. But it doesn't doesn't group data. notification = AppointmentNotificationGroupAppointment.objects.filter(receiver__notification_group__group=group).values('receiver__notification_group__group', 'sender__status__name').annotate(pcount=Count('sender__status__name', distinct=True)) It returns: {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Pending', 'pcount': 1}, {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Pending', 'pcount': 1}, {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Confirmed', 'pcount': 1}, {'receiver__notification_group__group': '841536_123856', 'sender__status__name': 'Confirmed', 'pcount': 1} What am I doing wrong? I want it to return distinct records with them counted by group -
how to automatically open url(not click open) http://127.0.0.1:8000 python manage.py runserver in pycharm terminal
I would like url (http://127.0.0.1:8000) to automatically open the browser (by no-click) if I enter the command 'python manage.py runserver'. I tried to run http://127.0.0.1:8000/ with a browser without a mouse. so I tried all the shortcuts I could find, but I could not find them. python manage.py runserver (venv) seongyoonhuh@seongyoonhuh:/media/seongyoonhuh/usb16g/20190619/basic$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). June 19, 2019 - 17:39:37 Django version 2.2.2, using settings 'config.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. -
Django user permission not working properly
Here i am trying to give staff users some specific permissions .I tried like this .This code saving all the checked permissions in the database table auth_user_user_permissions and also displaying the added permissions for the particular user in template but the users is not being able to use that permissions.For example i added only permission of user can view product and this permission gets added in the table but when i perform add product action with this user then i am being able to use that permission even i haven't given this action role to this user. views.py def update_user_roles(request,id): user = get_object_or_404(User, id=id) user_permissions = Permission.objects.all() if request.method == 'POST': permissions = request.POST.getlist('user_permissions') print('hey',permissions) form = EditUserRole(request.POST or None,instance=user) if form.is_valid(): role = form.save(commit=True) role.save() user.user_permissions.set(permissions) messages.success(request,'Roles updated for user '.format(user.username)) return redirect('user_profile',user.id) else: form = EditUserRole() return render(request,'update_user_role.html',{'form':form,'user':user,'user_permissions':user_permissions}) template <form action="{% url 'update_user_role' user.id %}" method="post" > {% csrf_token %} <div class="form-group"> <h5>User Roles</h5> <div class="controls"> {% for permission in user_permissions %} <input name ="user_permissions" type="checkbox" id="permission-{{permission.id}}" value="{{permission.id}}" {% if permission in user.user_permissions.all %} checked="checked" {% endif %}> <label for="permission-{{permission.id}}">{{permission.name}}</label> {% endfor %} </div> </div> <div> <button type="submit" class="btn btn-info">Save</button> </div> </form> -
How do I make "if the loop is executing for the last time" condition in python
So, I am making a login system through file handling in python. The code works fine when I enter the correct username/password but it doesn't work when I use 'else' statement for the condition which should execute when the user enters incorrect password. for line in open('accounts.txt','r+').readlines(): loginfo = line.split() if a==loginfo[0] and b==loginfo[1]: return render(request, 'login.html') else: return render(request, 'index.html') Here, the loop is executed and each line is checked to see if the username, password entered by the user is in the file or not. I am using getlines() function to get usernames and passwords of a user through lines, which means each line should consist of a username and password separated with a space. I am using line.split to split usernames and passwords in the file. If I remove "else" then enter the correct password, then the code works fine but it does not work fine when I enter incorrect password. If I put 'else' condition inside the loop then it messes up the algorithm, and the web-page is rendered when the loop is executing for the first time. What I want is that the "else" condition should execute only and the web-page 'index.html' should only be … -
How can i use same serializer in Create and List Views
I have a PostSerializer and this serializer have an user field. Also i have a UserSerializer. So i want to use UserSerializer in the PostSerializer like this class PostSerializer(serializers.ModelSerializer): user = UserSerializer(many=False) class Meta: fields = ('user', 'title') But i got the error when i try to use in the CreateView because i dont send UserSerializer data, i send user_id. I have to use same Serializer in Create and List view. Because i use to ListCreateAPIView. -
Request error in django view when setting up user
I have an app which lets the currently logged in user to create a Person object. That person object has the current logged in user as it's owner. But as I save the form it give me the following error global name 'request' is not defined I am trying to achieve this using Django CreateView the error trackback Traceback: File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\edit.py" in post 217. return super(BaseCreateView, self).post(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\edit.py" in post 183. return self.form_valid(form) File "C:\Users\Bitswits 3\Desktop\Maala\MaalaWeddings\userfiles\views.py" in form_valid 120. obj.user_relation = request.user Exception Type: NameError at /Personadd/ Exception Value: global name 'request' is not defined Views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import * from django.contrib.admin.views.decorators import staff_member_required from .forms import * from django.shortcuts import * from .models import * from django.contrib.auth.forms import * from django.http import * from datetime import * from django.contrib.auth import * from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.views.generic import … -
Django test assertTemplateUsed with included templates
I have a base.html which includes a lot of .html templates. While testing for the correct template, the test fails because the response lists all of the templates used as includes in base.html. But the one which is used is also in the list. Here my code and the error from the test: response = self.client.get(reverse('ListAccounts')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response=response, template_name='/backstage/account/list_accounts.html') The test message: AssertionError: False is not true : Template '/backstage/account/list_accounts.html' was not a template used to render the response. Actual template(s) used: backstage/account/list_accounts.html, backstage/base.html, backstage/partials/header_mobile.html, backstage/partials/header_topbar.html, backstage/partials/header_topbar_menu.html, backstage/partials/header_topbar_search.html, backstage/partials/header_topbar_notifications.html, backstage/partials/header_topbar_quickactions.html, backstage/partials/header_topbar_cart.html, backstage/partials/header_topbar_language.html, backstage/partials/header_topbar_userbar.html, backstage/partials/aside_menu.html, backstage/partials/sub_header.html, backstage/partials/generalModal.html, backstage/partials/footer.html, backstage/partials/quick_panel.html, backstage/partials/filter_panel.html, toastrMessageAjax.html How can I test this ?