Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to use python in backent and VueJS in frontend in Django framework?
I was trying from last 5 days to connect and communicate VueJS and Django in a single project but I didn't get any useful link on internet. Please help me with Vue cdn or with Vue Cli link. Please help me with understanding how to send data from python and how should I receive that data in Vue data varibale to show that on frontend. I have triend with Vue cdn and Vue cli, along with that I have tried with Django restfull API but my data did not send from .py file to .html file -
how remove field from admin view django
I have the following model class Organizer(models.Model): name = models.CharField(max_length=100) phone = models.CharField(max_length=20, default="", blank=True) created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) I have a field created_by of all the users. I don't want to show on the front end in admin form. how to do that. and save the current login user id -
Why I get serializing error in Django Rest Framework?
I need to store comments to posts and replies to comments, but replies are also comments and both have many in common, therefore I decided to create abstract model AbstractComment and to inherit my Reply and Comment models from it. But there is a problem with serializing of Comment: AttributeError: Got AttributeError when attempting to get a value for field `replies` on serializer `CommentSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Reply` instance. Original exception text was: 'Reply' object has no attribute 'replies'. The code is: models.py class AbstractComment(models.Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='%(class)ss', null=True) text = models.TextField(null=True) liked_by = models.ManyToManyField(Profile, related_name='liked_%(class)ss') likes = models.PositiveIntegerField(default=0) created_time = models.DateTimeField(default=timezone.now, editable=False) def pretty_time(self): return '{:%Y-%m-%dT%H:%M:%S}'.format(self.created_time) class Meta: abstract = True class Comment(AbstractComment): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') class Reply(AbstractComment): comment_field = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='replies') serializers.py class ReplySerializer(DynamicFieldsModelSerializer): author = serializers.DictField(source='author.get_data') avatar = serializers.ImageField(source='author.avatar', use_url=False) class Meta: model = Reply fields = '__all__' class CommentSerializer(DynamicFieldsModelSerializer): author = serializers.DictField(source='author.get_data') avatar = serializers.ImageField(source='author.avatar', use_url=False) replies = ReplySerializer(many=True) class Meta: model = Comment fields = '__all__' -
How to show unread notification count in Django
I have notifications create from getstream in Django, but I don't know how to show count of unread notifications. Is there any simple way to do this? In documentation I see mention about it but not how to do this. Maybe I overlooked this. My notification view look like this: @login_required def notification_feed(request): enricher = Enrich(request.user) context = {} feed = feed_manager.get_notification_feed(request.user.id) activities = feed.get(limit=25, mark_seen='all')['results'] activities = enricher.enrich_aggregated_activities(activities) return render(request, 'auth/notification_feed.html', {'activities': activities}) I need to create global count of unread notifications something like on facebook. -
Django: Where to place an infinite loop
I am currently working on a project where I'd need to integrate a django application with mastodon, a federated twitter-like service. In order to interact with Mastodon, I use Mastodon.py package: https://mastodonpy.readthedocs.io/en/stable/# I would need to monitor events occurring to a specific mastodon account, a bot account managed by the django application, using the streaming capabilities provided by the package: https://mastodonpy.readthedocs.io/en/stable/#streaming So I would need to call one of these stream methods in an infinite loop. But I can't figure out where I should place it in django. Is there a main loop somewhere where I could insert it? -
Read the timeout of a django cache entry
We had a bug in our production system. The timeout was set incorrectly. Now I want to write a test which checks, that the value of the timeout is correct. I look at the docs and don't see a way to read the timeout value of a particular cache-key: https://docs.djangoproject.com/en/2.2/topics/cache/ How could I read the timeout value in my test to unsure it is correct? -
django save all record in for loop
this is the code from the picture {% for schedule in sched %} <tr> <td></td> <td>{{schedule.Remark}}</td> <td>Php {{ schedule.Amount|floatformat:2}}</td> <td> </td> </tr> {% endfor %} this is the code from inserting record to database id = request.POST.get('ids') educlevel = request.POST.get('gradelevel') studentname = StudentProfile(id=id) educationlevel = EducationLevel(id=educlevel) id = request.POST.get('payments') payment = PaymentType(id=id) sc = request.POST.get('schoolyear') schoolyear = SchoolYear(id=sc) V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() for file in request.FILES.getlist('myfile'): StudentsSubmittedDocument.objects.create( Students_Enrollment_Records=V_insert_data, Document=file ) insert_StudentsPaymentSchedule = StudentsPaymentSchedule( Students_Enrollment_Records = V_insert_data, #Amount = ScheduleOfPayment.Amount, Remarks = ScheduleOfPayment.Remark ) insert_StudentsPaymentSchedule.save() this the models.py class ScheduleOfPayment(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) this is where I want to save all the record shown class StudentsPaymentSchedule(models.Model): Students_Enrollment_Records=models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Payment_Schedule = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True,blank=True) Remarks=models.TextField(max_length=500,null=True,blank=True) this is the problem, only 1 record save in database StudentsPaymentSchedule, I just want to save all the Payment schedule and amount from database ScheduleOfPayment and automatic post it in StudentsPaymentSchedule and I don't know what this mean django.db.models.query_utils.DeferredAttribute object at … -
list Dictionary output isnt what i expected
i try to load data from py manage.py shell with this code def makeDictFactory(cursor): columnNames = [d[0] for d in cursor.description] def createRow(*args): return dict(zip(columnNames, args)) return createRow import cx_Oracle dsn_tns = cx_Oracle.makedsn('', '', sid='') conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns) c = conn.cursor() c.execute("select table_name from all_tables") c.rowfactory = makeDictFactory(c) c.fetchall() the output that i want is { a : b , c : d} , but when i execute the c.fetchall() it become [{a:b},{c:d}] , it cause when i put the code in backend and want to display it to front end , it will return an error like unhashable type dict , unhashable type list or context must dict or list what should i do?