Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uvicorn running with Unicorn, how?
While reading the docs of running Uvicorn: Gunicorn is a mature, fully featured server and process manager. Uvicorn includes a Gunicorn worker class allowing you to run ASGI applications, with all of Uvicorn's performance benefits, while also giving you Gunicorn's fully-featured process management. Is doc wrong or i didn't understand correctly? from my understanding, Gunicorn has a master slave structure to allow Uvicon class(async sever) to run in separate worker classes using command: gunicorn example:app -w 4 -k uvicorn.workers.UvicornWorker why the doc says: Uvicorn includes a G unicorn worker class allowing you to run ASGI applications Someone could explain? thanks in advance! -
django raised 'function' object is not subscriptable but local python doesn't
I got a strange thing I can't handle and understand. I'm really intrigue Let me explain, I coded some stuff locally on my computer with python3 (which run like a charm !! ), I used to transfer this script to my django . And magic happen it's raised an error , I don't have when I run locally ... here is the script part which seems to create the error : from c***.utils import calculate_distance from operator import itemgetter import geopy solution = [] def is_in_radius(elem1, elem2): dict_coord = { 'pa' : (elem1[3][0],elem1[3][1]), 'pb' : (elem2[3][0],elem2[3][1]), } distance = calculate_distance(dict_coord.get('pa'), dict_coord.get('pb')) # print("distance : " + str(distance) + " m - entre : "+ str(elem1[0]) + " et " + str(elem2[0])) if (distance <= 1200): return(True) else: return(False) def last_rad(data_info, elem1, am_act): global solution if(len(solution) + 1 == am_act): if(is_in_radius(elem1, data_info[1]) == True): return(True) else: return(False) else: return(True) def first_rad(data_info, elem1): global solution if(len(solution) == 0): if(is_in_radius(data_info[0], elem1) == True): return(True) else: return(False) else: return(True) Error raised is : 'function' object is not subscriptable Request Method: POST Request URL: http://****.io/new_search Django Version: 3.1 Exception Type: TypeError Exception Value: 'function' object is not subscriptable Exception Location: /home/debian/***/mysite/**/backtrack.py, line 33, in first_rad … -
How to query multiple models in views and pass them to one template?
I am trying to make a path lab database system, Where I have models as follows: Client model: to store client name CBC test model: child to client model. Liver test model: child to client model. kidney function test model: child to client model. my purpose is that if we enter client id and date to form it goes to result page and shows all the test performed to that particular client on that date. I made a client model and models for each tests. from django.shortcuts import render from .models import client, cbc, lft, kft from django.db.models import Q # Create your views here. def index(request): return render(request, 'vmr/index.html') def result(request): client = request.POST['client'] date = request.POST['date'] r = cbc.objects.filter(Q(id = client ) & Q(Date__iexact = date)) l = lft.objects.filter(Q(id = client ) & Q(Date__iexact = date)) k = kft.objects.filter(Q(id = client ) & Q(Date__iexact = date)) context = { "results": r, "liver": l, "kidney":k} return render(request, 'vmr/result.html', context=context ) ``` My Result template for results is: {% if results %} {% for result in results%} <h3 style="padding-left: 10%;"> DATE:{{result.Date}} </h3> <table style="width:70%"> <tr> <th>PARAMETER</th> <th>UNIT</th> <th>VALUE</th> <th>RANGE</th> <th>INFERENCE</th> </tr> <tr> <td> RBC </td> <td> million/mm3 </td> <td> {{result.RBC}} … -
Django: Create linked objects by overriding the models save method
I have two models, invoice and service. What I want to achieve is that when a new service is created, the system should check is there is a draft invoice and save the service under that draft, if there is none then first create an invoice and add the service to the invoice. This is my current code class Invoice(BaseModel): patient_id = models.IntegerField(default=0) is_draft = models.BooleanField(default=True) is_billed = models.BooleanField(default=False) is_paid = models.BooleanField(default=False) paid_date = models.DateField(blank=True, null=True) class Meta: unique_together = ('patient_id', 'is_draft') class ServiceRequest(BaseModel): invoice_id = models.IntegerField(default=0) appointment_id = models.IntegerField(default=0) service_id = models.IntegerField(default=0) cost = models.DecimalField(max_digits=20, decimal_places=2) def save(self, *args, **kwargs): print(args) # create or update invoice when service is requested if not self.pk: patient_id = kwargs['patient_id'] org = kwargs['organization'] invoice = models.Invoice.objects.filter(patient_id=patient_id, is_draft=True) if invoice is not None: invoice = models.Invoice.objects.create( patient_id=patient_id ) kwargs['invoice_id'] = invoice.pk super(ServiceRequest, self).save(*args, **kwargs) In my viewset. def perform_create(self, serializer): org = self.request.user.organization appointment = serializer.save(organization=org, created_by=self.request.user) clinic = Clinic.objects.get(pk=self.request.data['clinic_id']) ServiceRequest.objects.create( patient_id=self.request.data['patient_id'], appointment_id=appointment.pk, service_id=request.data['service_id'], quantity=1, cost=clinic.appointment_fee, ) This is not working and even when I print the kwargs, I don't get the right data printed so I know am not doing it right. If anyone can point me to the right direction guys. Well … -
Django BSModalUpdateView Issue
I am trying to update a model class using BSModalUpdateView. I have a lot of update views like this without issues, but I don't know why I can't make this work. This is my view Class: class ReservaUpdateView(BSModalUpdateView): model = Reserve form_class = ReserveForm success_message = 'Success: La reserva ha sido creada.' template_name = 'panelcontrol/reserve_update_create.html' success_url = reverse_lazy('panel_control_reservas') The Form: class ReserveForm(BSModalModelForm): class Meta: model = Reserve fields = '__all__' def clean(self): #us_re = Payment.objects.filter(Q(pa_reserve__in=Reserve.objects.filter(re_renter=self.user)),\ # Q(status=PaymentStatus.WAITING)) property = self.cleaned_data.get('re_property') pr = property us_re = Payment.objects.filter(pa_reserve__re_property=pr, status=PaymentStatus.CONFIRMED).select_related('pa_reserve') #print(str(us_re.count())) """ if us_re.count() > 0: raise ValidationError("Ya tienes una reserva activa y sin pagar") """ enter_date = self.cleaned_data.get('re_enter_date') exit_date = self.cleaned_data.get('re_exit_date') print("ENTER AND EXIT DATE") print(enter_date) print(exit_date) #reserves = Reserve.objects.filter(re_property=pr) reserves = us_re extraMonth = 0 max_v = pr.p_max_stay min_v = pr.p_min_stay stance = relativedelta.relativedelta(exit_date, enter_date).months stanceDays = relativedelta.relativedelta(exit_date, enter_date).days months_year_calculation = relativedelta.relativedelta(exit_date, enter_date).years * 12 if stanceDays > 15: extraMonth = 1 stance += months_year_calculation + extraMonth if max_v == 0: max_v = sys.maxsize print("STANCE") print(stance) if stance < min_v or stance > max_v: if max_v == sys.maxsize: max_v = "sin límite" print("RAISEA 1") print('La estancia permitida es:\n\n Mínimo {0} meses/ \n\n Máximo {1} meses'.format(str(min_v), str(max_v))) raise ValidationError('La estancia permitida es:\n\n … -
Django show me Query set in terminal but not show me Query set in home page
hi I have created a search function in my views.py file that take query from user from homepage of website. I created a URL for that search function each and every thing working fine but when I search it take me to that URL but does not show me anything but it show me the Query set in terminal which I want to be printed in home.html my views.py file is def search(request): model = Post query = request.GET.get('query') if query: object_list = model.objects.filter(Q(title__icontains=query)) print(object_list) else: object_list= model.objects.filter(None) context = { 'query_list':object_list } return render(request, 'blog/home.html', context) my urls.py file is: from django.urls import path from .views import PostListView , PostDetailView , PostCreateView, PostUpdateView, PostDeleteView ,UserPostListView,TagMixin,TagIndexedView, AdminApproval from . import views urlpatterns = [ path('', PostListView.as_view() , name='blog-home' ), path('post/new/', PostCreateView.as_view() , name='post-create' ), path('post/new/admin-approval', AdminApproval.as_view() , name='admin-approval' ), path('<slug:slug>', TagIndexedView.as_view() , name='tagged' ), path('user/<str:username>', UserPostListView.as_view() , name='user-posts' ), path('post/<slug:slug>/', PostDetailView.as_view() , name='post-detail' ), path('post/<int:pk>/update/', PostUpdateView.as_view() , name='post-update' ), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='blog-about' ), path('search/', views.search, name='blog-search' ), path('contributors/', views.contributors, name='post-contributors' ), #path('search/', PostSearch.as_view(), name='post-search' ), ] my base.html file is: <form class="form-inline my-2 my-lg-0" method="get" action="{% url 'blog-search'%}"> <input class="form-control mr-sm-2" name="query" value="{{ request.GET.query}}" placeholder="Search"> <button class="btn … -
how to call django method from angular
I have a simple scenario in Django and angular. I have method in views.py which takes file as input parameter and return string as result. How can I invoke this django method from Angular and get the results. views.py class ResViewSet(viewsets.ModelViewSet): queryset = Res.objects.all() serializer_class = ResSerializer @csrf_exempt def reslt(self, image_path): //doing something with image and create result string return result urls.py urlpatterns = [ url(r'^imageUpload', ResViewSet.reslt) ] -
django-import-export: instance data not updated after save
I've got a model which allows imports via django-import-export. After the Event instances are imported I need to create related objects so I'm using after_save_instance to kick off celery tasks which reference the objects by ID. But in those tasks, when I retrieve the object from the database using the ID passed from the Resource class, I get old data. For example, the imported data changes the date value on an existing Event object and during after_save_instance the data is updated, but once the celery task retrieves the data it's different. Here's the stripped down resource class; class EventImportResource(resources.ModelResource): """ Admin importer for Events """ date = fields.Field( attribute='date', column_name='date', widget=LocalisedDateWidget( format=get_format('UK_DATE_INPUT_FORMATS') ) ) class Meta: model = Event fields = [ 'id', 'date', 'name', 'city', 'state', 'country', 'url' ] def after_save_instance(self, instance, using_transactions, dry_run): """ Override to add additional logic. Does nothing by default. """ if not dry_run: create_categories.delay(instance.id) # debugging at this point shows the new value # >>> instance.date # webapp_1 | datetime.date(2020, 10, 25) In the celery task I need to get the object from the database & perform some additional object creation etc. At this point, attributes on the instance are different to the instance … -
Should I commit static files into Git repo with Django project?
Please, should I commit and push my Django's project static files into my git repo ? I know there is collectstatic command but it's just for prod deployment right? I work on the same project from 2 different computers and then, I have static files in one that I don't have on the other. Am I supposed to collectstatic from one to the other? But I don't understand this command neither how to use it neither what it does. Thanks for helping! Best regards. -
Take URL Parameters from a Button in Django
I am trying to get url parameters like this: <tbody> {% for object in objects %} <tr> <td>{{ object.id }}</td> <td>{{ object.user }}</td> <td>{{ object.url }}</td> <td>{{ object.minimum }}</td> <td>{{ object.maximum }}</td> <td>{{ object.requests }}</td> <td>{{ object.stay }}</td> <td class="text-Centre"> <a href="{% url 'trafficapp:generate_traffic/?id={{object.id}}&?user{{object.name}}' %}" class="btn btn-danger btn-round remove">Run</a> </td> </tr> {% endfor %} </tbody> If I put my URL like this, it works since the view exists in view.py: {% url 'trafficapp:generate_traffic' %} Now, I am trying to take URL parameters with it, but I am unable to make how can I pass data from this button, and what should I put in my URL pattern for this. Kindly help, I am new to Django and still figuring out how it works. -
Django Check Current User Liked Comment
I want to check if the current logged in user has already liked a comment in the template. If it has, the like button should change styles. How do I do this in the tempalte? class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name='like', default=None, blank=True) like_count = models.IntegerField(default='0') Views: @login_required def like(request): if request.POST.get('action') == 'post': result = '' id = int(request.POST.get('commentid')) comment = get_object_or_404(Comment, id=id) if comment.likes.filter(id=request.user.id).exists(): comment.likes.remove(request.user) comment.like_count -= 1 result = comment.like_count comment.save() else: comment.likes.add(request.user) comment.like_count += 1 result = comment.like_count comment.save() return JsonResponse({'result': result}) -
One views - two forms why it returns the same forms?
I'm going to end up tearing my hair out. I don't understand why this view returns the same form (CreateSugarChatForm: which works well) for both forms. Could someone please help me? But I don't know why validation_form appears as CreateSugarChatFormlooking. @method_decorator(login_required(login_url='/cooker/login'),name="dispatch") class CheckoutDetail(generic.DetailView, FormMixin): model = Sugargroup context_object_name = 'sugargroup' template_name = 'checkout_detail.html' form_class = CreateSugarChatForm validation_form_class = LaunchSugargroupForm def get_context_data(self, **kwargs): context = super(CheckoutDetail, self).get_context_data(**kwargs) context['form'] = self.get_form() context['validation_form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.sugargroup = self.object form.instance.user = self.request.user form.save() return super(CheckoutDetail, self).form_valid(form) else: return super(CheckoutDetail, self).form_invalid(form) def form_valide(self, validation_form): if validation_form.is_valid(): validation_form.instance.user = self.request.user validation_form.save() return super(CheckoutDetail, self).form_valide(validation_form) else: return super(CheckoutDetail, self).form_invalide(validation_form) def post(self,request,*args,**kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) elif validation_form.is_valid(): return self.form_valide(validation_form) def get_success_url(self): return reverse('checkout:checkout_detail',kwargs={"slug":self.object.slug}) template {% crispy form %} {% crispy validation_form %} -
Sending files via AJAX; Request.FILES is empty?
As per title. I've created a function that would allow me to upload a file, parse it through AJAX to a Python function which then processes the file. I can either upload just an image file, or a zip file or a docx file et al. HTML: <input type="file" onchange="ProcessData(this)" id='theUpload' name='theUpload' accept="image/*,application/vnd.ms-excel, application/pdf,application/vnd.ms-word.document.macroEnabled.12,application/vnd.ms-word.template.macroEnabled.12,application/zip " style="display:none;" /> JavaScript ProcessData function(partial) function ProcessData(thisData){ thisCurrentAttachment = thisData; var formData = new FormData(); var filesizeLimit = 2097152; //2MB * 1024 * 1024 /* * Check if there is a file selected */ if (thisData.files.length==0) { document.getElementsByName("theUpload")[1].value = ""; return } underLimit=(thisData.files[0].size<=2097152); formData.append('theUpload', thisData.files[0], "Test"); if (underLimit) { $.ajax({ url: "{% url 'userProcessData' %}", type: "post", async: true, data: formData, contentType: false, processData: false, (....) Python Function def UserProcessData(request): theReqFile = request.FILES.getlist('theUpload')[0] (...) obj={"status": 0, "message": _("Success")} return JsonResponse(obj) The code works when I try it in my local server, but after deploying it to an online server, I get a list index out of range error at the point of theReqFile = request.FILES.getlist('theUpload')[0] with a Response of Server 500 To be specific, when I tried uploading both an image file as well as a zip file in my local runserver, it succeeds. On … -
uwsgi + nginx... mistake after mistake in options
I think it's a second week started since I'm trying to start the server for Django app, first with Apache, second with gunicorn and now uwsgi + nginx... I'm very thankful for the help on my previous post... nginx with gunicorn and django on centos 7 It pushed me into the right direction... I don't know why, but most of guides for the django and server are incomplete and don't include settings tuning for the engines like gunicorn and nginx... there are some... and I tried to follow them, but end up with bunch of mistakes. I followed: http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ and https://youtu.be/DzXCHAuHf0I . Very good guides, but I ended up with the bunch of mistakes, which I'm trying to fix. Any help guys? Virtual environment installed at: /opt/venv the way to activate virtual environment at: /opt/venv/sc/bin/activate Users added for both nginx and uwsgi: useradd -s /bin/false nginx/uwsgi nginx.conf: include /etc/nginx/conf.d/*.conf; virtual.conf: server { listen 80; server_name site's_ip domain_name; error_log /srv/www/sc/logs/error.log; access_log /srv/www/sc/logs/access.log; charset utf-8; location /static/ { alias /srv/www/sc/static/; } location /media/ { alias /srv/www/sc/media/; } location / { uwsgi_pass unix:/opt/uwsgi/sock/sc.sock; include uwsgi_params; } } emperor.ini: [uwsgi] emperor = /etc/uwsgi/vassals uid = uwsgi gid = uwsgi logto = /etc/uwsgi/log sc.ini: http … -
How to make a reusable "BooleanDate" field in Django?
For fields like "Accepts terms and conditions", "Authorizes newsletter sending" and so on, what I do is to use a DateTime field with null=True, but then only show a checkbox. If is null, the checkbox is unchecked. If it goes from unchecked to checked, the current date is stored. I know how to make it work, my question is: how should I approach the idea of making a custom model field that handles everything just by setting up this? newsletter_auth = BooleanDateTime("title") So then it works like I described in the admin panel, and provides the HTML representation for the front-end. Well now I realize that maybe that the right place for that is a custom widget, and in the model just set a normal DateTime field, and in the Form, specify the custom widget..? In any case, I'll appreciate recommendations to some tutorial, or some git with a clear example (I mean: if the example is too complex or is tangled amongst a thousand files' project it's probably going to be too much for me) Thanks a lot in advance! -
how to show maplotlib graph directly using django without showing it as an image?
I am trying to plot the graph using Django and matplotlib. So while plotting the graph on the Django template, I am converting matplotlib figure in png format and passing that png file to Django template. My requirement is as follows: I want to place the vertical lines on the graph, that vertical lines should be able to move left and right side horizontal on the graph. As we are passing the image on the Django template, it doesn’t seem possible to drag the vertical lines on the graph and to get the x value corresponding to it. Please suggest a way how we should be able to drag the lines and get its x axes value. Is there any direct way to plot matplotlib figure without passing it as an image? This is the code added in views.py: buffer = BytesIO() fig.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic = base64.b64encode(image_png) graphic = graphic.decode('utf-8') Html code: <img src="data:image/png;base64,{{ graphic|safe }}"> I want to do similar to this on webpage. please refer image and reference link for more detail: Draggable lines select one another in Matplotlib I want to add red marker like this which should be drag-gable. -
How to setup live django project on localhost?
Is there any way so that we can set and run django project from live server to local machine as like codeigniter projects. -
AttributeError: 'NoneType' object has no attribute 'check_password'
I saw this question was asked many times already but it's not working for me. The problem is the authenticate method always returns None. this is what i added in settings # Custom User AUTH_USER_MODEL = 'account.CustomUser' #Authentication backends AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) this is the clean method inside form class class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs=email_attr)) password = forms.CharField(widget=forms.PasswordInput(attrs=password1_attr)) class Meta: fields = ['email', 'password'] def clean(self, *args, **kwargs): cleaned_data = super(LoginForm, self).clean(*args, **kwargs) email = cleaned_data.get('email') password = cleaned_data.get('password') user = authenticate(email=email, password=password) print(user) try: CustomUser.objects.get(email=email) except CustomUser.DoesNotExist: raise forms.ValidationError({'email': 'Email is incorrect'}) if not user.check_password(password): raise forms.ValidationError({'password': 'Password is incorrect!'}) return cleaned_data views.py def loginView(request): template_name = "app/login.html" form = LoginForm() if request.user.is_authenticated: return redirect('home') if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user is not None: login(request, user) return redirect('home') return render(request, template_name, {'form': form}) error i got if not user.check_password(password): AttributeError: 'NoneType' object has no attribute 'check_password' -
Angular 8 + Django RestFramework file(csv) download
I am new to angular. I want to download a CSV, on click of download button. django viewset @action(detail=False, methods=['get']) def download_csv(self, request): data = { "student_data": [ { "roll_no": 12, "detail": { "name": "Tom", "address": "XYZ" } }, { "roll_no": 8, "detail": { "name": "Ryan", "address": "ABC" } }, { "roll_no": 12, "detail": { "name": "Tom", "address": "PQR" } } ] } response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="emp_details.csv"' writer = csv.DictWriter(response, fieldnames=['name', 'roll', 'address']) writer.writeheader() for i in data["student_data"]: meta_data = i["detail"] detail_dict = {} if len(meta_data) > 0: detail_dict["name"] = meta_data["name"] detail_dict["address"] = meta_data["address"] detail_dict["roll"] = i["roll"] writer.writerow(address) return response when i am hitting url http://localhost:8000/download_csv/ . CSV is downloaded with file name emp_details.csv. Now i want to integrate this response with anuglar. on click of download button from angular frontend, how do I subscribe to this API endpoint and download the csv file. which is the response(not usual JSON) of this end point. -
How to change Status when update form in Django?
I am working with Django form Updation, but I am facing a small issue, I have 3 fields in form updating, name, image, status, Now if a user upload a image in form then status should be change automaticly in my database. here is my forms.py file... class UpdateForm(forms.ModelForm): model = Product fields = ['name', 'image', 'status'] here is my views.py file... def myview(request, id): datas=Product.objects..get(pk=id) form = UpdateForm(instance=datas) if request.method === 'POST' form = UpdateForm(request.POST or None, request.FILES or None, instance=datas) if form.is_valid(): edit = form.save(commit=False) edit.save() return HttpResponse('Success') else: return HttpResponse('Fail') template_name='test.html' context={'datas':datas} return render(request, template_name, context) Default status is 0 in my database, If a user upload image then status should be 1 in my database, please let me guide how i can do it. -
Django group permissions not working correctly
I'm working on a project using Python(3.7) and Django(3) in which I have created a custom user model using AbstractBaseUser and also utilized PermissionsMixin. In my user model, I have created a field named is_instructor on signup if this is checked user will have the permission of the instructor group. Now if I try to use these permissions with a user which has is_active, is_instructor & is_staff it doesn't work but if I try with is_admin it works. Here are my Implementations: User model: class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email', max_length=60, unique=True) fullname = models.CharField(max_length=30, unique=True) is_instructor = models.BooleanField(default=False) date_join = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Signup view def registration_view(request): form = RegistrationForm(request.POST or None, request.FILES or None) if request.method == 'POST': print('get post req') if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() if form.cleaned_data['is_instructor'] is True: instructor_group = Group.objects.get(name='Instructors') instructor_group.user_set.add(user) return HttpResponseRedirect(reverse_lazy('users:login')) return render(request, 'users/register.html', {'form': form}) Login view: def login_user(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) … -
Why i am getting this error "Server Error(500)" in django heroku?
Everything is working fine in the application. But in predicting the model. It shows the response like Server Error(500) And the log look like this 10.171.230.57 - - [18/Sep/2020:08:42:24 +0000] "POST /"appname" HTTP/1.1" 500 145 "...." "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36" -
Django URL passing parameter
Would anyone please explain to me how to passing parameter in Django URL I created view in view.py "def hours_ahead(request, offset)" to calculate the time ahead. Then on URL.py I call it with re_path(r'^time/plus/\d{1,2}/$', hours_ahead). But I get the error message when I put the url http://127.0.0.1:8000/time/plus/2/ TypeError at /time/plus/2/ hours_ahead() missing 1 required positional argument: 'offset' -
Add context get method multiple values
I have this method in a Django view in order to receive value from the src http://url/my-view?get1=some1 def my_view(request): get1= request.GET['get1'] context = {'data':{"get1":{"value":get1}}} template_name="get.html" return render(request, template_name, context) And now I want to send multiple values to the get context http://url/my-view?get1=some1&get2=some2. I tried to reconstruct the method to receive both values like this but it doesn't accept them. def my_view(request): get1= request.GET['get1'] get2= request.GET['get2'] context = {'data':[{"get1":{"value":get1}, "get2":{"value":get2}}]} template_name="get.html" return render(request, template_name, context) Do you have any idea what structure should I use for it?? -
Django management command save output to file gives AttributeError
I'm using Django 2.2 I have written a management command to migrate user data from the previous server to the new server. The command is python manage.py migrate_all --email user@example.com Where email is passes as **options and is used to filter the queryset for the specified email of the user. Now I want to save the stdout and stderr to a file because terminal does not shows full output when the command runs for a long time. For that I'm using python manage.py migrate_all --email user@example.com |& tee -a output.txt But this is giving error as AttributeError: 'dict' object has no attribute 'endswith'