Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Aggregate Subquery and outer query
I've got two queries in Django, which work independently, but I can't seem to chain them together: q1 = M.objects.values('f1', 'f2').annotate(Min('timestamp')).filter(timestamp__min__gte=datetime.datetime(2020, 4, 30, 11, 6, 15, 998799)).values('f1', 'f2') q2 = M.objects.values('f2').annotate(Count('f1')) This is the SQL from the first query: SELECT `t`.`f1_id`, `t`.`f2` FROM `t` GROUP BY `t`.`f1_id`, `t`.`f2` HAVING MIN(`t`.`timestamp`) >= '2020-04-30 11:06:15.998799' ORDER BY NULL And from the second: SELECT `t`.`f2`, COUNT(`t`.`f1_id`) AS `f1__count` FROM `t` GROUP BY `t`.`f2` ORDER BY NULL If I try to chain them together: q3 = q1.values('f2').annotate(Count('f1')) I get: SELECT `t`.`f2`, COUNT(`t`.`f1_id`) AS `f1__count` FROM `t` GROUP BY `t`.`f2` HAVING MIN(`t`.`timestamp`) >= 2020-04-30 11:06:15.998799 ORDER BY NULL Which is not what I want. What I want is: SELECT `t`.`f2`, COUNT(`t`.`f1_id`) AS `f1__count` FROM (SELECT `t`.`f1_id`, `t`.`f2` FROM `t` GROUP BY `t`.`f1_id`, `t`.`f2` HAVING MIN(`t`.`timestamp`) >= '2020-04-30 11:06:15.998799' ORDER BY NULL) AS `t` GROUP BY `t`.`f2` ORDER BY NULL I'm not sure how to achieve this in either pure python/Django, with RawSQL, or with RawQuerySet. -
Query on Djago list view
I have Django list view but I want to put search based on two columns. how to implement this. User would be able to search records based on two columns in same view. -
Django urls handle slug with slash inside e.g. /main/subpage
I have this in my urls.py path('<str:slug>', views.page, name='page'), which I want to handle any links that didn't get caught above, think of the slug like a url link that can be deep like main\subpage\sub-sub-link which I can match to a page. Thing is it seems the slug will only handle one layer like \main is there a way to pipe all of that sublink info e.g. domain.com/this/that/that-that so my slug will be this/that/that-that -
Django can't access admin login page
Here's the issue - I've created my project, migrated to the database django had created, and when I run the server, everything is peachy. Then I add /admin/ to my search line and it gets me to the login window. At this point I open another command prompt window, get to the folder with my project and create a superuser. Then I try to log in using the superuser credentials, but to no avail - " This site can't be reached. 127.0.0.1 refused to connect." Now, what's interesting is that when I run the server again, it won't even let me access the admin login site. I tried different browsers, I tried remigrating, and I tried creating new superusers (with the server both running and shut down) - and got the same result. Eventually, it is only when I delete the superuser that I can access the admin page again. But if I create a new superuser, the story repeats itself. I'm at my wits end, really. Any thoughts? -
After browser closes , how do datas made by website persists?
I have went through a e-commerce website and after adding some items to cart, I closed the browser without purchasing or signing into the e-commerce website. When I reopen the website, my cart still exists with items, How did this happen ? I am working on a Django + React website, to implement the same feature shall I use local Storage Or cookie ? If cookie ,I am very new to that feature. -
django admin attribute to override error_message in modelForm Meta for Regex, and variables in error_message strings
I've got some validators defined on my ModelForm in Django Admin: class AddressesAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddressesAdminForm, self).__init__(*args, **kwargs) self.fields['unitorsuitenumber'].validators = [MinValueValidator(1), MaxValueValidator(1000)] self.fields['streetaddress'].validators = [RegexValidator(regExAlphanumericSpacesCommasPeriods)] In Meta for ModelForm, I can override the error_messages: error_messages = { 'unitorsuitenumber': { 'min_value': _('Ensure Unit/Suite Number value is at least %(limit_value)d ' + '(Current value is %(show_value)d).'), 'max_value': _('Ensure Unit/Suite Number value is not more than %(limit_value)d ' + '(Current value is %(show_value)d).'), }, 'streetaddress': { 'regexvalidator': _('Only numbers, letters, periods, spaces and dashes are allowed'), }, } Two questions: For the RegEx Validator, the error msg is not being replaced with my custom one. On the validators for Min and Max Values, I have to specify min_value and max_value for the attributes to override the message. But for the RegEx validator, which attribute do I override? Furthermore, for any given validator, how can I know the proper attribute to override for the error_message? I want to do this here in Meta, not somehow else. I see that for MinValue and MaxValue Validators, there are variables available to me in the string, %(limit_value)d and %(show_value)d. I would like to know how can I know which variables are available to me for … -
How to integrate Paypal Subscription API with Django
I have tried to integrate paypal subscription payment system with my django application. But there are some issue in API calling from backend. Option 1: url = "https://api.sandbox.paypal.com/v1/billing/subscriptions/I-VL5K5767RB6S" headers = {'Authorization': 'Bearer Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_', 'Content-Type': 'application/json'} response = requests.get(url, headers=headers) This option arise: headers {'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Content-Length': '83', 'Content-Type': 'application/json', 'Date': 'Fri, 29 May 2020 08:57:14 GMT', 'Paypal-Debug-Id': '50867574d2a79'} status_code 401 response text {"error":"invalid_token","error_description":"Token signature verification failed"} This error in option 1. Option 2: url = "https://api.sandbox.paypal.com/v1/billing/subscriptions/I-VL5K5767RB6S" headers = {'Authorization': 'Ae2UGxdThO9xMgFCSJihnhqDrv7zqTSngh6ILNc3imd6RrOM-GovHN_R0jFVL80Qm5oKhDi6rg715G9_', 'Content-Type': 'application/json'} response = requests.get(url, headers=headers) This option arise: {'Cache-Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Content-Length': '244', 'Content-Type': 'application/json', 'Date': 'Fri, 29 May 2020 08:58:50 GMT', 'Paypal-Debug-Id': '3e1641470db08'} status_code 401 response text {"name":"AUTHENTICATION_FAILURE","message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.","links":[{"href":"https://developer.paypal.com/docs/api/overview/#error","rel":"information_link"}]} This error in option 2. What will be the solution? Any one can help please? -
Django Rest Framework Doesn't Escape Html Entity
I wrote the django blog and api. When i started the postman and then wrote the api url it returns correct values except content i have issue with content content is returning &ouml . It's turkish charset &ouml=ö How can i fix this problem ? **my api/serializers.py : ** class MakaleSerializer(serializers.ModelSerializer): Yazar = serializers.CharField(source="Yazar.username") class Meta: model = Makale fields = ('__all__') def to_representation(self, instance): data = super().to_representation(instance) data['İçerik'] = strip_tags(instance.İçerik) return data my api/views.py : class MakaleRudView(APIView): def get(self, request): makale = Makale.objects.all() serializer = MakaleSerializer(makale , many=True) return Response(serializer.data) and the postman or drf(Django Rest Framework returns : { "id": 26, "Yazar": "gorkem", "Başlık": "Atatürk'ün Samsuna Çıkışı 2", "İçerik": "Atatürk'ün Samsuna çıkışı sırasında Türkiye Cumhuriyeti'nin", "Olusturma_Tarihi": "2020-05-29T09:10:43.874477+03:00", "makal_resim": null }, -
getting this TypeError: is_valid() missing 1 required positional argument: 'self'
i am getting the typeError: is_valid() missing 1 required positional argument: 'self' please make me correct where i have done the mistake def register(request): registered = False if request.method == "POST": user_form = UserForm(request.POST) profile_form = UserProfileInfoForm(request.POST, request.FILES) if user_form.is_valid() and UserProfileInfoForm.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'basic_app/registration.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}) -
Is Tensorflow_Hub Universal Sentence Encoder threadsafe?
I want to use Django server to implement natural language search with Universal Sentence Encoder (USE) and Annoy based database. The loading of USE is very slow: import tensorflow as tf import tensorflow_hub as hub module_url = "https://tfhub.dev/google/universal-sentence-encoder/4" model = hub.load(module_url) It's impossible to load pre-trained USE embedding on every browser request. The plan is to create USE instance as a global object and store in session. Each request uses the object in session to access USE object to get embedding of query sentence. Question: Is Tensorflow_hub USE thread safe when getting embeddings for queries, since there is only 1 global USE object? If running Django server in production Nginx, multiple workers will be configured. If Tensorflow is configured to use GPU, does mean only 1 worker can be configured for Nginx? If it's not thread safe, what's good design pattern can be used here? -
How can I store the variables values from views to the Django models?
In my terminal the values of name and score are displaying but how to store that two variable values into the particular model(Results). models.py: class Results(models.Model): username = models.CharField(max_length=50,default='') score = models.IntegerField(null=True,blank=True) views.py: def html2(request): name = request.GET.get('name') scores = request.GET.get('scores') print(name, scores) return render(request,'quiz/html/html2.html') Terminal: [29/May/2020 13:15:22] "GET /api2/?format=json HTTP/1.1" 200 1467 Pavana 40 I tried this statement but it is displaying the not null constraint error so I deleted that statement save_data = Results.objects.create(username =name, score=scores) How can I store the name and scores into the Results model. -
django.urls.exceptions.NoReverseMatch: Reverse for 'new_entry' with arguments '(1,)' not found. 1 pattern(s) tried: ['new_entry/$']
I am currently working on a tutorial in the "Python Crash course" Book. The tutorial is about creating a "Learning Log" Webapp with Django. The idea of the app is to allow users to: 1. create "Topics" they have learned about 2. add "Entries" to those Topics, describing details they have learned specific to those topics I am currently stuck at editing an existing Entry form and receive an Error, when I run http://127.0.0.1:8000/topics/2/ forms.py file from django import forms from .models import Topic,Entry class Topicform(forms.ModelForm): class Meta: model = Topic fields =['text'] labels = {'text' :''} class Entryform(forms.ModelForm): class Meta: model = Entry fields =['text'] labels = {'text' :''} widgets = {'text' : forms.Textarea(attrs={'cols':80})} urls.py file from django.conf.urls import url from . import views app_name='learning_logs' urlpatterns=[ #Home page url(r'^$',views.index,name='index'), #Show all topics page url(r'^topics/$',views.topics,name='topics'), #Detail page for a single topic url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'), #Page for adding a new topic url(r'^new_topic/$',views.new_topic,name='new_topic'), #Page for adding a new entry url(r'^new_entry/$',views.new_entry,name='new_entry'), #Page for editing an entry url(r'^edit_entry/(?P<entry_id>\d+)/$',views.edit_entry,name='edit_entry'), ] views.py file from django.http import HttpResponseRedirect from django.urls import reverse from django.shortcuts import render from .models import Topic,Entry from .forms import Topicform, Entryform --snip-- def edit_entry(request,entry_id): entry = Entry.objects.get(id=entry_id) topic=entry.topic if request.method != 'POST': # No data … -
How to display certain part of chart.js as dotted while rest as bold?
I want to display the last block of the line chart (from 2020/05/27 to 2020/05/29) as a dotted line with different color as compared to rest of the chart. In short I want to highlight the last block of the chart readings than the rest. PFA the chart screenshot for reference: Please guide me in the right direction. var ctx = document.getElementById('myChart').getContext('2d'); var data_array = [307.65, 309.54, 307.71, 314.96, 313.14, 319.23, 316.85, 318.89, 316.73, 318.11, 319.55]; var myChart = new Chart(ctx, { type: 'line', data: { labels: ['2020/05/13', '2020/05/14', '2020/05/15', '2020/05/18', '2020/05/19', '2020/05/20', '2020/05/21', '2020/05/22', '2020/05/26', '2020/05/27', '2020/05/29'], datasets: [{ label: 'Count', data: data_array, lineTension: 0, borderColor: [ 'rgba(255, 99, 132, 1)', ], borderWidth: 5 }] }, options: { scales: { yAxes: [{ ticks: { min: Math.round(Math.floor(Math.min.apply(this, data_array) - 50) / 10) * 10, max: Math.round(Math.floor(Math.max.apply(this, data_array) + 50) / 10) * 10 } }] } } }); <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <canvas id="myChart" width="1000" height="1000"></canvas> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> -
How to restart apache2 service through jenkins build
While setting up deployment through jenkins for my django project, I got stuck where I had to restart apache2 service to reflect the new changes to the client side. I am not sure how to provide user password after running systemctl reload apache2.service command. I tried below options but no luck. 1) systemctl reload apache2.service Result: Failed to reload apache2.service: Interactive authentication required. See system logs and 'systemctl status apache2.service' for details. Build step 'Execute shell' marked build as failure 2) sudo systemctl reload apache2.service Result : sudo: no tty present and no askpass program specified Build step 'Execute shell' marked build as failure 3) Also not sure whether sshpass will help in this case Attached screenshot taken from jenkins job. -
Djano Rest Framework Html Entity issue
I wrote the django blog and api. When i started the postman and then wrote the api url it returns correct values except content i have issue with content content is returning &ouml . It's turkish charset &ouml=ö How can i fix this problem ? -
python django requests.get() vs jquery ajax session is returned in ajax but not in requests.get()
whenever i am calling a url of django to get response it returns session data if calling from ajax and returns no data of session if called from request.session python: api_call=requests.get('http://www.localhost.com/restapi/authlogin/') user_data = json.loads(api_call.content.decode('utf-8')) request.session['userdata'] = user_data['data'] return HttpResponse(request.session['userdata']) jquery : $.ajax({ method: "GET", url: "http://www.localhost.com/restapi/authlogin/", async:false, dataType:'json', }) .done(function( response ) { if(response['error_code']=='0'){ $rootScope.usersessiondata =response['data']; }else{ $rootScope.usersessiondata ='False' ; } }); -
Pass method from child component to parent component in vuejs
Can someone help me with passing a function from the child component to the parent component? I am calling a modal in parent component . Inside component there are two buttons cancel and submit. I want to close the child component after clicking on the submit or cancel buttons. I tried to close the modal by declaring "show" in data, It makes the style display=None and makes the modal disappear but I am not able to scroll the screen after that. Parent component <div> <modal-dialog v-if="show" id="showCommentEffortBox"> <input type="button" value="Cancel" @click="show=false"> <input type="button" value="Submit" @click="show=false"> </modal-dialog> data() { return { show: true } } Child component <template> <transition name="modal"> <div class="modal fade" tabindex="-1" data-backdrop="static" data-keyboard="false"> <div class="modal-dialog" style="max-width: 95%"> <div class="modal-content" style="max-height: 90vh;"> <header class="modal-header"> <slot name="header"> </slot> </header> <section class="modal-body" style="overflow-y: auto"> <slot name="body"> </slot> </section> </div> </div> </div> </transition> </template> <script> export default { ***** } </script> Thanks in Advance -
Django problem with foreginKey in templates
I am started learning Django and I have question. I have code like this: from django.db import models from django.utils import timezone class Worker(models.Model): firstname = models.CharField(max_length = 32, blank=False, null=False) lastname = models.CharField(max_length = 32, blank=False, null=False) class Computer(models.Model): TYPE = { (0, 'PC'), (1, 'Laptop'), } workerId = models.ForeignKey(Worker, on_delete=models.SET_NULL, blank=True, null=True) prod = models.CharField(max_length = 32, blank=False, null=False) type = models.PositiveSmallIntegerField(default=0, choices=TYPE) What I should do in views and templates if I want to do list with workers and theirs computers? One computer can be for one user or for no one but one worker can have a few computers. My template for this look like: {% block site %} {% for work in worker %} <p>{{ work.id }} {{ work.fullname }} {{ work.lastname }}</p><br> {% if comp.workerId == work.id%} {{ comp }} {% else %} <p>Empty</p> {% endif %} {% endfor %} {% for c in comp %} <p>{{ c }}</p> {% endfor %} {% endblock %} But I always have "Empty". Thanks for help -
How to filter a particular category in Django for the blog?
How to filter a particular category in Django for the blog? I have written the following code, you can mainly focus on views.py urls.py- urlpatterns = [ path('', views.homepage, name="home"), url(r'^News/', views.News, name="News"), url(r'^Android/', views.android, name="android"), url(r'^PC/', views.PC, name="PC"), url(r'^MachineLearning/', views.MachineLearning, name="Offers"), url(r'^Offers/', views.Offers, name="Offers"), url(r'^Gaming/', views.Gaming, name="Gaming"), url(r'^Others/', views.Others, name="Others"), path('create/', views.article_create, name="create"), url(r'^(?P<slug>[\w-]+)/$', views.article_detail, name="detail"), url(r'^(?P<slug>[\w-]+)/edit/', views.article_update, name="post_edit"), url(r'^(?P<slug>[\w-]+)/edit/post_edit', views.article_update, name="post_edit"), url(r'^(?P<slug>[\w-]+)/delete/', views.article_delete, name="delete_post"), ] models.py- class Home(models.Model): title = models.CharField(max_length=100) tag1 = models.CharField(max_length=100, default='Tech') tag2 = models.CharField(max_length=100, default='Android') tag3 = models.CharField(max_length=100, default='Best') tag4 = models.CharField(max_length=100, default='News') tag5 = models.CharField(max_length=100, default='PC') slug = models.SlugField(max_length=250, null=True, blank=True) body = models.TextField() CATEGORY_CHOICES = [ ('NEWS', 'News'), ('ANDROID', 'Android'), ('PC', 'PC'), ('Machine Learning', 'Machine Learning'), ('OFFERS', 'Offers'), ('OTHERS', 'Others'), ('GAMING', 'Gaming'), ] category = models.CharField( max_length=20, choices=CATEGORY_CHOICES, default='OTHERS', ) link = models.URLField(blank=True) date = models.DateTimeField(auto_now_add=True) pub_date = models.DateTimeField(auto_now_add=True) thumb = models.ImageField(default='default.png', blank=True) thumbnail = CloudinaryField('image') author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) def __str__(self): return self.title def snippet(self): return self.body[:100]+'...' def get_absolute_url(self): return '/' + self.title views.py- def Others(request): homeblog_list = Home.objects.all().order_by('-date') paginator = Paginator(homeblog_list, 10) page = request.GET.get('page') homeblog = paginator.get_page(page) return render(request, 'home/Others.html', {'articles': homeblog}) Now, in views.py I want to fetch only the "Others" category in < Home.objects.all().order_by('-date') > this … -
Django 1.11 and djangorestframework 3.9.2 'django.template.response.ContentNotRenderedError:
HTTPServerRequest(protocol='http', host='mywebsite', method='GET', uri='/api/v1/lanManagerOptions?routerId=1', version='HTTP/1.0', remote_ip='127.0.0.1', headers={'X-Forwarded-Proto': 'http', 'Host': 'mywebsite', 'Connection': 'close', 'X-Request-Id': 'dacd3c74a93922893b2009c24a3c4bed', 'X-Real-Ip': '65.153.116.34', 'X-Forwarded-For': '65.153.116.34', 'X-Forwarded-Host': 'mywebsite', 'X-Forwarded-Port': '443', 'X-Scheme': 'https', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0', 'Accept': 'application/vnd.api+json; charset=utf-8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/vnd.api+json; charset=utf-8', 'Origin': 'https://dcm-fbar-temp6-3707.dcm.public.aws.mywebsite.com', 'Referer': 'https://dcm-fbar-temp6-3707.dcm.public.aws.mywebsite.com/dcm.html', 'Cookie': '_ga=GA1.2.1664587868.1582810494; experimentation_subject_id=ImQ0NjI4N2VlLTI4MmYtNDQzYS1iOTAxLWMwOTA5MzU4MWVlNiI%3D--cb04922dd4b62d7113de78a524ca37a8316e0779; _gid=GA1.2.1519592971.1590643532; sessionid=wmxk23fb5j3r7qwzr7s0hk0tm64xhb24; jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJIazFJM2VsOG1sY3V6RVFkIiwianRpIjoiNzI1OTBkNjktYTBlZS00NThhLTliZmYtNzkyN2RjNjE5ZmMyIiwiZmlyc3ROYW1lIjoiQm9vdHN0cmFwIiwibGFzdE5hbWUiOiJBZG1pbiIsImVtYWlsIjoiYWRtaW5AdGVzdDEyMy5jb20iLCJ0ZW5hbnRJZCI6InRlc3QxMjMiLCJhdXRoeiI6eyJlY20iOiJodHRwOi8vYWNjb3VudHMtd2Vic2VydmVyLmJzaHJlc3RoYS10ZW1wNi0zNzA3OjQ0My9hcGkvdjEvdXNlckF1dGhvcml6YXRpb25zL0hrMUkzZWw4bWxjdXpFUWQ6NzI1OTBkNjktYTBlZS00NThhLTliZmYtNzkyN2RjNjE5ZmMyOmVjbToxamVZdnQ6SmtfZ1pJcTdcmWJnSW5hd1l0cjR4MElSaXNJIiwiYWNjIjoiaHR0cDovL2FjY291bnRzLXdlYnNlcnZlci5ic2hyZXN0aGEtdGVtcDYtMzcwNzo0NDMvYXBpL3YxL3VzZXJBdXRob3JpemF0aW9ucy9IazFJM2VsOG1sY3V6RVFkOjcyNTkwZDY5LWEwZWUtNDU4YS05YmZmLTc5MjdkYzYxOWZjMjphY2M6MWplWXZ0OlZfZ2ZhR0t1Rm80UFhXRThiYmFrSF9TUndNbyJ9LCJzeXN0ZW1Sb2xlIjoicm9vdEFkbWluIiwiZXhwIjoxNTkwNzM2MjU3LCJpc3MiOiJodHRwczovL2FjY291bnRzLWJzaHJlc3RoYS10ZW1wNi0zNzA3Lm5jbS5wdWJsaWMuYXdzLmNyYWRsZXBvaW50ZWNtLmNvbSIsIm5iZiI6MTU5MDczNTM1NywiaWF0IjoxNTkwNzM1MzU3LCJ0eXBlIjoidXNlciJ9.cxfdx_a-h3YGiAtVtVFPRyUp3S4mXOPK9IiN81xA3sNmjd0spag0IG2dUW1FCkV3q-A4FHFrzpI_L6w-k3nRzF4Vcgw0spRqLNjKtQqFn6hrFu1YnRR-KBWnbOdYdNArK69MIi7MeuOO2cifCKVOtbQ12RCGetUrsFjB6M3Ov1mMoFaf--qCju8TLlSgwWLTqq8LsWhf8b7ZwUvIU3s7ZlKV2BUIeViqY03cp4X-3PMfdrGYtb3wiUwOt2evZm-jbX3j9QRpTJx3LBDq14zzaifV9J3n0d1LH0se6Ub-irWKP5APoyDpIxzGPi9qIlFU4DXZyMFsSAIpBPShI1KHDA; _gat=1'}) Traceback (most recent call last): File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/web.py", line 1511, in _execute result = yield result File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/gen.py", line 1055, in run value = future.result() File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/concurrent.py", line 238, in result raise_exc_info(self._exc_info) File "", line 4, in raise_exc_info File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/tornado/gen.py", line 1069, in run yielded = self.gen.send(value) File "", line 6, in _wrap_awaitable File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 280, in get await self._handle_request(*args, **kwargs) File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 272, in _handle_request response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 179, in get_response response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 44, in middleware_mixin__call__ response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 44, in middleware_mixin__call__ response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 44, in middleware_mixin__call__ response = await response File "/home/fbar/Workspace/projects/src/services/tornado_django_application.py", line 45, in middleware_mixin__call__ response = self.process_response(request, response) File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/django/middleware/common.py", line 139, in process_response response['Content-Length'] = str(len(response.content)) File "/home/fbar/Workspace/projects/packages_venv/lib/python3.6/site-packages/django/template/response.py", line 129, in content 'The response content must be rendered before it … -
django dynamic query set filtering with using string from URL
is there any way we can filter the queryset dynamically i.e we have a two string value from the url and search the model where first string is an attribute of the model and get all the objects containing second string in that particular attribute -
creating django model for review gives this msg
When i try to create the reviews table, i get the the following error message. The models.py and error message in the terminal is mentioned below. models.py class reviews(models.Model): reviewee = models.ForeignKey('Person', on_delete=models.CASCADE) reviewer = models.ForeignKey('Person', on_delete=models.CASCADE) review = models.TextField() rating = models.FloatField() class Person(models.Model): email = models.CharField(max_length=30) pwd = models.CharField(max_length=30) type = models.CharField(max_length=30) terminal output SystemCheckError: System check identified some issues: ERRORS: pfapp.reviews.reviewee: (fields.E304) Reverse accessor for 'reviews.reviewee' clashes with reverse accessor for 'reviews.reviewer'. HINT: Add or change a related_name argument to the definition for 'reviews.reviewee' or 'reviews.reviewer'. pfapp.reviews.reviewer: (fields.E304) Reverse accessor for 'reviews.reviewer' clashes with reverse accessor for 'reviews.reviewee'. HINT: Add or change a related_name argument to the definition for 'reviews.reviewer' or 'reviews.reviewee'. System check identified 2 issues (0 silenced). The logic behind my models is that on person can review another person. Also, when either reviewer or reviewee is deleted from the table, the review should also be deleted. i hope you got my idea. -
i am building a django projects using a medium blogpost, i cannot understand the purpose of these three lines of code
this application is a order manager and I am new to django therefore i do not know what these line of code do so please help me understand what this piece of code is used for objects = models.Manager() browser = ProductManager() tag_final_value.short_description = 'Value' this my models.py file class Product(models.Model): title = models.CharField(max_length=150, unique=True) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) active = models.BooleanField(default=True) value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10) discount_value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10) final_value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10) qty = models.PositiveIntegerField(default=0) objects = models.Manager() browser = ProductManager() class Meta: verbose_name_plural = 'Products' def save(self, *args, **kwargs): self.final_value = self.discount_value if self.discount_value > 0 else self.value super().save(*args, **kwargs) def __str__(self): return self.title def tag_final_value(self): return f'{CURRENCY} {self.final_value}' tag_final_value.short_description = 'Value' this my managers.py file from django.db import models class ProductManager(models.Manager): def active(self): return self.filter(active=True) def have_qty(self): return self.active().filter(qty__gte=1) -
Avoid username field creation in custom user model for django allauth
I'm using a custom user model with allauth and I need to have the username field omitted. I've already seen the docs and a whole bunch of stackoverflow answers about using ACCOUNT_USER_MODEL_USERNAME_FIELD = None but all of this still leads my database to have an username field. Now since the db still has an username field with the unique constraint set on and allauth will not put a username in the field with the aforementioned setting set to None, this causes me to face IntegrityError after the very first user creation. I know I can solve this by just having the aforementioned setting be set to 'username' but I'm curious, how do I just not make the username, because I'm never using it. My model: class CustomUser(AbstractUser): # Custom user model for django-allauth first_name = None last_name = None def delete(self): # Custom delete - make sure user storage is also purged # Purge the user storage purge_userstore(self.email) # Call the original delete method to take care of everything else super(CustomUser, self).delete() It doesn't really do much except override the delete function. This override is irrelevant in this topic but I included it just for the sake of completeness. It … -
How to write QuerySet syntax let field contains items in a list?
I know in Django I can use __icontains to query database use LIKE. name = "joe" Q(name__icontains=name) but if I have a list: name_list = ["joe", "klare"] How can I write the QuerySet syntax let the name contains "joe" or "klare"?