Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Jinja not transfer tags in blocks into html file?
I started to learn Django recently (in PyCharm) and this problem has appeared: tags inside the {% block 'name' %} <taaags> {% endblock %} doesn't transfer and execute in html fileJinja's example code /Html file Also, i want to admit, that all links to static files(img,css etc) are working. P.S.: Django's server is running. Python 3.6; PyCharm 2017.1. -
NoReverseMatch Exception in Django template URL path
I can access the desired URL but when it is added in another template as a hyperlink, the template fails to render. So, when I try to access http://127.0.0.1:8000/jobs/97072947-looking-for-woodcutter/add-milestones/, it works. But when I want to insert the above URL in project_milestones's template: {% url 'projects:create_milestone' %} This error occurs when I open http://127.0.0.1:8000/jobs/97072947-looking-for-woodcutter/milestones/: Request Method: GET Request URL: http://127.0.0.1:8000/jobs/97072947-looking-for-woodcutter/milestones/ Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'create_milestone' with no arguments not found. 1 pattern(s) tried: ['jobs/(?P<project>[-\\w]+)/(add-milestones)/$'] Python Version: 3.6.1 views.py: def project_milestones(request, project): project = get_object_or_404(Project, slug=project) ...code.. return render(request, 'projects/employer_milestones_project.html' {'project': project,}) def create_milestone(request, project): project = get_object_or_404(Project, slug=project) ..code... return render(request, 'projects/employer_create_milestone.html', {'project': project}) urls.py: url(r'^'r'(?P<project>[-\w]+)/(add-milestones)/$', create_milestone, name='create_milestone'), url(r'^'r'(?P<project>[-\w]+)/(milestones)/$', project_milestones, name='project_milestones'), What am I missing here? I have also tried {% url 'projects:create_milestone' project=project.slug %} but nothing seems to work. Also if I remove that built-in url tag, the page loads successfully. I am sure the answer is somewhere here in documentation or here but I am not able to understand. Sorry if question is not well structured. Thanks! -
What Django model field do I use for a checkbox form?
I created an HTML form and am now hooking it up to Django. (I know I should have used Django to create the form, but in this case I didn't). In my models.py, I use CharField for textboxes, CharField with choices for select forms, but for checkboxes, what model field do I use? Do I have to create another class for all of the checkbox choices and then link that with a manytomany relationship? Thank you. -
Get current page for custom django cms plugin
I have a problem with my own django cms plugin. I have a product detail page with an id as object and the ID in the URL. When i add my custom plugin into the placeholder, I want to set the foreign key product_id of my cms plugin. What is the best was to do this? At Django i would pass the request as Argument for the Form, but i dont know how to do this with django cms. At cms_plugins.py i could only choose the form via form = MediaForm or something like this, but MediaForm(request=...) would not work. Thank you for your help :-) -
Django Rest Framework works fine in PATCHing in localhost but fails in homolog environment
I've just deployed my Django/Python application in a homolog environment. The application uses Django Rest Framework to implement REST. Now I'm testing the homolog environment, and having a little problem with a resource that I want to do partial updated. But testing app in localhost works fine. Localhost: I'm using httpie to consume API resources. The command below sends a PATCH to an object experiment in localhost: http -a lab1:'nep-lab1' PATCH http://127.0.0.1:8000/api/experiments/11/ status='to_be_analysed' and that's all right, the PATCH was made successfully. Homolog: In homolog environment the same command fails. The erro: HTTP/1.0 400 Bad Request Connection: close Content-Length: 2065 Content-Type: text/html Date: Thu, 27 Jul 2017 18:48:48 GMT Server: squid/2.7.STABLE9 Via: 1.0 athena.ime.usp.br:3128 (squid/2.7.STABLE9) X-Cache: MISS from athena.ime.usp.br X-Cache-Lookup: NONE from athena.ime.usp.br:3128 X-Squid-Error: ERR_INVALID_REQ 0 <html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>ERROR: The requested URL could not be retrieved</title> <style type="text/css"><!-- %l body :lang(fa) { direction: rtl; font-size: 100%; font-family: Tahoma, Roya, sans-serif; float: right; } :lang(he) { direction: rtl; } --></style> </head><body id="ERR_INVALID_REQ"> <div id="titles"> <h1>ERROR</h1> <h2>The requested URL could not be retrieved</h2> </div> <hr> <div id="content"> <p><b>Invalid Request</b> error was encountered while trying to process the request:</p> <blockquote id="data"> <pre>PATCH /api/experiments/12 HTTP/1.1 Host: portal-dev.numec.prp.usp.br Connection: keep-alive Accept-Encoding: gzip, … -
Django: Model class X doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS
He looked for other solutions in stackoverflow but did not get it. The structure of my project is the following: src | |---project | | settings.py | apps | | __init__.py app1 |..... app2 app3 My settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'project.apps.App1Config', 'project.apps.App2Config', 'project.apps.App3Config', 'project.apps.App4Config', 'project.apps.ProjectConfig',) apps/__init__.py class App1Config(AppConfig): name = 'project.apps.app1' verbose_name = "App" And still appears in console: RemovedInDjango19Warning: Model class project.models.Model doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9. RemovedInDjango19Warning: Model class project.apps.app1.models.Model doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9. -
Django how to filter objects in many to many field, not the original queryset
i'm trying to filter objects in a manytomany field of a queryset and am having difficulty, most other posts seemed to address filtering the queryset based on the contents of the manytomany field whereas i need to filter the ManyToMany field itself. Models: class IngredientsUserNeeds(models.Model): user = models.ForeignKey(User, blank=True, null=True) drinks = models.ManyToManyField(Drink) class Drink(models.Model): name = models.CharField(max_length = 1000, null=True, blank=True) user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) In my ListAPI view, I start filtering by qs = IngredientsUserNeeds.objects.all().filter(user=user) But after calling this, I want to filter out drinks in each object of the qs that do not belong to a particular user like, qs = qs.filter(drinks=drink_object) However, this call filters the original IngredientsUserNeeds queryset and not the items in it's ManyToMany field. How can I modify my filter so that it does not filter the queryset but rather the items in each of its object's ManyToMany Fields? -
Django model: a fieldtype for making a set/list of instances of another model
Consider these three models: class Statement(models.Model): statement_id = models.CharField(max_length=200) title = models.CharField(max_length=200) statement-keywords = ? statement-contexts = ? class Keyword(models.Model): word = models.CharField(max_length=200) statement = models.ManyToManyField(Statement) def __str__(self): return self.word @python_2_unicode_compatible class Context(models.Model): context_word = models.CharField(max_length=200) keyword = models.ManyToManyField(Keyword) statement = models.ManyToManyField(Statement) def __str__(self): return self.context_word Every Statement is supposed to have a set of associated Keywords and Contexts. I am also working mainly on the admin interface of this website, and wanted to ensure that someone could enter in keywords and contexts on the same page for updating or submitting a new page. It would be ideal if I could make statement-keywords hold a set of all Keywords's, and statement_contexts hold a set of all associated keywords to that statement instance, and statement-context hold a set of all Context's associated with that statement. But there are two issues that come up for me: Because Statement is above Keyword and Context, I can't reference Keyword and Context as objects in a manytomany relationship. If I do so, I get an error message. If I move Statement below Keyword and Context, then Keyword and Context would both be unable to make a reference Statement (I would get an error message). I … -
Django + Zappa/Lambda + Amazon S3 403 Forbidden
My relevant django settings.py for django-storages usage: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') os.environ['S3_USE_SIGV4'] = 'True' AWS_S3_HOST = 's3.eu-central-1.amazonaws.com' AWS_STORAGE_BUCKET_NAME = 'sjef-static' AWS_S3_CUSTOM_DOMAIN = '%s.s3-eu-central-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' This is my bucket policy for sjef-static: { "Version": "2008-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:*", "Resource": [ "arn:aws:s3:::sjef-static/*", "arn:aws:s3:::sjef-static" ] } ] } This is the policy Zappa automatically adds to the created Lambda function: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:*" ], "Resource": "arn:aws:logs:*:*:*" }, { "Effect": "Allow", "Action": [ "lambda:InvokeFunction" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "ec2:AttachNetworkInterface", "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface", "ec2:DescribeInstances", "ec2:DescribeNetworkInterfaces", "ec2:DetachNetworkInterface", "ec2:ModifyNetworkInterfaceAttribute", "ec2:ResetNetworkInterfaceAttribute" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "s3:*" ], "Resource": "arn:aws:s3:::*" }, { "Effect": "Allow", "Action": [ "kinesis:*" ], "Resource": "arn:aws:kinesis:*:*:*" }, { "Effect": "Allow", "Action": [ "sns:*" ], "Resource": "arn:aws:sns:*:*:*" }, { "Effect": "Allow", "Action": [ "sqs:*" ], "Resource": "arn:aws:sqs:*:*:*" }, { "Effect": "Allow", "Action": [ "dynamodb:*" ], "Resource": "arn:aws:dynamodb:*:*:*" }, { "Effect": "Allow", "Action": [ "route53:*" ], "Resource": "*" } ] } I've … -
Direct file upload in django without caching the file
I was trying to build a django powered file uploader which will upload and store the file directly to the destination location, without caching the file in any temporary location. So far what I understood is, we should write a custom FileUploadHandler to achieve this. So I came up with the following. class DirectUploadHandler(FileUploadHandler): def __init__(self, request=None): super().__init__(request) self.field_name = None self.file_name = None self.content_type = None self.content_length = None self.charset = None self.content_type_extra = None self.request = request self.file = None def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None): self.field_name = field_name self.file_name = file_name self.content_type = content_type self.content_length = content_length self.charset = charset self.content_type_extra = content_type_extra self.file = open('/destinationfolder/filename.ext', 'wb+') def receive_data_chunk(self, raw_data, start): self.file.write(raw_data) def file_complete(self, file_size): self.file.seek(0) self.file.size = file_size return self.file Now the upload is working fine and it is directly writing to the destination. But I have noticed that file_complete method is called before the destination file is completely written. All the code execution completed and django view returned that upload is completed. Still the file is growing, and it took few more seconds to complete the writing. Why there is a delay in completing the write process? Why the file_complete method is called … -
Django save_model method works locally, but not on Bluemix server?
This program works correctly on localhost when I save a blogpost on the admin site, but results in "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" when I try the same on the server (there are no logs in the IBM Bluemix server). I put my own print statements in there for debugging, and I noticed on the server the save_model method is never being called upon clicking Save. Everything else including deleting a blog post on the server works. Any help would be appreciated! This is the BlogPostAdmin class in admin.py: class BlogPostAdmin(VersionAdmin): form = BlogPostForm list_display = ('__unicode__', "status", 'user', 'is_published', 'is_live', 'publish_date') list_filter = ("status",) actions = ("delete_posts", submit_for_approval, ) filter_horizontal = ('categories', 'access_level') def get_queryset(self, request): print "Calling function get_queryset" qs = super(BlogPostAdmin, self).get_queryset(request) if self.is_contributor(request): qs = qs.filter(user=request.user) return qs def get_actions(self, request): print "Calling function get_actions" actions = super(BlogPostAdmin, self).get_actions(request) del actions['delete_selected'] return actions def get_fieldsets(self, request, obj=None): fields = super(BlogPostAdmin, self).get_fieldsets(request, obj) print "Calling function get_fieldsets" if self.is_contributor(request): # this person is a blog_contributor fields_obj = fields[0][1].get('fields') try: fields_obj.remove('status') fields_obj.remove('user') fields_obj.remove('slug') fields_obj.remove('publish_date') fields_obj.remove('expiry_date') fields_obj.remove('allow_comments') fields_obj.remove('is_public') fields_obj.remove('categories') fields_obj.remove('access_level') fields_obj.remove('featured_category') fields_obj.remove('is_featured_caregiver') fields_obj.remove('is_featured_member') fields_obj.remove('is_featured_provider') except: log.error("Error removing items from … -
Why does a JavaScript file named 'index.js' not work in Django templates?
I am working on a Django project and my JavaScript file was not loading on the HTML template. After a lot of tinkering, what finally got the file to load was changing its name from 'index.js' to 'homepage.js' but I could have changed it to anything. I wanted to keep the file consistent with the HTML and CSS files that are named 'index.html' and 'index.css'. Why is this the case that 'index.js' failed to load? It doesn't seem like file name should matter. I am mainly curious but hopefully this could help others. -
NoReverseMatch at /vehicles/delete/1/ Reverse for 'detail' with keyword arguments '{'pk': ''}' not found
Please help. i setup an apps. my update is working but delete is not. it gives: NoReverseMatch at /vehicles/delete/1/ Reverse for 'detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['vehicles/(?P\d+)/$']. here is the code that i have: models.py: from django.db import models from django.core.urlresolvers import reverse class Vehicles(models.Model): vehicle_id = models.AutoField(primary_key=True) vin_number = models.CharField(unique=True, max_length=17, blank=True, null=True, error_messages={'unique':"VIN already exists"}) make = models.CharField(max_length=15, blank=True, null=True) model = models.CharField(max_length=15, blank=True, null=True) year = models.IntegerField(blank=True, null=True) vehicle_type = models.CharField(max_length=8) class Meta: managed = True db_table = 'vehicles' def get_absolute_url(self): return reverse('vehicles:detail', kwargs={'pk': self.pk}) views.py: from django.core.urlresolvers import reverse_lazy from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from . import models class VehicleUpdateView(LoginRequiredMixin, UpdateView): fields = '__all__' model = models.Vehicles template_name = 'vehicles/vehicle_form.html' class VehicleDeleteView(LoginRequiredMixin, DeleteView): model = models.Vehicles success_url = reverse_lazy('vehicles:all') template_name = 'vehicles/vehicle_confirm_delete.html' urls.py: urlpatterns = [ url(r'^$', views.VehicleListView.as_view(), name='all'), url(r'^(?P<pk>\d+)/$', views.VehicleDetailView.as_view(), name='detail'), url(r'^create/$', views.VehicleCreateView.as_view(), name='create'), url(r'^update/(?P<pk>\d+)/$', views.VehicleUpdateView.as_view(), name='update'), url(r'^delete/(?P<pk>\d+)/$', views.VehicleDeleteView.as_view(), name='delete'), ] vehicle_detail.html: <h1>VIN: {{ vehicle_detail.vin_number }}</h1> <p>id: {{ vehicle_detail.vehicle_id }}</p> <!--<p>vehicle_detail.vin_number</p>--> <p>make: {{vehicle_detail.make }}</p> <p>model: {{ vehicle_detail.model }}</p> <p>year: {{ vehicle_detail.year }}</p> <p>type: {{ vehicle_detail.vehicle_type }}</p> <p><a class="btn btn-warning" href="{% url 'vehicles:update' pk=vehicle_detail.vehicle_id %}">Update</a></p> <p><a class="btn btn-danger" href="{% url 'vehicles:delete' pk=vehicle_detail.vehicle_id %}">Delete</a></p> … -
Pros/Cons of Using Apollo Client with Relay plugin in Graphene-Django?
I'm really new to GraphQL so I used assorted sample code to build a GraphQL API in Django. Part of my work involved introducing Relay into the mix. Thus I ended up with code snippets like these: from graphene import relay interfaces = (relay.Node, ) class CreateWorkflow(relay.ClientIDMutation) def mutate_and_get_payload(cls, input, context, info): I built this somewhat in isolation. Meanwhile my front-end colleagues have been building an Angular 4 UI using the Apollo Client. We're currently engaged in a discussion of whether the presence of Relay in my server app provides any benefits to them using the Apollo Client. I'd be very interested to hear any pros or cons people might offer. Robert -
Django - How to move attribute to another model and delete it
I have the following scenario: class C(): y = models.Integer... z = models.Integer... class D(): y2 = models.Integer... z2 = models.Integer... I want to copy the data from the attribute y and paste it to y2. Ok, I created a data migration that does the work. In a nutshell: class Migration(migrations.Migration): def move_info_to_class_d(apps, schema_editor): objs = C.objects.all() for obj in objs.iterator(): d = D.objects.create(y2=obj.y) operations = [ migrations.RunPython(move_info_to_class_d) ] Notice that I also want to remove the attribute from the class C, so the code would look like this: class C(): z = models.Integer... class D(): y2 = models.Integer... z2 = models.Integer... Everything looks ok, right? Time to commit. Oh, wait! The next person who executes this code will get an error, because the data migration is trying to access an attribute that doesn't exist anymore (y in this case). Does anybody know a workaround to copy the attribute to another model class and then delete it from the source class? -
Django DateField greater than filtering not working
What could possibly cause this? (Pdb) Incident.objects.filter(incident_date__gt=curr_date)[0].incident_date datetime.date(2019, 7, 19) (Pdb) curr_date datetime.date(2017, 7, 26) Seems like the greater-than is just not working here. My model: class Incident(models.Model): incident_dt = models.DateTimeField(null=True, blank=True) incident_date = models.DateField(null=True, blank=True) -
How to save a file to a model using upload_to for dynamic paths
I am trying to create a folder for each users to put their project in. So their file will have the path ..\project\id\filename, id is the user id and filename is the name of the file. Now using the arguments allowed for upload_to (instance and filename) in the Filefield, I realize that instance.id will be None and the path to the file will be ..\project\None\filename instead of ..\project\id\filename. Now reading the Django documentation upload_to I saw this: In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field. My interpretation is that creating a new record and user_directory_path are not instantiated at the same time, that is, when I call create on Project model, instance.id will be None. My question is now, is there a way to get around this? While I see upload_to convenient, it is not necessarily convenient for dynamic path such as the one I am doing. I was thinking of creating the record, then adding the file path in an update, but I am in search of a way that can save everything in … -
Django maintain order of internal query in external query?
I have a profile model which refers to the default User model of Django. I want a list of users with increasing points. My Profile Model: class Profile(models.Model): username = models.ForeignKey(User, on_delete=None, primary_key=True) image = models.CharField(max_length=255, default="") points = models.IntegerField(default=0) views = models.IntegerField(default=0) def __str__(self): return self.username.username I am firing this query: users = User.objects.filter(username__in=Profile.objects.filter().order_by('-points').values('username__username')) print(users,Profile.objects.filter().order_by('-points').values_list('username__username')) And my output is <QuerySet [<User: aplha>, <User: baqir>, <User: beta>]> <QuerySet [{'username__username': 'beta'}, {'username__username': 'baqir'}, {'username__username': 'aplha'}]> Now here we see, Profile model is giving the usernames in the same order that I want to, but the user model is not maintain that order. How to I make it maintain the same order as the Profile returns. -
Chatbot using websockets in Angular 4 and Django
I am trying to create real-time chat between Django backend and Angular 4 frontend using PostgreSQL database. Let's assume that I would like to create chatbot for instance like A.L.I.C.E. I am not sure but it seems to me that the most optimal solution would be to use websockets? I am trying to get data from frontend, add it to the PostgreSQL database and then return a response. Content at this moment is not important, I would like to focus only on connection. I am trying to do this in the way shown below without positive results. Any suggestions? Django: settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "backend.routing.channel_routing", }, } routing.py: from channels.routing import route from backend.consumers import ws_add, ws_message, ws_disconnect channel_routing = [ route("websocket.connect", ws_add), route("websocket.receive", ws_message), route("websocket.disconnect", ws_disconnect), ] consumers.py: # In consumers.py from channels import Group # Connected to websocket.connect def ws_add(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) # Connected to websocket.receive def ws_message(message): Group("chat").send({ "text": "[user] %s" % message.content['text'], }) # Connected to websocket.disconnect def ws_disconnect(message): Group("chat").discard(message.reply_channel) Angular 4: websocket.service.ts: import { Injectable } from '@angular/core'; import * as Rx from 'rxjs/Rx'; @Injectable() export class WebsocketService { … -
django admin: Displaying all
I need to edit the admin interface for when someone looks at one of my models, Statement, and either tries to update an existing statement or edit it. I have two other models called Keyword and Context, both of which have a field called statements_assigned that create a many to many relationship with Statement. This way, keywords and contexts can be assigned to a variety of different statements. The issue I'm having is that I want, for an individual Statement via the admin interface, to have a display of all its associated keywords and contexts. Currently because a Statement has no field indicating its associated contexts and keywords, nothing about keywords or contexts appear on the admin interface page for Statements. I believe that if for Statement instance a, a.keywords_set.all() (or some variant of that) should be able to return all of the associated Keyword objects for instance a (if I'm wrong, please correct me). How can I make this displayed on the admin page? Even further, an ideal situation would be to have a user be able to enter in new Contexts and Keywords on the Statement submission page, because otherwise the only way to relate a keyword and … -
How to set up Django and React project without having to deal with CORS?
So I've been working on a React project that sends requests to the Django REST-API. The problem is, I can't seem to get around the problem of the CORS. The front end is totally isolated to the backend. In order to make sure the website works properly, I need to have Django serve the front end files. I'm not sure where to start, How do I set up Django + React environment so I don't have to deal with the CORS issue? -
Loading to trans tags in Djangocms-text-ckeditor
I am using the djangocms-text-ckeditor plugin to add text to my pages but amhaving one issue which is to do with translations. Currently I have added the load i18n at the top but whenever am using the text plugin and switch to source and directly type the html e.g. <h1>{% trans "My Heading" %}</h1>, it only shows `{% trans "My Heading" %}. It renders it as it is. Any help on how to use the trans tag inside the text plugin and get it to render correctly will be greatly appreciated. Thanks` -
Nginx fails when django app posts form and try to send a (gmail) email
in my Django+nginx app, I’m experiencing issues since I implemented a contact form which shall send a (gmail) email. <form method='POST' action=''>{% csrf_token %} {{ form|crispy}} <button class="btn btn-xl" type="submit">Send Message</button> </form> the view processing the form POST: if request.method == "POST": form = ContactsForm(request.POST or None) if form.is_valid(): form_nome = form.cleaned_data['nome'] form_email = form.cleaned_data['email'] telefono = form.cleaned_data['telefono'] form_message = form.cleaned_data['message'] from_email = settings.EMAIL_HOST_USER to_email = [from_email] subject = "test" contact_message = "%s: %s via %s"%( form_nome, form_message, form_email ) send_mail( subject, contact_message, from_email, to_email, fail_silently=False) return HttpResponseRedirect('#contact') else: form = ContactsForm() I read tons of q&a relative to my issue but no one fits my problem. In the server: uwsgi.ini [uwsgi] module=core.wsgi:application socket=/tmp/uwsgi_portfoliomga.sock master=True pidfile=/tmp/project-master_portfoliomga.pid processes=4 threads=10 vacuum=True max-requests=5000 harakiri=30 daemonize=/home/martina/www/portfoliomga/logs/portfoliomga.log stats=/tmp/stats_portfoliomga.sock nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable … -
Goodreads API and Django
I am trying to use Goodreads API in a Django project. I have setup a simple tag to extract the reviews_widget and am attempting to send the css style and html to a template. However, the style and html is not being registered when sent. Using {{reviews_widget}} shows the style and html as a string, but {% load reviews_widget %} does not show anything. book.html {% extends "base.html"%} {% block content %} <!-- Does not render --> {% load reviews_widget %} <!-- Shows response in string format --> {{ reviews_widget }} <!-- What is sent to template--> <!-- <style> #goodreads-widget { font-family: georgia, serif; padding: 18px 0; width:565px; } #goodreads-widget h1 { font-weight:normal; font-size: 16px; border-bottom: 1px solid #BBB596; margin-bottom: 0; } #goodreads-widget a { text-decoration: none; color:#660; } iframe{ background-color: #fff; } #goodreads-widget a:hover { text-decoration: underline; } #goodreads-widget a:active { color:#660; } #gr_footer { width: 100%; border-top: 1px solid #BBB596; text-align: right; } #goodreads-widget .gr_branding{ color: #382110; font-size: 11px; text-decoration: none; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } </style> <div id="goodreads-widget"> <div id="gr_header"><h1><a href="https://www.goodreads.com/book/show/31430654-the-millionaire-booklet"> The Millionaire Booklet Reviews</a></h1></div> <iframe id="the_iframe" src="https://www.goodreads.com/api/reviews_widget_iframe?did=DEVELOPER_ID&amp;format=html&amp;isbn=0990355454&amp;links=660&amp;min_rating=&amp;review_back=fff&amp;stars=000&amp;text=000" width="565" height="400" frameborder="0"></iframe> <div id="gr_footer"> <a class="gr_branding" target="_blank" href="https://www.goodreads.com/book/show/31430654-the-millionaire-booklet?utm_medium=api&amp;utm_source=reviews_widget"> Reviews from Goodreads.com</a> </div> </div> --> {% endblock … -
Why python-social-auth is deleting my first_name and last_name fields every time i login with steam?
It's very strange to happen, does anyone know how to fix it? All this is because I want to eliminate user creation and just leave external social networks. I will also implement Twitch.tv, although I have not tested it if it deletes it as well. Login (Template): Here I just put the button as it appears in the documentation. <a class="btn btn-steam" href="{% url "social:begin" "steam" %}" role="button"><i class="fa fa-steam" aria-hidden="true"></i> Login with Steam</a> Login views.py class UserLogin(TemplateView): success_url = 'timeline' template_name = 'registration/login.html' Settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = ['127.0.0.1','plxapp.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'easy_thumbnails', 'social_django', 'core.apps.CoreConfig', 'userprofile.apps.UserProfileConfig', 'posts.apps.PostsConfig', 'posts.templatetags.custom_filters', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'plaxed.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'plaxed.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Bogota' USE_I18N = True USE_L10N = True USE_TZ = …