Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn cannot load some of my Django app static files
I have a Django application which loads almost all the static files. I do not know whether there is anything else that is not loaded but I know that it does not load some code from bootstrap.min.css which is already collected in the static root file. I used gunicorn and nginx for deployment. And also I tried to run it by runserver and everything was fine. P.S. The code is related to the header of my website which is supposed to transform to a drawer menu when loading in a mobile phone. If you can please help me fix this problem! Thanks html file <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="collapse navbar-collapse offset" id="navbarSupportedContent"> <ul class="nav navbar-nav menu_nav ml-auto"> <li class="nav-item {{home}}"><a class="nav-link" href="{% url 'index' %}" style="margin-right: 20px; font-size: large;">home</a></li> <li class="nav-item {{about}}"><a class="nav-link" href="{% url 'about' %}" style="margin-right: 30px; font-size: large;">about</a></li> </ul> </div> -
Google Forms Model Structure in Django
I am using Django (and Postgres) and want to recreate Google Forms. I am struggling to come up with the models needed to replicate the following functionality: A model to store the questions of a form, including the question itself and the type of question. A model to store the answers for the forms, to clarify, the answers that people filled in to a particular form. Please let me know if you have any ideas or suggestions! Thanks!! -
How to redirect on button click on user is not logged in in django
Hey django gang how's it going? I wanted to know how I can redirect a user to login page if he is not logged in when he clicks a button which serves different purpose when the user is logged in. For example: I have a button which acts as modal popup button when the user is logged in but will redirect the user to login page if the user is not logged in. -
Django trying to save object with existing primary key
Today something strange happened. Basically I have a code to import json data into model, its something like: for i in data: Signature.objects.get_or_create(**i) json example: [ {'id': 1, 'plan': 1, 'customer': 1}, {'id': 2, 'plan': 3, 'customer': 50}, ... {'id': 31, 'plan': 12, 'customer': 22}, ... {'id': 222, 'plan': 12, 'customer': 22}, ] Yes, my client didn't follow a sequence :( so, I'm importing and keeping the same pk. This code works as expected and data is now synced with payment service (all objects imported). Now the strange behavior: I'm using Django Rest Framework and after a POST (check validated_data) in my API the following error raises at this line: Signature.object.create(**self.validated_data) duplicate key value violates unique constraint "plans_signature_pkey" DETAIL: Key (id)=(1) already exists. validated data: { "plan": "3", # This is a foreign key to plan 3 "payer_only": False, "schedule": "09:00", "payment: "CREDIT_CARD" } There is no 'pk': 1 or 'id': 1 in validated data Django is trying to create an object with an existing key? Debugging code, I called the Subscription.create() line 31 times then: duplicate key value violates unique constraint "plans_signature_pkey" DETAIL: Key (id)=(1) already exists. .... duplicate key value violates unique constraint "plans_signature_pkey" DETAIL: Key (id)=(31) already … -
Django PreviewForm - how do I add a queryset to a field?
I'm using formtools (https://github.com/jazzband/django-formtools) to show a preview of the form data before it's being submitted. Below is the code I'm working on. models.py class Invoice(Model): issue_date = DateField() due_date = DateField() description = CharField(max_length=200) project = ForeignKey(Project, on_delete=CASCADE) currency = CharField(max_length=3, choices=CURRENCY_CHOICES, default='eur') amount = DecimalField(blank=True, null=True, max_digits=100, decimal_places=2) preview.py class InvoiceFormPreview(FormPreview): def done(self, request, cleaned_data): invoice = Invoice.objects.create(**cleaned_data) success_url = reverse("finance:list-invoices") return HttpResponseRedirect(success_url) urls.py path('invoice/', InvoiceFormPreview(InvoiceForm)), With regular ModelForm, I can add a queryset to the Project foreignkey to only display projects that belongs to the logged in user, e.g class InvoiceForm(ModelForm): def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.filter(projectuser__user=user.id) How would I go about adding that self.fields.... to the InvoiceFormPreview? It looks like there is a get_initial method available to use, but not sure how that works -
HTML form data not saved in database - django
I can get data from html but it wont save to database what should i do ? it works correctly the only problem is that it wont be save views.py def comment(request , newsId): cm = get_object_or_404(models.News , id= newsId) print("news = " + newsId) if request.method == 'POST' : cm.comments_set.text = request.POST.get('comment_text') cm.comments_set.name = request.POST.get('comment_name') cm.save() return HttpResponseRedirect(reverse('details', args=(cm.id,))) urls.py urlpatterns = [ path('', views.test), path('details/<newsId>', views.details, name="details"), path('comment/<newsId>' , views.comment ,name="comment")] models.py class News(models.Model): title = models.CharField(max_length=300) author = models.CharField(max_length=100) date = models.DateTimeField() description = models.TextField() like = models.IntegerField(default=0) img = models.CharField(max_length=100) def __str__(self): return self.title class Comments(models.Model): news = models.ForeignKey(News, on_delete=models.CASCADE) name = models.CharField(max_length=100) text = models.TextField() def __str__(self): return self.name html form <form action="{% url 'comment' newsKey.id %}" method="POST"> {% csrf_token %} <textarea name="comment_text" id="comment_text_id" cols="30" rows="10" placeholder="Write your here comment here"></textarea> <input type="text" name="coment_name" id="comment_name_id" placeholder="Type full name"/> <button type="submit" value="comment_submit"> SUBMMIT </button> </form> -
Convert JQuery Ajax code to plain JavaScript
This is Ajax code in my application, it adds object in Model without refreshing the page and shows no error: $(document).on('submit', '#addbookform', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'books:home' %}", data: { name: $('#name').val(), price: $('#price').val(), num_of_pages: $('#num_of_pages').val(), csrfmiddlewaretoken: "{{ csrf_token }}" }, success: function () { alert('Form submitted successfully!!'); } }) }) I tried to convert it to JavaScript, however it add objects to model, but it refreshes the page and moreover it shows a 403 error in console and then fade away. document.querySelector('#addbookform').onsubmit = savebook; function savebook() { const name = document.querySelector('#name').value; const price = document.querySelector('#price').value; const num_of_pages = document.querySelector('#num_of_pages').value; const url = "{% url 'books:home' %}" const xhr = new XMLHttpRequest(); xhr.onload = function () { if (this.status == 200) { alert("Saved!"); } } xhr.open('POST', url, true); xhr.send(); } Can you please help me solve it? -
Django channel chat direct message instead of group chat
You know in Django channel documentation, they have shown a group chat system but i dont want this. I want to send a message directly to the user instead of group. This is my consume.py file: class ChatConsumer(AsyncJsonWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: # Reject the connection await self.close() else: # Accept the connection await self.channel_layer.group_add( str(self.scope["user"].username), self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( str(self.scope["user"].username), self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( str(self.scope["user"].username), { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) and this is the client: <!-- chat/templates/chat/room.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br/> <input id="chat-message-input" type="text" size="100"/><br/> <input id="chat-message-submit" type="button" value="Send"/> </body> <script> var roomName = "{{ usernamee|escapejs }}"; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = … -
Is there any idea to get jwt token in django?
i'm doing my own project. communicate python program - django server. first is when program send information about signup(like name, password, id etc.) server return success signal. next step is when program send login information about sign(like name, password), server return jwt token and program receive jwt token. I'm try everything what i know... but i don't know how to return jwt token to python program. any idea? -
Django Admin - display image on hover
I'd like to display a thumbnail in a popover when I hover over text (a camera emoji) in our Django Admin view. The code I have works, but displays the image inline, which disrupts the rest of the layout of the site I'm by no means a Django expert, so there might be something easy I'm missing. I'm totally open to using other libraries to help if that's the best path forward, but am not sure of how to appropriately load them in to django admin. I'm also open to pure js/css solutions - whatever works best! Here's the code that I have def image_column(self, obj): format_html(foo + " " + \ '''<a href="{}"" target="_blank" style="font-size: 18pt" onmouseover="document.getElementById('{}_img').style.display='block';" onmouseout="document.getElementById('{}_img').style.display='none';">📷 <img id="{}_img" style="display:none" src="{}" />'''.format(img_url, img_id, img_id, img_id, img_url) I'd love any thoughts or suggestions on the best way to make it 'popover' instead of display inline. Thank you!! -
Django autoescape adds an additional div to the html output
This is my django template : <div> <div class="container"> {% for art in articles %} <div class="js-hor-card m-3 pt-3 pb-3 px-3 rounded"> <div class="row"> <div class="col-4"> <div class="view overlay"> <img class="card-img-top" src="{{ art.image.url }}" alt="Card image cap"> <a href="{% url 'blog:article' art.slug %}"> <div class="mask rgba-white-slight"></div> </a> </div> </div><!--End col-4--> <div class="col-8"> <h4> {{ art.title }} </h4> {% if art.reading_time %} <p>Temps de lecture : <span>{{ art.reading_time }}</span></p> {% endif %} <div> <p> {% autoescape off %} {{ art.text|truncatechars:150 }} {% endautoescape %} </p> </div> </div><!--End of col-8--> </div><!--End of row--> </div> {% endfor %} </div> </div> This is my jQuery code to add a class to my cards on mouser over : $(".js-hor-card").hover( function () { $(this).addClass("z-depth-1"); }, function () { $(this).removeClass("z-depth-1"); } ); The problem is that the autoescape filter adds another additional div (with the same classes as as my cards) to my HTML. I found this by inspecting the page in the browser. This div wraps all of my cards and as it has the same classes as my cards the jQuery function applies to it as well. When I delete the autoescape everything works fine. I tried |safe, but it produces the same effect. Do … -
Display SVG image from qrcode in Django
As per the qrcode docs, I generate an SVG QR code: import qrcode import qrcode.image.svg def get_qrcode_svg( uri ): img = qrcode.make( uri, image_factory = qrcode.image.svg.SvgImage) return img And that's all fine. I get a <qrcode.image.svg.SvgImage object at 0x7f94d84aada0> object. I'd like to display this now in Django html. I pass this object as context (as qrcode_svg) and try to display with <img src="{{qrcode_svg}}"/> but don't get really anywhere with this. The error shows it's trying to get the img url, but isn't there a way I can do this without saving the img etc.? Terminal output: >>> UNKNOWN ?????? 2020-06-16 07:38:28.295038 10.0.2.2 GET /user/<qrcode.image.svg.SvgImage object at 0x7f94d84aada0> Not Found: /user/<qrcode.image.svg.SvgImage object at 0x7f94d84aada0> "GET /user/%3Cqrcode.image.svg.SvgImage%20object%20at%200x7f94d84aada0%3E HTTP/1.1" 404 32447 -
Django not finding nested tests
I have the following file structure: project - - resources -__init__.py - core __init__.py test.py My test code looks like this: class TestEmailHelper(TestCase): def test_send_mail(self): EmailHelper.send_email(EmailHelper.SLUGS.ORDER_COMPLETED, 'lee@lee.com', {}) assert len(mail.outbox) == 1, "Inbox is not empty" Here is the config in the app apps.py file: class CoreConfig(AppConfig): name = 'resources.core' And, of course, this is in my INSTALLED_APPS and works perfectly fine except for finding the tests. if I attempt to run all tests, I get the response 'No Tests ran, please check the configuration settings fo the tests. if I use this command, it works: python3 manage.py test resources/core If I use this command, I get a module not found error looking for 'core': python3 manage.py test core It seems to me it may have something to do with having my app nested due to the error caused when I dont append the pat with 'resources'. But I'm not sure how I can fix this. -
Tired of settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
I am using mysql as database for my django project hosted in digitalocean python3 manage.py makemigrations python3 manage.py migrate creating superuser everything is working. but when i try to open up my site the error message shows as : settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I checked all those previous questions and solutions but they didn't worked for me.. Below is my database setting. Hope someone can help me on that. Thanks! It was working perfectly fine on my localhost DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'newdb_py', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", # Strict mode }, } } -
How do you test model field types in Django?
I'm trying to test whether a field is in fact a primary key. class PatientTests(test.TestCase): def test_primary_key(self): # Cannot be NULL patient = models.Patients(patient_id=None) patient.save() But the test is passing with no exceptions raised. My model definition: class Patients(models.Model): patient_id = models.CharField(max_length=12, primary_key=True) -
Is there any possibility to pass wagtail.core.block file content values from models file to utils.py in wagtail?
I am beginner with Wagtail and i have been trying to use a wagtail block page content as plugin(plugin.py) in a models.Model file(Apllications.py) to be displayed on the website. I have called the class of plugin.py as a function in the Applications.py. Wagtail CMS is loading fine with the fields in plugin.py as i can enter the values in the fields. but the values are not passing to the following page(Utils.py) where the values has to be returned.The value has to be passed in a JSON format. plugin.py class Plugin(AbstractSerializedStructBlock): title = blocks.CharBlock(required=False) def get_api_representation(self): return{ 'title' : self.title } Application.py class Application(models.Model): body = StreamField([ ('plugin',plugin()) ], blank=True) panels = [ MultiFieldPanel( [ FieldPanel('application_category'),] ), StreamFieldPanel('body'), ] utils.py def get_applications_json(category): applicationsByCategory = get_applications(category) applications = [] if applicationsByCategory: for app in applicationsByCategory: applications.append({ "body" : app.body }) return applications Error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data -
Joining same table in django ORM / QuerySet
I have been battling with is problem for the past week, so I have a mysql query where I am joining the same table, reason being I am trying to return null values, That I have done seeing it is quite straightforward. However Implementing this using Django orm, I initially used RAW, however I am trying to get it done using orm. The details are below: MYSQL QUERY: select t1.ca,t2.cc2 from ( select a.`ca_acq` ca from mat a where a.`YYYY- MM`="2020-05" group by a.`ca_acq` )t1 left join ( select b.`ca_acq` ca2, count(b.`ca_acq`) cc2 from mat b where b.`YYYY- MM`="2020-05" and b.network="PP" group by b.`ca_acq` )t2 on t2.ca2= t1.ca The above query produces: **ca** **cc2** B1 2177 CI2 693 J2l {null} J2N {null} N1B 8901 S21 1948 VS1 {null} However I tried doing this using Queryset: t1=mat.objects.filter(yyyy_mm="2020-05").values("ca_acq").annotate(cnt1=Count("ca_acq")) t2=t1.exclude(network="CC").exclude(network="AA").values("network","ca_acq") t3=t2.filter(ca_acq__in=Subquery(t1)).values("network","ca_acq") However i got the following error Operand should contain 1 column(s) Id appreciate for brain picking insight and assistance as to how I can resolve it issue -
Django 3, how to load from picture views in aws s3
When we upload pictures, they are uploaded to the root of the project in the media folder, what I have to fix (add) so that everything uploads also to s3 amazon views.py randomlist = random.sample(range(1, 99), 13) print(randomlist) bar_code = '' for i in randomlist: bar_code += str(i) print(bar_code) hr = barcode.get_barcode_class('code39') HR = hr(bar_code,writer=ImageWriter()) qr = HR.save('media/tikets/'+bar_code) settings AWS_ACCESS_KEY_ID = 'id_key' AWS_SECRET_ACCESS_KEY = 'key' AWS_STORAGE_BUCKET_NAME = 'cinemaxpro-bucket' # AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
A list of locations that contain a GeoPoint - (geo_spatial_filter_fields, geo_distance)
I'm using elasticsearch-dsl-drf, and I just converted a single location field on my document, to a NestedField with this definition: location = fields.NestedField(properties={"point": fields.GeoPointField()}) Then on my view I have (I added path and changed the field value to try and make it work): geo_spatial_filter_fields = { 'location': { 'path': 'location', 'field': 'point', 'lookups': [constants.LOOKUP_FILTER_GEO_DISTANCE] } } geo_spatial_ordering_fields = {'location': None} I'm wondering how this can be achieved? I want to order all the documents based on the closest location from a list of locations for each document. Edit Currently experimenting with (changed elasticsearch dsl drf to use this): { "query":{ "nested":{ "path":"location", "query":{ "geo_distance":{ "distance":"16090km", "location.point":{ "lat":"52.240995", "lon":"0.751156" }, "distance_type":"arc" } } } }, "sort":[ { "_geo_distance":{ "location.point":{ "lat":"52.240995", "lon":"0.751156" }, "unit":"km", "distance_type":"plane", "order":"asc" } }, { "date_first_registered":{ "order":"desc" } } ] } This seems to execute but the sorting is off. I appreciate your time, Thanks -
Django collectstatic recollects module static files when deployed to Heroku
My issue is that every time I deploy my code to Heroku, when collecting static, all the static files within modules are copied again, even if they haven't changed. This means my free amazon S3 bucket copy limit is being reached after just a few deploys because it is copying 400 files each deployment. The issue must be with some Heroku setting because when running manage.py collectstatic in my IDE, it does not re-copy the files even when using the S3 bucket as default. I have DISABLE_COLLECTSTATIC=1 in my heroku config vars, and set it in the heroku CLI to be doubly sure. I have no idea why it is doing this. There's nothing useful in the deployment logs either. Any help would be appreciated. This is the log: Successfully compiled 1 referred SASS/SCSS files. Debug mode is off. 386 static files copied, 106 unmodified. The 106 unmodified files are the bootstrap SASS and a few others of my own. the 386 files are drom django admin and django-countries. Despite not changing, they are always copied. No settings swap seems to fix the issue. Relevant parts of my settings.py: STATICFILES_FINDERS = [ # Default finders 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # finders for … -
Elastic Beanstalk - '.ebextensions/02_setup.config' - Contains invalid key: '03_wsgipass'
Using this guide to try to deploy my django app which uses channels: https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 This is my 02_setup.config container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' When running eb create django-env I get: Printing Status: 2020-06-17 16:11:36 INFO createEnvironment is starting. 2020-06-17 16:11:38 INFO Using elasticbeanstalk-us-west-2-041741961231 as Amazon S3 storage bucket for environment data. 2020-06-17 16:11:39 WARN Error processing file (Skipping): '.ebextensions/02_setup.config' - Contains invalid key: '03_wsgipass'. For information about valid keys, see http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/ebextensions.html 2020-06-17 16:12:00 INFO Created security group named: sg-09fcbd00450e2438d 2020-06-17 16:12:15 INFO Created load balancer named: awseb-e-3-AWSEBLoa-1E8WRE8X90Q7D 2020-06-17 16:12:15 INFO Created security group named: awseb-e-3um2qhsms9-stack-AWSEBSecurityGroup-1OH8TOJHUVWOT 2020-06-17 16:12:15 INFO Created Auto Scaling launch configuration named: awseb-e-3um2qhsms9-stack-AWSEBAutoScalingLaunchConfiguration-7V5MPL4ZNZOG 2020-06-17 16:13:35 INFO Created Auto Scaling group named: awseb-e-3um2qhsms9-stack-AWSEBAutoScalingGroup-6WNX8OQK3WQO 2020-06-17 16:13:35 INFO Waiting for EC2 instances to launch. This may take a few minutes. 2020-06-17 16:13:50 INFO Created Auto Scaling group policy named: arn:aws:autoscaling:us-west-2:041741961231:scalingPolicy:b25f0129-aec8-414c-9b64-72b95986648c:autoScalingGroupName/awseb-e-3um2qhsms9-stack-AWSEBAutoScalingGroup-6WNX8OQK3WQO:policyName/awseb-e-3um2qhsms9-stack-AWSEBAutoScalingScaleUpPolicy-N1XL34JAPA6S 2020-06-17 16:13:50 INFO Created Auto Scaling group policy named: arn:aws:autoscaling:us-west-2:041741961231:scalingPolicy:f6eecd79-39ee-475d-b927-ed1a5dc205d5:autoScalingGroupName/awseb-e-3um2qhsms9-stack-AWSEBAutoScalingGroup-6WNX8OQK3WQO:policyName/awseb-e-3um2qhsms9-stack-AWSEBAutoScalingScaleDownPolicy-155DVPR0DTOK 2020-06-17 16:13:50 INFO Created CloudWatch alarm named: awseb-e-3um2qhsms9-stack-AWSEBCloudwatchAlarmHigh-CPMPHOMFE9IT 2020-06-17 16:13:50 INFO Created CloudWatch alarm named: awseb-e-3um2qhsms9-stack-AWSEBCloudwatchAlarmLow-UVP8LL57BLI4 2020-06-17 16:17:49 INFO Successfully launched environment: django-env What's wrong with … -
Reset Password link for django not working
After sending a reset link and clicking it the link is not working it shows that it is not valid. Url for link path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), password_reset_email.html {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} Your username is {{ user.username }} password_reset_confirm.html {% if vaidlink %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Change Password"> </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %}``` -
System error: null argument to internal routine in xmlsec
I am trying to implement SSO in a Django application. I have a ubuntu 16.04 OS, Apache and WSGI and python 3.5.2 The packages that I installed: xlmsec 1.3.3 lxml 4.5.1 pkg-config 1.5.1 python3-saml 1.9.0 And all the dependencies for xmlsec: libxmlsec1-dev libxml2-dev libxmlsec1-openssl My server is behind a proxy (I dont have full access to that server) trying to install xlmsec >= 1.3.7 throws me a connection error, that why I used 1.3.3 version. Once I run the following command I get the error: python -c "import xmlsec" func=xmlSecOpenSSLAppKeyLoadMemory:file=app.c:line=188:obj=unknown:subj=data != NULL:error=100:assertion: func=xmlSecCheckVersionExt:file=xmlsec.c:line=185:obj=unknown:subj=unknown:error=19:invalid version:mode=exact;expected minor version=2;real minor version=2;expected subminor version=30;real subminor version=20 func=xmlSecOpenSSLInit:file=crypto.c:line=312:obj=unknown:subj=xmlSecCheckVersionExact:error=1:xmlsec library function failed: func=xmlSecOpenSSLAppPkcs12Load:file=app.c:line=580:obj=unknown:subj=filename != NULL:error=100:assertion: Traceback (most recent call last): File "", line 1, in SystemError: null argument to internal routine I am not sure if it could be something about wrong versions or related to xlmsec issue (I already tried to rollback to older versions and have the same issue). -
Django form validation not passing to cleaned_data, data is there though
So I am not actually adding any of the data in the form data to a database, it is going to run through a program to edit paragraphs. I'm having trouble getting the response to clean the data. I can retrieve the data normally but it doesn't get added to the clean dictionary. I assume it's because I overwrote the init method of the form but I'm totally getting stuck on how to fix it. If I can get away with not cleaning data, things will probably work, I'm new so I wonder what havoc that would cause in the end. My Form data: class GameForm(forms.Form): def __init__(self, *args, **kwargs): categories= kwargs.pop('categories', None) super(GameForm, self).__init__(*args, **kwargs) if categories: for i in range(0, categories[0]): j=i+1 self.fields["_noun_%d" % j] = forms.CharField(max_length=15, label=("Noun "+ str(j)+":")) self.fields["_noun_%d" % j].widget.attrs.update({'class': 'special'}) for i in range(0, categories[1]): j = i + 1 self.fields["_verb_%d" % j] = forms.CharField(max_length=15, label=("Verb "+ str(j)+":")) self.fields["_verb_%d" % j].widget.attrs.update({'class': 'special verb'}) for i in range(0, categories[2]): j = i + 1 self.fields["_adverb_%d" % j] = forms.CharField(max_length=15, label=("Adverb "+ str(j)+":")) self.fields["_adverb_%d" % j].widget.attrs.update({'class': 'special adverb'}) for i in range(0, categories[3]): j = i + 1 self.fields["_adjective_%d" % j] = forms.CharField(max_length=15, label=("Adjective "+ str(j)+":")) … -
cors issue with django, rest-framework and vue js
Im trying to create my first django application + rest-framework, in the frontend I use VueJS. backend path: http://127.0.0.1:8000/ frontend path: http://localhost:8080/ I read a lot of posts about this error but none works for me (maybe I need to save the changes migrate again or something, Im new to django) I get this Error on the frontend path: Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/todo' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I installed 'corsheaders' and added it to the INSTALLED_APPS array, I added 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware' to the MIDDLEWARE array, I added CORS_ORIGIN_ALLOW_ALL = True what can cause this issue?