Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django markdown show_preview feature throws an error
I am new using markdown. I tried to use the show_preview = False to implement preview using jQuery instead. class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget(show_preview=False)) publish = forms.DateField(widget = forms.SelectDateWidget) class Meta: model = Post fields = [ "title", "content", "image", "draft", "publish", ] unfortunately, it throws an error: line 9, in PostForm content = forms.CharField(widget=PagedownWidget(show_preview=False)) TypeError: __init__() got an unexpected keyword argument 'show_preview' I did look into the markdown files and could not find show_preview using except here: 4 <textarea {{ attrs|safe }}>{{ body }}</textarea> 5 </div> 6 {% if show_preview %} 7 <p class="wmd-preview-title"> 8 <small>HTML Preview:</small> I am running: Django==2.2.6 django-markdown-deux==1.0.5 django-pagedown==2.0.3 -
the JSON object must be str, bytes or bytearray, not 'generator'
I have made a program of scraping data from two url : { "url" : "https://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168#.XaA9cEZKiUk" , "svgurl":"https://www.amcharts.com/wp-content/themes/amcharts4/css/img/icons/weather/animated/cloudy.svg" } the first one just information text and the seconde one to store the svg data so i want to execute two function in the same time without using thread using instead asyncio My Goal is to transform synchronous python code to Asynchronous code this is what i have made for that : from django.shortcuts import render import requests import json from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.http import JsonResponse from django.core.serializers import serialize import urllib.parse as urlparse import base64 from cairosvg import svg2png from rest_framework.decorators import api_view requests.packages.urllib3.disable_warnings() # Create your views here. from bs4 import BeautifulSoup import asyncio @api_view(["POST"]) def Post(request): global srcsnapcodeimg,soup,tonight,sourcesvg body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) url = body['url'] urlsvg=body['svgurl'] source = requests.get(url).text sourcesvg=requests.get(urlsvg).text soup = BeautifulSoup(source, "html.parser") seven_day = soup.find(id="seven-day-forecast") forecast_items = seven_day.find_all(class_="tombstone-container") tonight = forecast_items[0] loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) tasks = [ asyncio.ensure_future(Getvalues()), asyncio.ensure_future(Get_bin_img())] loop.run_until_complete(asyncio.wait(tasks)) print(Get_bin_img()) Getvalues_dict = json.loads(asyncio.wait(Getvalues())) data={"period":Getvalues_dict['period'] ,"short_desc":Getvalues_dict['short_desc'],"temp":Getvalues_dict['temp']} #print(data) return JsonResponse(data) @asyncio.coroutine def Getvalues(): period = tonight.find(class_="period-name").get_text() short_desc = tonight.find(class_="short-desc").get_text() temp = tonight.find(class_="temp").get_text() datanameboxandprice={"period":period,"short_desc":short_desc,"temp":temp} return json.dumps(datanameboxandprice) @asyncio.coroutine def Get_bin_img(): svg2png(bytestring=sourcesvg,write_to='output.png') with … -
JavaScript - How to print http response on stdout?
Django backend setting has # CORS Settings CORS_ORIGIN_ALLOW_ALL = True mocha is running acceptance tests for Django backend, where one of the test case is: describe('Cross Origin Requests', function(){ var result; before(function() { result = request('OPTIONS', url) .set('Origin', 'http://someplace.com') .end(); }); it('should return the correct CORS headers', function(){ return assert(result, "header").to.contain.all.keys([ 'access-control-allow-origin', 'access-control-allow-methods', 'access-control-allow-headers' ]); }); it('should allow all origins', function(){ return assert(result, "header.access-control-allow-origin").to.equal('*'); }); }); function assert(result, prop){ return expect(result).to.eventually.have.deep.property(prop) } Test case should allow all origins fails with below error: should allow all origins: AssertionError: expected { Object (_events, _eventsCount, ...) } to have deep property 'header.access-control-allow-origin' at /home/mohet01-ubuntu/git/CDelivery/todobackend-specs/node_modules/chai-as-promised/lib/chai-as-promised.js:302:22 at tryCatcher (node_modules/bluebird/js/release/util.js:16:23) at Promise._settlePromiseFromHandler (node_modules/bluebird/js/release/promise.js:547:31) at Promise._settlePromise (node_modules/bluebird/js/release/promise.js:604:18) at Promise._settlePromise0 (node_modules/bluebird/js/release/promise.js:649:10) at Promise._settlePromises (node_modules/bluebird/js/release/promise.js:729:18) at _drainQueueStep (node_modules/bluebird/js/release/async.js:93:12) at _drainQueue (node_modules/bluebird/js/release/async.js:86:9) at Async._drainQueues (node_modules/bluebird/js/release/async.js:102:5) at Immediate.Async.drainQueues [as _onImmediate] (node_modules/bluebird/js/release/async.js:15:14) at processImmediate (internal/timers.js:439:21) http://someplace.com is a dummy origin header value 1) How to print result on stdout? to verify the error... 2) Why expect(result).to.eventually.have.deep.property(prop) fails? for this test case should allow all origins -
Django redirect if User has created object
in my model the USER will create the object startup_name, however, i want to carry out a check when user click the button again that of he has created the object so he will be redirected to another page. class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) class startupform(forms.ModelForm): class Meta: model = Startup fields = ('startup_name',) widgets = { 'startup_name': forms.TextInput(attrs = {'class':'form-control'}), } def clean(self): super ( ).clean ( ) startup_name = self.cleaned_data.get ( 'startup_name' ) startup_qs = Startup.objects.filter ( startup_name = startup_name ) if startup_qs.exists ( ): raise forms.ValidationError ( 'This Startup Already Exist!' ) @login_required def create_startupform(request) : if request.method == 'POST' : form = startupform ( request.POST ) if form.is_valid ( ) : result = form.save ( commit = False ) result.author = request.user result.save ( ) return redirect ( 'test', startup_id = result.pk) else : form = startupform ( ) return render ( request , 'str_name.html' , { 'form' : form } ) -
Graphene-Django and many to many relationship lookup
I have two Django models - Teacher and Student and have a many-to-many relationship. Teachers can have multiple students and students can have multiple teachers. There is 'through' model called 'Remarks' where a teacher can mark a student as favourite. I am new to GraphQL. I am trying to implement two queries: 1. Teachers and all of their students 2. Teachers and their favourite students I am having difficulty in implementing the second query and have been unable to do so. models.py SUBJECTS = ( ("Maths", "Maths"), ("Chemistry", "Chemistry"), ("Physics", "Physics") ) class Student(models.Model): name = models.CharField(max_length=100) age = models.IntegerField(default=0) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=100, choices=SUBJECTS) students = models.ManyToManyField(Student, through="Remarks") def __str__(self): return self.name class Remarks(models.Model): student = models.ForeignKey(Student, related_name="student", on_delete=models.DO_NOTHING) teacher = models.ForeignKey(Teacher, related_name="teacher", on_delete=models.DO_NOTHING) favorite = models.BooleanField(default=False, choices=( (True, "Yes"), (False, "No") )) schema.py import graphene from graphene import relay, ObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Teacher, Student, Remarks class RemarkNode(DjangoObjectType): class Meta: model = Remarks filter_fields = ['favorite'] interfaces = (relay.Node, ) class TeacherNode(DjangoObjectType): favorite = graphene.Field(RemarkNode) class Meta: model = Teacher filter_fields = ['name', 'subject'] interfaces = (relay.Node, ) class StudentNode(DjangoObjectType): class Meta: … -
Django unittest assertRedirects explanation of work
I need explanation of work assertRedirects function. My view: def login_view(request): if request.user.is_authenticated: return redirect('account:profile') else: form = UserLoginForm(request.POST or None) if request.method == 'POST': if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is None: messages.error(request, 'something.') else: if user.is_active: login(request, user) next_url = request.POST.get('next', reverse('account:profile')) return HttpResponseRedirect(next_url) else: messages.error(request, 'something') else: messages.error(request, 'something.') context = {'form': form, 'next': request.GET.get('next')} return render(request, 'account/login.html', context) Now I wrote 2 tests. def test_login_view_valid_data_username(self): path = reverse('account:login') response = self.client.post(path=path, data={'username': 'test123', 'password': 'everything123'}) # is logged self.assertTrue(self.user.is_authenticated) # is redirect and good redirected self.assertRedirects(response, reverse('account:profile')) My view pass this test. My second test: def test_redirect_url_if_not_login(self): path = '{}?next={}'.format(reverse('account:login'), reverse('orders:create')) response = self.client.post(path=path, data={'username': 'test123', 'password': 'everything123', 'next': reverse('orders:create')}) print('RESPONSE CODE', response.status_code) print('RESPONSE URL', response.url) self.assertRedirects(response, reverse('orders:create')) And here I have problem. I get error: AssertionError: 302 != 200 : Couldn't retrieve redirection page '/orders/create/': response code was 302 (expected 200) but my response code and response url is correct to reverse path. I'm little bit confusion, because is not the first case like this. Is there any formal explanation of this? Thanks for any answer Magnus -
Date type field in Django template
I have custom form in template file. [form] input type="date" value={{info.from_date|date:'Y-m-d'}} [/form] Here info.from_date is context data. In this case in FORM on page, date is always showing in format 'dd-mm-yyyy' But i want in 'mm-dd-yyyy'. So how to change this format. Please any body share any idea ! -
Issue with UTC Datetime conversion
I am gathering appointment times from clients in a Django application and creating a combined date using datetime. I pass the timezone name through a hidden field on the form and convert my naive time to the client's correct timezone so I can then convert it to UTC (which is what my DB uses). However, something is going wrong, extra time is randomly added to the final time, and it seems the actual days are getting messed up as well. What am I doing incorrect? combined_time = datetime.combine( make_aware(datetime.strptime(str(dict_to_update['appointment_date']), '%Y-%m-%d')), # set time to utc so timezone conversion still works make_aware(datetime.strptime(str(dict_to_update['appointment_time']), '%H:%M')).time(), tzinfo=timezone(request.POST.get('tz')), ) print(1, combined_time.tzinfo) # 1 America/New_York print(2, combined_time) # 2 2019-10-21 09:00:00-04:56 --correct time selected print(3, combined_time.utcnow()) # 3 2019-10-11 13:44:47.393057 -
How to merge queryset into a single result without any repetation?
I have the following queries: group_debit_positive = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='Yes',base_group__group_ledger__closing_balance__gt=0).annotate( total_debit_positive=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0)), total_debit_negative=Sum(0,output_field=FloatField()), total_credit_positive=Sum(0,output_field=FloatField()), total_credit_negative=Sum(0,output_field=FloatField())) group_debit_negative = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='Yes',base_group__group_ledger__closing_balance__lt=0).annotate( total_debit_positive=Sum(0,output_field=FloatField()), total_debit_negative=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0)), total_credit_positive=Sum(0,output_field=FloatField()), total_credit_negative=Sum(0,output_field=FloatField())) group_credit_positive = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='No',base_group__group_ledger__closing_balance__gt=0).annotate( total_debit_positive=Sum(0,output_field=FloatField()), total_debit_negative=Sum(0,output_field=FloatField()), total_credit_positive=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0)), total_credit_negative=Sum(0,output_field=FloatField())) group_credit_negative = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='No',base_group__group_ledger__closing_balance__lt=0).annotate( total_debit_positive=Sum(0,output_field=FloatField()), total_debit_negative=Sum(0,output_field=FloatField()), total_credit_positive=Sum(0,output_field=FloatField()), total_credit_negative=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0))) I have performed union of all the queries: final_set = group_debit_positive.union(group_debit_negative,group_credit_positive,group_credit_negative) I want to get a single result rather then getting repetation in my union queryset. For example: whenever I am trying to print the resulted queryset for g in final_set: print(g.name,'-',g.total_credit_positive,'-',g.total_credit_negative) I am getting results like this: Sundry Creditors - 0.0 - -213075 Purchase Accounts - 0.0 - 0.0 Sundry Creditors - 95751.72 - 0. Sales Accounts - 844100.0 - 0.0 Sales Accounts - 0.0 - -14000.0 As you can see Sales Account is repeated twice. I want something like the following: Sundry Creditors - 0.0 - -213075 Purchase Accounts - 0.0 - 0.0 Sundry Creditors - 95751.72 - 0. Sales Accounts - 844100.0 - -14000.0 How to stop the repetition of results and make it into a single result. Any idea anyone how to perform this? Thank you -
How to implement create and update in one API view.?
I have a model called CarDetailsAdd and VehicleDetails (field - description), VehicleDetails is a Foreignkey to CarDetailsAdd. I am using Nested Relationship in this serializer. Using this update function, I can update existing vehicle details. Add and update runs on the same screen, depending on the UI. If the user has updated the field, it should be updated or user has added a new field, it should be added. How do I do that if the user updates and adds at the same time.? # Serializer class CarDetailsSerializer(serializers.ModelSerializer): vehicle_details = VehicleDetailsSerializer(many=True) class Meta: model = CarDetailsAdd fields = ( 'id', 'name', 'year', 'color', 'fuel_type', 'vehicle_details', ) read_only_fields = ['id'] def update(self, instance, validated_data): vehicle_data = validated_data.pop('vehicle_details') vehicle = (instance.vehicle_details).all() vehicle = list(vehicle) instance.name = validated_data.get('name', instance.name) instance.year = validated_data.get('year', instance.year) instance.color = validated_data.get('color', instance.color) instance.fuel_type = validated_data.get('fuel_type', instance.fuel_type) instance.save() for vehicle_data in vehicle_data: vehicle = vehicle.pop(0) vehicle.description = vehicle_data.get('description', vehicle.description) vehicle.save() return instance # View class CarDetailsView(APIView): permission_classes = [IsAuthenticated] def put(self, request, pk, format=None): try: car = self.get_object(pk) serializer = CarDetailsSerializer(car, data=request.data) if serializer.is_valid(): serializer.save() return Response({'response': 'Update Success', 'result': serializer.data}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except: return Response({'response': 'Oops! Something Went Wrong'}, status=status.HTTP_400_BAD_REQUEST) -
Bootstrap lines are not working in case of Ubantu 18.4
I used to make django forms by using Bootstrap lines in Windows os but after switching in to Ubantu those bootstrap codes do not affect my code <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> Please help me with this. -
Url looks okay, but doesn't match?
urls.py in objects app: from django.urls import path from . import views urlpatterns = [ path('<str:category>/<int:pk>/', views.show_object, name='show-object'), ] views.py (show_object method): def show_object(request, category, pk): URL which I hit: http://localhost:8000/objects/restaurants/23/ Response: NoReverseMatch at /objects/restaurants/23/ Reverse for 'show-object' with keyword arguments '{'pk': 23}' not found. 1 pattern(s) tried: ['objects/(?P[^/]+)/(?P[0-9]+)/$'] -
Can't work modal form with method POST in Django
Thats my first project in Django. I want to make table and add items with modal form. I use Mysql database. items which addes manually from phpmyadmin already exist on table but when i try add from modal form it cant added. views.py from django.shortcuts import render from django.http import HttpResponse from .models import Client def viewpost(request): post_list = Client.objects.all() context = { 'posts': post_list } return render(request, 'mysite/viewpost.html', context) def add_client(request):if request.method == 'POST': post = Client() post.name = request.POST.get('name') post.surname = request.POST.get('surname') post.address = request.POST.get('address') post.gender = request.POST.get('gender') post.age = request.POST.get('age') post.save() return render(request, 'mysite/viewpost.html') else: return render(request, 'mysite/viewpost.html') url.py: from django.urls import path from . import views urlpatterns = { path('', views.CiscoManager, name='CiscoManager'), path('test/', views.test, name='test'), path('viewpost/', views.viewpost, name='viewpost'), path('viewpost/#add_data_Modal', views.add_client, name='add_client'), } -
Using admin.RelatedOnlyFieldListFilter with content_type/generic relation
I have a model with a generic relation so includes these fields: content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") In my admin for this model I would like to use this: list_filter = ( ("content_type", admin.RelatedOnlyFieldListFilter), ... ) But this doesn't work... I get this exception: django.contrib.admin.utils.NotRelationField Is there a way of using a list_filter to show the app_label of the related model? -
How to install a server at home with django&postgre
Please help me to set my home PC as a server (Windows 10 + Python + Django + Postgre SQL + Anaconda) There are several instructions on how to set the server on the Internet, and surprisingly, many instructions differ from each other. I have absolutely no experience in setting a server. Probably, I’m making a stupid mistake somewhere that I can’t identify for 3 days. I am lost. I believe that most useful instructions are these (they are complete and new): https://www.codementor.io/aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e https://ostrokach.gitlab.io/post/apache-django-anaconda/ I followed the instructions and successfully downloaded the necessary modules, installed Wamp, made the changes as displayed in the guide and started it. What I see now: the Wamp icon glows green. When I load a localhost, the page loads endlessly but does not load. Wamp error log shows following: [Fri Oct 11 14:50:33.823752 2019] [core:notice] [pid 1364:tid 808] AH00094: Command line: 'c:\wamp64\bin\apache\apache2.4.39\bin\httpd.exe -d C:/wamp64/bin/apache/apache2.4.39' [Fri Oct 11 14:50:33.840681 2019] [mpm_winnt:notice] [pid 1364:tid 808] AH00418: Parent: Created child process 15052 [Fri Oct 11 14:50:34.981629 2019] [mpm_winnt:notice] [pid 15052:tid 800] AH00354: Child: Starting 64 worker threads. Project name: turiumasina path D:/Users/PycharmProjects/turiumasina/ path to wsgi: D:/Users/PycharmProjects/turiumasina/turiumasina/wsgi_windows.py (I renamed wsgi to wsgi_windows, settings file is in turiumasina/turiumasina/) I copied … -
int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor'
how to correct this error? int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor' def enrollmentform(request): id = request.GET.get('StudentID') if StudentsEnrollmentRecord.objects.filter(Student_Users=id).exists(): studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) FeesType = SchoolFeesMasterList.objects.filter(Education_Levels=StudentsEnrollmentRecord.Education_Levels) #payment = StudentsPaymentSchedule.objects.filter(Students_Enrollment_Records__in=studentenroll)"payment":payment, return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"SchoolFeesType":FeesType}) else: id = request.GET.get('StudentID') students = StudentProfile.objects.all().filter(id=id) edulevel = EducationLevel.objects.all().order_by('Sequence') payment = PaymentType.objects.all() year = SchoolYear.objects.all() gradelevel = request.POST.get('gradelevel') subj = Subject.objects.all().filter(Education_Levels=gradelevel) paymentID = request.POST.get('paymentID') sched = ScheduleOfPayment.objects.all().filter(Payment_Type=paymentID).filter(Education_Levels=gradelevel) doc = DocumentRequirement.objects.all() education = EducationLevel.objects.all().filter(id=gradelevel) payments = PaymentType.objects.all().filter(id=paymentID) return render(request, 'Homepage/EnrollmentForm.html', {"students": students, "edulevel": edulevel, "payment": payment, 'sched': sched, 'subj': subj, "year": year, "doc": doc,"education":education,"payments":payments}) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class SchoolFeesMasterList(models.Model): Education_Levels= models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True) Payment_Types = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE,blank=True) Display_Sequence = models.IntegerField(blank=True, null=True) School_Fees_Type= models.ForeignKey(SchoolFeesType, related_name='+', on_delete=models.CASCADE,blank=True) Amount = models.FloatField() Amount_Per_Unit = models.FloatField() Effectivity_Date_From = models.DateField(null=True,blank=True) Effectivity_Date_To = models.DateField(null=True,blank=True) Remark = models.TextField(max_length=500,blank=True) def __str__(self): suser = '{0.Education_Levels} {0.Courses}' return suser.format(self) This error is new to me , … -
Run StaticLiveServerTestCase on local pc and selenium in docker
For development I want to run my tests locally and selenium using selenium hub. hub: image: selenium/hub environment: GRID_BROWSER_TIMEOUT: '300' ports: - "4444:4444" firefox_node_1: image: selenium/node-firefox-debug depends_on: - hub environment: HUB_HOST: hub ports: - "5900:5900" In my test I use: class SimpleTestCase(StaticLiveServerTestCase): def setUp(self): super(SimpleTestCase, self).setUp() self.browser = webdriver.Remote(command_executor=f'http://localhost:4444/wd/hub', desired_capabilities=DesiredCapabilities.FIREFOX) def tearDown(self): self.browser.quit() super(SimpleTestCase, self).tearDown() def test_mainpage(self): self.browser.get(self.live_server_url) But in this case I get an error: selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A51325/&c=UTF-8&f=regular&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20localhost%3A51325. because firefox node do not see localhost I tried to set host to 0.0.0.0 class SimpleTestCase(StaticLiveServerTestCase): host = '0.0.0.0' And of course container do not see my pc, is there a way to do this without dockerize my Django app -
How to add destination and next parameters to the url
I am trying to execute the url with @login_required(login_url="url_address") in django views. Is this proper way to mention destination and next parameters in url. url_address = http://dev-address/user/login?destination=apps/member/change-password&next=http%3A//app.dev-address.abcvso.org/member/change-password/``` -
Celery - Memory Leak (Memory doesn't get free even after worker completed the task)
I have a atomic transaction running on celery server which consumes lot of memory but memory doesn't get free after task is completed. Solution which worked for me is to kill the celery worker after N tasks i.e. to use - CELERYD_MAX_TASKS_PER_CHILD. Is there any other solution to this problem? what should be good number to set for CELERYD_MAX_TASKS_PER_CHILD, If celery receives around 10,000 tasks per day -
Override ChoiceField with for loop in django views
I m trying to override a choicefield in forms in which i can loop through specific object in my views, But i Failed cause i only get in the template form only the last item in the list.. need some help to get all the choices i need from this object. **thats my first question and i don`t know if anything is going wrong while typing my code here to you! model.py class TourPackageBuyer(models.Model): tour = models.ForeignKey(TourPackage, on_delete=models.CASCADE, null =True) production number_choice = [(i,i) for i in range(6)] number_choice_2 = [(i,i) for i in range(18)] number_choice_3 = [(i,i) for i in range(60)] user = models.CharField(settings.AUTH_USER_MODEL, max_length=200) num_of_adults = models.PositiveIntegerField(default=0, choices= number_choice_2, null=True) num_of_children = models.PositiveIntegerField(default=0, choices= number_choice_3, null=True) hotel = models.ManyToManyField(PackageHotel, blank=True)### thats the field forms.py class TourPackageBuyerForm(ModelForm): class Meta: model = TourPackageBuyer date = datetime.date.today().strftime('%Y') intDate = int(date) limitDate = intDate + 1 YEARS= [x for x in range(intDate,limitDate)] # YEARS= [2020,2021] Months = '1', # fields = '__all__' exclude = ('user','tour','invoice','fees', 'paid_case') widgets = { 'pickup_date': SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day")), 'hotel': Select(), # 'pickup_date': forms.DateField.now(), } hotel = forms.ChoiceField(choices=[]) ### Thats the field i m trying to override views.py def TourPackageBuyerView(request, tour_id): user = request.user tour … -
Find the location of data base file that gets created when a user is created in django application
In a django application with 'postgresql' as data base ,where do the users get stored ? any file where can i check the users info...basically where will be the .db file stored in django -
how to create django form with multiplechoicefield and add those value to database
what I want to achieve is user will submit 3 inputs in the form 1) name 2) dropdown to select technician, 3) multiselect dropdown to select multiple products. Once the user submit the details it will generate one lead in database with value like name,foreignkey of selected technician and id of selected products in different table. I don't know how to achieve this below I have mentioned my approch to achieve what I want. Please let me know if the models need any changes and how I can write a view for the same. models.py class product(models.Model): name = models.CharField(max_length=20) class technician(models.Model): name = models.CharField(max_length=20) class lead(models.Model): name = models.CharField(max_length=20) technician = models.ForeignKey(technician,on_delete=models.SET_NULL,null=True) #only single selection products = models.ManyToManyField(product) #user can select multiple product in dropdown form.py class leadForm(form.ModelForm): products = forms.MultipleChoiceField(queryset=Product.objects.all()) technician = forms.CharField(max_length=30,choices=[(i.id,i.name) for i in Technician.objects.all().values('id','name') class Meta: model = lead fields = ('name','technician') -
Django reverse optional path parameters
Before anyone comments I have seen both: Django optional url parameters and How to have optional parts of a django url and reverse to it And while similar these existing questions do not answer or solve my problem. I have good reasons to attempt to use optional path parameters. In fact I have gotten it 90% working but stumbled across a seeming inconsistency between Django's Redirect (and reverse) and the {% url %} templatetag I've written a custom optional parameter: class OptionalStringConverter: regex = '((_)*[a-zA-Z]+)*' def to_python(self, value): if value: return str(value) else: return None def to_url(self, value): return str(value) if value is not None else '' register_converter(OptionalStringConverter, 'opt_str') urlpatterns = [ # url with optional params path('<opt_str:optional_a>/<opt_str:optional_b>/foo/', foo.bar, name='foo_bar'), ] Inside of the view: def bar(request, optional_a=None, optional_b=None): // do some stuff view_name = 'some:namespaced:viewname' return redirect(view_name, optional_a=optional_a, optional_b=optional_b) This gives me exactly what I want, if I manually go to http://0.0.0.0:8888/some/namespaced/foo/ http://0.0.0.0:8888/some//foo/ http://0.0.0.0:8888//namespaced/foo/ The urls all resolve nicely and the parameters entered come through nicely and more importantly the redirect also works nicely (None values get passed) But when I try reversing inside of a template with one of the following however: {% url 'some:namespaced:viewname' optional_a=optional_a optional_b=optional_b %} … -
Compare django template varaiable with javascript varaible
I am trying to populate a table in django template, but I want to compare cell values, one of them is javascript variable and another is django template variable. Is it possible to compare them without converting django variables to javascript variables? or is there a quick work around? {% for x in price_data %} <script> counter++ var VALUE =document.getElementById("price_table").rows[0].cells.item(counter).innerHTML; </script> {% if x.room_scan == i and x.checkin == VALUE %} I want to check if x.checkin is equals to VALUE. Thanks. -
django ascii error when loading to AWS elasticbeanstalk
I'm getting this error when trying to upload an update version (from python2.7 to 3.6 and Django 1.11 to 2.2) of an app to AWS Traceback (most recent call last): File "hjsm/./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/opt/python/bundle/2/app/hjsm/researcher_UI/management/commands/populate_instrument.py", line 22, in handle instruments = json.load(open(os.path.realpath(PROJECT_ROOT + '/static/json/instruments.json'))) File "/usr/lib64/python3.6/json/__init__.py", line 296, in load return loads(fp.read(), File "/opt/python/run/venv/lib64/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2029: ordinal not in range(128). This is running a ./manage.py populate_items management command. It works locally and the file doesn't seem to have any ascii issues. It also works using Pythjon2.7 and Django 1.11. I include the json file below (I do wonder if the accented French characters are the issue but then I do not understand why it is working locally): [ { "language": "English", "form": "WS", "verbose_name": "Words and Sentences", "min_age": 16, "max_age": 30, "csv_file": "cdi_form_csv/[English_WS].csv", "json_data": "cdi_forms/form_data/English_WS_meta.json", "fillable_headers": "cdi_form_csv/EnglishWS_pdf_headers.csv", "scoring_json" : "cdi_forms/form_data/scoring/English_WS_scoring.json", "benchmark" : "cdi_forms/form_data/benchmarking/English_WS_benchmark.csv" }, { "language": "English", "form": "CDI3", …