Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what does " get_object().highlighted " do , refferering GenericAPIView
class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = [renderers.StaticHTMLRenderer] def get(self, request, *args, **kwargs): # snippet = self.get_object() return Response(self.get_object().highlighted) -
How do I look into Django based Database for Emails or phone Validation from Angular Front End
I am working on a project consist of Django and Angular Integration. I have created RestApi in Django and receiving Data in JSON format. I added Resgistration module in Angular in which **I want to add Validation for non repeating email and phone number which calls Django api and checks for the validation ** <-- how to do this :/ Django Model class Employee(models.Model): DESIGNATION = ( ('Admin', 'Admin'), ('PM', 'Project Manager'), ('TL', 'Team Leader'), ('Dev','Developer'), ('QA', 'Quality Analyst') ) employeeid = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone_no = models.BigIntegerField(unique=True) date_of_birth = models.DateField() email = models.EmailField(unique=True) password = models.CharField(max_length=50) designation = models.CharField(max_length=50,choices=DESIGNATION, default='Dev') dept_id = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) Django URL from which Angular receive JSON response url(r'^employee/list/$', views.employee_list), url(r'^employee/details/(?P<pk>\d+)/$', views.employee_detail), -
i try to add new products but it shows following erroe :no such table: main.auth_user__old
I tried instaling latest django and latest sqlite but the error is not solved error: OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\bhand\PycharmProjects\website\venv\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\bhand\PycharmProjects\website', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\bhand\AppData\Local\Programs\Python\Python37-32', 'C:\Users\bhand\PycharmProjects\website\venv', 'C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages', 'C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg', 'C:\Users\bhand\PycharmProjects\website\venv\lib\site-packages\pip-19.0.3-py3.7.egg'] Server time: Fri, 8 Nov 2019 12:17:12 +0000 -
How to pass one django template with a 'for loop' into another one using 'include' statement?
I am working on FAQs page where questions and answers are passed to a template sections based on their categories. I would like to reduce amount of html and use section div as a template <div id="{{id}}"> <div class="h2">{{category}}</div> {% for q in faqs %} {% if q.category == '{{category}}' %} <ul class="collapsible"> <li> <div class="collapsible-header">{{q.question}}></div> <div class="collapsible-body"><span>{{q.answer}}</span></div> <div class="divider"></div> </li> </ul> {% endif %} {% endfor %} </div> My main html contains following code: {% with id='m_faq'%} {% with category='Methodology'%} {% include 'main/faqs_section.html' %} {% endwith %}{% endwith %} I am only able to pass variables id and category. Is there a way to the for loop as well? -
Image is not acting like a link
I have wrapped my <img> in the anchor tag but it isn't acting like a link. However the <p> is acting as a link. How do I get it so that I do not need the <p> tag to be there and the image to still work as the same link? There is currently no cursor change on hovering over the image <div class="container"> {% for item in page.client_images.all %} {% image item.image fill-150x150-c100 %} <a href="{{ item.caption }}"> <img src="{{ img.url }}" class="item" alt="{{ img.alt }}"> <p>{{ item.caption }}</p> </a> {% endfor %} </div> -
sorting and ordering in custom fields in Django admin and change_list
I'm trying to add a custom ordering in Django admin change_list. I made custom fields in django admin and ordering is not straight forward as those fields are custom made and is not directly accessible from Django models.py '''class abc(BaseParamsAdmin): # change_list_template = 'admin/logistics_admin/agent_performance_today_changelist.html' list_display = ['field_engineer', 'leads_assigned','leads_rescedule', 'leads_complete', 'leads_failed', 'current_lead', 'time_spent', 'reassign', 'route'] list_display_links = None list_filter = [ManagerListFilter, RegionAutoFilter] ordering = ('_field_engineer',) search_fields = ['name'] def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} response = super().changelist_view(request, extra_context) _cl = response.context_data['cl'] # additional data on the basis of fes on page qs = _cl.result_list._clone() self.get_fe_stats(qs) extra_context['title'] = 'Control Panel' return response def get_queryset(self, request): qs = super().get_queryset(request) qs = self._filter_base(request, qs) qs = self.orders_complete.annotate(_leads_completed=Count(order_status_id__in=Orders.STATUS_COMPLETE)) qs = qs.only("id","username","name","role_id","role__id") return qs def _filter_base(self, request, qs): is_superuser = request.user.is_superuser if not is_superuser: logistic_user = CustomUserAuthMapping.get_authenticated_user(request.user.id) if not logistic_user: raise Exception('No mapping found for this Manager..') if logistic_user.user.role.id == LogisticUtils.ROLE_SR_MANAGER: region_ids = UserRegion.get_users_for_region_manger_distinct(logistic_user.user.id,LogisticUtils.ROLE_SR_MANAGER) qs = qs.filter(user_region__region_id__in=region_ids,user_region__is_active=1).distinct() else: qs = qs.filter(manager=logistic_user.user) return qs def field_engineer(self, obj): #return obj.name # url_red = reverse('admin:fe_performance', args=(obj.id,)) # return format_html('<a href="{}">{}</a>&nbsp;', url_red, obj.name) url_red = ("%s?user=%s&created_at__gte=%s&created_at__lte=%s") % (reverse('admin:logistics_admin_ordershistoryfb_changelist'), obj.id,LogisticUtils.subtractDateOnly(30),LogisticUtils.getDateOnly()) return format_html('<a href="{}">{}</a>&nbsp;', url_red, obj.name) field_engineer.admin_order_field = '_field_engineer' def leads_assigned(self, obj): #return self.orders_assign.get(obj.id, 0) order_assign = OrdersHistory.objects.filter(assign_at__date=LogisticUtils.getDateOnly(), user_id=obj.id, … -
How to Handle Exception HTTP 400 | Django Rest Framework
I tried to remove the worksheet in Google docs file. I am using Pygsheets to perform this process. There's only one sheet in that file. So we can't remove the sheet. so it will throw the Error. How i handle it Separately. Below is i tried something. but its not working def deleteWorksheets(file_name=None, sheet_name=None): try: sheet = client.open(file_name) delete_worksheet = sheet.worksheet_by_title(sheet_name) sheet.del_worksheet(delete_worksheet) except urllib.error.HTTPError: print("You can't remove") Below error is shown. How to handle it Separately . <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/ returned "Invalid requests[0].deleteSheet: You can't remove all the sheets in a document."> -
How can I get the primary key of the last insered quote?
I have 2 views: display_quote and quote_create. def display_quote(request, pk): items_quote = Quote.objects.filter(pk=pk) items_quote_line = LineQuote.objects.all().filter(num_quote_id=pk) form = QuoteLineForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() total = 0 for item in items_quote_line: total = total + item.get_price() context = {'items_quote': items_quote, 'items_quote_line': items_quote_line, 'form': form, 'total':total } return render(request, 'quote/quote_display.html', context) def quote_create(request): form = QuoteForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return render(request, 'quote/quote_create.html', {'form': form}) After creating a quote, I want to redirect to "display_quote" (the quote creted). Error obtained: The view quote.views.quote_create didn't return an HttpResponse object. It returned None instead. -
Nginx serving css, but just half of it
I just upload a website Django application on AWS using NGINX and uwsgi protocol. The website is running fine but only part of the minified version of CSS is loaded. More specificaly the part of the css which configures the footer section of the page doesn't load. But all the CSS is in the same file. NGINX conf file is something like this: `upstream django { server unix:///home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu /mysite.sock; } server { listen 8000; server_name example.com; charset utf-8; client_max_body_size 75M; location /media { alias /home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu/media; } location /static { alias /home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu/static; } location / { uwsgi_pass django; include /home/ubuntu/django-apache-nginx-uwsgi-vps-ubuntu/uwsgi_params; } } ` -
Django: Updating and Deleting objects using Django Views
The task which I am trying to achieve is to give the power to the logged-in user to update and delete their contact list via Django views. I coded all the templates and views.py functionality but has not been able to proceed forward. Here is what I was able to achieve: "views.py": @login_required def update_contact(request,contact_id=1): current_user = request.user.get_username() user = User.objects.filter(username=current_user).first() output = UserContacts.objects.filter(current_user_id=user.id) count = output.count() contact_obj =get_object_or_404(UserContacts,id = contact_id) form = UserContactForm() if request.method == "POST": form = UserContactForm(request.POST,instance=contact_obj) if form.is_valid(): form.save(commit=True) return index(request) else: print('Error Form Invalid') my_dict = {'output':output,'form':form} return render(request,'basic_app/update.html',my_dict) Here is my template for update.html for updating contact: @login_required def update_contact(request,contact_id=1): current_user = request.user.get_username() user = User.objects.filter(username=current_user).first() output = UserContacts.objects.filter(current_user_id=user.id) count = output.count() contact_obj =get_object_or_404(UserContacts,id = contact_id) form = UserContactForm() if request.method == "POST": form = UserContactForm(request.POST,instance=contact_obj) if form.is_valid(): form.save(commit=True) return index(request) else: print('Error Form Invalid') my_dict = {'output':output,'form':form} return render(request,'basic_app/update.html',my_dict) URLS.Py: app_name = 'basic_app' urlpatterns = [ url(r'^register/$',views.register,name='register'), url(r'^user_login/$',views.user_login,name='user_login'), url(r'^new_contact/$',views.new_contact,name='new_contact'), url(r'^view_contacts/$',views.view_contacts,name='view_contacts'), url(r'^update/(?P<contact_id>[\d]+)$',views.update_contact,name='update'), url(r'^delete/$',views.delete_contact,name="delete") ] Here is the error I am currently stuck with Any help would be greatly appreciated! -
Copy text after click to form field Django
I try to create something like suggested tags in stackoverflow. When user click sugested tag I try to copy this into autocomplete tag form. Im beginer in javascript. But I found this: http://jsfiddle.net/j08691/fhjzdj4z/ and try on my code but this solution don't work. In my code look like this: {% for interest in request.user.subscribed_category.all %} <a onClick="insertText(this)" href="javascript:void(0)">{{ interest.title }}</a> {% endfor %} </p> <script type="text/javascript"> function insertText(txt) { document.getElementById('id_interests').value = txt.innerHTML; } </script> -
Iterater over table rows appending a div to each row
I have table rows that look like this: {% for item in items %} <tr id="rows"></tr> {% endfor %} and bars that look like this: {% for item in items2 %} <div class='bar' id="bars"></div> {% endfor %} now I want to attach each bar to a row, the first bar to the first row and so on... For a start, I tried using fragments but I haven't been successful yet... $(document).ready(function(){ $('.rows').each(function(index){ $('.bars').each(function(index){ iBars = document.getElementById("bars"); iRows = document.getElementById("rows"); var fragment = document.createDocumentFragment(); fragment.appendChild(iBars); iRows.appendChild(fragment); }); }); }); The idea is to get all the rows and all the bars and iterate through them, while appending a bar to each row like this Django + JQuery - Iterate over table rows updating each row with json data I don't know if its because there are cells inside the rows or what but I tried different solutions and none worked. Thank you for any help -
Problem with two dynamically updated vertical lines on two charts in Chart.js
I have a problem with updating the position of vertical lines simultaneously on plots using Chart.js. What I want to do is to draw vertical line in a specifc x postion when mouse pointer is on another graph. The problem is that with the current code after moving mouse pointer over one plot in the second I have plotted line but the plot doesn't refresh, thus after moving again pointer there is a bunch of other lines. I was trying including update() option before drawing vertical lines which actually solves the problem but the whole chart is refreshed and it's very slow. Thx for the help! enter image description here Chart.defaults.LineWithLine = Chart.defaults.scatter Chart.controllers.LineWithLine = Chart.controllers.scatter.extend({ draw: function(ease) { Chart.controllers.scatter.prototype.draw.call(this, ease); if (this.chart.tooltip._active && this.chart.tooltip._active.length) { var activePoint = this.chart.tooltip._active[0], ctx = this.chart.ctx, x = activePoint.tooltipPosition().x, topY = this.chart.scales['y-axis-1'].top, bottomY = this.chart.scales['y-axis-1'].bottom; // draw line ctx.save(); ctx.beginPath(); ctx.moveTo(x, topY); ctx.lineTo(x, bottomY); ctx.lineWidth = 1.5; ctx.strokeStyle = 'black'; ctx.stroke(); ctx.restore(); // get x value var xValue = map(x, this.chart.chartArea.left, this.chart.chartArea.right, chainage_min, chainage_max); if (this.chart == graph2) { try { // graph1.update() // drastically slows down } finally { // } var activePoint = graph2.tooltip._active[0], ctx2 = graph1.ctx, x = graph1.scales['x-axis-1'].getPixelForValue(xValue) topY … -
Django CORS headers whitelist doesn't work
I'm working on an existing code base which consists of a Django backend and a ReactJS frontend. Everything is dockerized so I'm running the backend on localhost:8001 and the frontend on localhost:3000. Because I got CORS errors in the browser, I added django-cors-headers to Django. When I add CORS_ORIGIN_ALLOW_ALL = True however, I get an error saying Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘http://127.0.0.1:8001/devices/’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’). So then I added the following settings: CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http//:127.0.0.1:3000', 'http//:127.0.0.1:8001', ) But than I get an error saying CORS header ‘Access-Control-Allow-Origin’ missing Why is the whitelist not working? Am I doing something wrong here? -
How would i increment the name of the field, when field with the same name is created?
I have dropdown component on my front-end. What i am trying to do is. Every time onChange event happens i want to add selected option value as role in my backend. That works just fine for first time the option value gets selected. What i want to do is to increment the name of the Role, if it gets selected once again. If i select Developer twice, i want the second time data to be posted as Developer 1 etc... How could i accomplish this? I have been googling this for an hours, and i have not already figured it out. I have tried creating validators for my serializers, checking if object exists, then if it does incrementing it for 1, and other ways. Model address1 = models.TextField(name="address1", max_length=150, null=True) address2 = models.TextField(name="address2", max_length=150, null=True) vat = models.CharField(max_length=100, null=True) categoryname = models.CharField(primary_key=True, max_length = 100) date_created = models.DateField(null=True) is_active = models.BooleanField(null=True) is_passive = models.BooleanField(null=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='roles', on_delete=models.CASCADE) def get_owner_full_name(self): return self.owner.get_full_name() Serializer from .models import Role from core.serializers import DynamicFieldsModelSerializer, BasicSerializer from user.serializers import CustomUserSimpleSerializer class RoleSerializerBasic(DynamicFieldsModelSerializer ,BasicSerializer,): owner = serializers.ReadOnlyField(source='owner.username') # class Meta(BasicSerializer.Meta): model = Role # Model to serialize fields = ('address1', 'address2','vat','categoryname','date_created', 'owner') depth = … -
django token authentication without rest framework
I am required to make api endpoint that receive XML in post request body the XML format is given by a third party and can not be changed I can't use the rest framework because the format of the XML is not in the form which rest framework expect I decided to use traditional Django requests with xmltodict library for parsing the XML my code will be something like this in views.py: def newOrderStatus(request): if request.method == 'POST': obj = readXML(request.body) obj.save() what I want now is to authenticate the request using a bearer token is there a way to do this or do i need to write my own middleware -
Python/Django library for registering multiple SSO Identity Providers(OpenID Connect)
I'm working on a project written in Python(Django) and i recently added an SSO option for logging in with OneLogin accounts. There's already support for Microsofts Azure SSO from an earlier feature. I'm looking for a library which can somehow register different identity providers(Microsoft, OneLogin, Facebook, etc...) and then wrap the similar login logic into a single class, which would handle all the SSO login attempts mentioned above so i don't have to write a new implementation for each new SSO option added. I don't know if it's relevant but the SSO flow is authorization code flow. Is there such a library/example? -
How to resolve error The specified alg value is not allowed in django
I am trying to decode some JWT string that I have received from an authentication service but I'm getting an error The specified alg value is not allowed. What could be the issue? I verified that the algorithim I should use is HS256. When I try to decode the JWT string at https://jwt.io/ it's being decoded. code snippet try: print(jwt_value) decoded = jwt.decode(jwt_value, 'secret', algorithms=['HS256']) print(decoded) except Exception as e: print(e) JWT Settings JWT_AUTH = { # 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=36000), 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'sbp.custom_jwt.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'sbp.custom_jwt.jwt_response_payload_handler', 'JWT_SECRET_KEY': 'secret', 'JWT_GET_USER_SECRET_KEY': None, 'JWT_PUBLIC_KEY': None, 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_LEEWAY': 0, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=36000), 'JWT_AUDIENCE': None, 'JWT_ISSUER': None, 'JWT_ALLOW_REFRESH': False, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_AUTH_COOKIE': None, } -
The build failed because the process exited too early. This probably means the system ran out of memory or someone called `kill -9` on the process
I've done Django + React application. I build React code using 'npm run build' and moves that files to hosting together with Python files. I got this error on my linux server. "Browserslist: caniuse-lite is outdated. Please run next command yarn upgrade The build failed because the process exited too early. This probably means the system ran out of memory or someone called kill -9 on the process." How can fix it? Thanks. -
SVG image file not displayed when accessing it from static folder
I'm trying to display an SVG image in my html page when I embedded the SVG image itself in the html it shows the image normally but what I need is to access it as a separate file in my project like this: <img src="{% static "images/اسناد.svg" %}"> This is the SVG image code: <svg xmlns="http://www.w3.org/2000/svg" width="16" height="18.49" viewBox="0 0 16 18.49"> <g id="اسناد" transform="translate(-1672 -1932.759)"> <path id="arrow-left-solid" d="M5.4,46.273l-.47.47a.506.506,0,0,1-.717,0L.1,42.631a.506.506,0,0,1,0-.717L4.214,37.8a.506.506,0,0,1,.717,0l.47.47a.509.509,0,0,1-.008.726l-2.55,2.43H14.878a.507.507,0,0,1,.508.508v.677a.507.507,0,0,1-.508.508H2.842l2.55,2.43A.5.5,0,0,1,5.4,46.273Z" transform="translate(1672.05 1904.357)" fill="#96a2a8"/> <path id="user-solid" d="M4.923,5.626A2.813,2.813,0,1,0,2.11,2.813,2.813,2.813,0,0,0,4.923,5.626Zm1.969.7H6.525a3.826,3.826,0,0,1-3.2,0H2.954A2.955,2.955,0,0,0,0,9.284V10.2a1.055,1.055,0,0,0,1.055,1.055H8.791A1.055,1.055,0,0,0,9.846,10.2V9.284A2.955,2.955,0,0,0,6.892,6.33Z" transform="translate(1678.154 1932.759)" fill="#96a2a8"/> when I try to access it with the img tag like the first line of the code above, I got an empty image icon does anyone knows how to solve this? -
Django annotate calculated avg subquery
How to Find avg on a calculated field grouped by another field? Suppose we have a model that contains three fields: class MyModel(models.Model): section = models.CharField() num_1 = models.IntegerField() num_2 = models.IntegerField() I want to replicate the following sql behavior using django ORM: SELECT section, AVG(relation) AS relation_avg FROM (SELECT *, (num_1 / num_2) AS "relation" FROM my_model) GROUP BY section which basically calculates average value of a calculated field grouped by section field. -
How to stop django-ckeditor adding <br /> tages in a list
I'm using django-ckeditor as a RichTextEditor within a project. When I create a bulleted list, it looks fine within the editor but when it is displayed on a web page additional <br /> tags have been added between items on the list. So html code that looks like this within the ckeditor source: <ul> <li>Commit to improving your business</li> <li>Make it happen</li> <li>Get recognition for your achievements</li> </ul> looks like this on the webpage <ul style=""> <br> <li>Commit to improving your business</li> <br> <li>Make it happen</li> <br> <li>Get recognition for your achievements</li> <br> </ul> How do I stop the being generated? -
Django i18n only pt_pt and pt_br does not work
I have a project that is translated to a lot of languages, among them zh_hans, en_us and en_gb. These languages work fine but for some reason pt_pt and pt_br translations do not work at all, although the "search" button is translated to "pesquisar", so probably only my locale files are not read. Strangely, the languages work fine in local development in unix, they only don't work on the linux server. Where can I debug this? What could be the problem? -
How to use -*-_DB_SHORT_LIVED_SESSIONS configuration setting
What does "-*-" represent in -*-_DB_SHORT_LIVED_SESSIONS (Django-specific) Celery setting. I need short lived sessions but I don't understand what am I supposed to replace -*-. I can't find it in the documentation neither The Django-specific doc is here: Django-specific Celery settings doc -
How to do multiprocessing with a Django management command?
I have a Django management command that I can run so: "python manage.py updateprices" and performs this query: activos = SearchTag.objects.filter(is_active=True) I would like to split commands like this over smaller chunks of my database e.g. activos[0:2000] at the same time, so I speed up the process How can I do that?