Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostgreSQL/PostGIS Stack builder missing dlls (GeoDjango)
I've installed GeoDjango Spatial Database libraries using Enterprise DB Stack for Postgres 10 and it includes following packages. I am using Windows 10 OS and needed to setup GeoDjango. Please assist PostGIS 2.4.3 bundle includes PostGIS 2.4.3 w GDAL 2.2.3, GEOS 3.6.2, Proj 4.9.3, pgRouting 2.5.2, osm2pgrouting 2.3.3, ogr_fdw 1.0.5 But now on Python I get this error below and I tried many posted answers but couldn't make it work. Quick hint will be great help. Below is the error: (gigfinder) C:\Users\dell\gigfinder\gigfinder>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\dell\gigfinder\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Users\dell\gigfinder\lib\site-packages\django\core\management\__init__.py", line 324, in execute django.setup() File "C:\Users\dell\gigfinder\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dell\gigfinder\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\dell\gigfinder\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\dell\gigfinder\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\dell\gigfinder\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\base.py", line 299, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\utils.py", line 212, in … -
How to take input from dropdown list compare it to a value in the database and then run commands using the other relating values of the same model?
So I have this Model: class Mymodel(models.Model) name = models.CharField(max_length=256) model = models.PositiveIntegerField() year = models.PositiveIntegerField() and I have a dropdown as such: <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> I want the user to be able to click a button, and it take their input from the dropdown. Then compare it to values in the database, and once it finds one that matches to return the other values. And lastly have a way to use them in a function in the views.py file. -
Returning Request.Post data from template in Django
I am trying to get the quantity of single product in cart using request.post but its not returning anything. This is what my views.py file looks like: def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) entry_quantity = request.POST.get('entry_quantity') print(entry_quantity) return render(request, 'carts/test.html', {'my_cart': cart_obj, 'my_carts_current_entries': my_carts_current_entries}) This is what my template looks like at the moment: <!doctype html> <html> <head> </head> <body> <h4>These are the current items in your Basket</h4> <form method="POST"> {% csrf_token %} {% for cart in my_carts_current_entries %} {{ cart.quantity }} x {{ cart.product }} <br> {% endfor %} <input type="hidden" name='entry_quantity' value='{{ cart.quantity }}'> <button>Add to Basket</button> </form> </body> </html> I am expecting a console printout of the request.post entry quantity. Thanks in advance. -
Custom save method for images/avatars in Django - how to use.
So, I'm trying to do a little bit of compression of images as well as some other operations. I had a few questions...I have the following save() method for my user class: class User(AbstractBaseUser, PermissionsMixin): ... avatar = models.ImageField(storage=SITE_UPLOAD_LOC, null=True, blank=True) def save(self, *args, **kwargs): if self.avatar: img = Img.open(BytesIO(self.avatar.read())) if img.mode != 'RGB': img = img.convert('RGB') new_width = 200 img.thumbnail((new_width, new_width * self.avatar.height / self.avatar.width), Img.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.avatar= InMemoryUploadedFile(file=output, field_name='ImageField', name="%s.jpg" % self.avatar.name.split('.')[0], content_type='image/jpeg', size=, charset=None) super(User, self).save(*args, **kwargs) I had two questions - 1.) best way for deleting the old avatar file on save, if a previous avatar exists. 2.) What do I pass into InMemoryUploadedFile for the size kwarg? Is this the size of the file...in what unit/(s)?? -
Django is not showing the right path when clicking on a link
This is what it shows when you click on the link Page not found (404) Request Method: GET Request URL: http://localhost:8000/jobapplication/new/1 Using the URLconf defined in careal.urls, Django tried these URL patterns, in this order: ^$ [name='landing-index'] ^admin/ ^accounts/ ^taskmanager/ ^login/$ [name='login'] The problem is that I don't know why it is opening the link as http://localhost:8000/jobapplication/new/1, when it should be http://localhost:8000/taskmanager/jobapplication/new/1 This is what I have in the urls.py from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.contrib.auth import views as auth_views from landingpage import views as landingpage_views urlpatterns = [ url(r'^$', landingpage_views.index, name='landing-index'), url(r'^admin/', admin.site.urls), url(r'^accounts/', include('allauth.urls')), url(r'^taskmanager/', include('taskmanager.urls')), url(r'^login/$', auth_views.login, name='login'), ] This is in urls.py in the app taskmanager from django.conf.urls import url from . import views from taskmanager.views import * app_name = 'taskmanager' urlpatterns = [ # Task manager urls url(r'^$', JobApplicationIndex.as_view(), name='index'), url(r'jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'), url(r'jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'), url(r'jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'), url(r'jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'), url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'), # Company urls url(r'company/$', CompanyIndex.as_view(), name='company-index'), url(r'company/add/$', CompanyCreate.as_view(), name='company-add'), url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'), # Job Post urls url(r'jobpost/$', JobPostIndex.as_view(), name='jobpost-index'), url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'), # Statistics urls url(r'^kpi/$', views.kpi, name='kpi'), ] And this is what I have in views.py in taskmanager, related to … -
NoReverseMatch Django error when trying to view cart - using Python 3.6
I'm getting the following error, and I'm having trouble figuring out why. NoReverseMatch at /cart/ Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\\/add\\/(?P<product_id>[^/]+)$'] I had no problems until I made some changes to my template. I also changed my product's pk values but I'm guessing that shouldn't affect anything? I also used clearsessions to in case that might have been the problem. I think that Django is saying it can't find a match for the url that I'm providing, but everything seems right to me. I made some changes to my code, and tried to revert it to a previous state, but I'm still getting the same error messages. I'll present my code, and if you could tell me where I'm likely making a mistake, that would be awesome. Here is my product_detail.html template {% extends "buylist/Header.html" %} {% block content %} <p>{{product.name}}</p> <p>{{product.price}}</p> <form action="{% url 'add_to_cart' product.id %}" method="post"> {% csrf_token %} <input type="number" name="quantity" min="1" max="{{product.quantity}}"> <button type="submit">add</button> </form> {% endblock %} I use a form to link the url with the product url and add that to my cart Here are my associated urls.py and Views.py urls.py path('cart/', views.get_cart, name='cart'), path('cart/add/<product_id>', views.add_to_cart, … -
Returning Quantity of Current Cart Entry using Django View
I have the following view where I want to return the quantity of the current cart entry. def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) product_quantity = request.POST.get('product_quantity') return render(request, 'carts/test.html', {'my_cart': cart_obj, 'my_carts_current_entries': my_carts_current_entries}) How would I reference the current entry quantity, e.g. if there is an entry in the database called 23x Chicken Nuggets I want it to return the quantity. On the template if I return: {{ my_carts_current_entries }} it will return all the current entries but without the quantity. For clarity I have included an extract of my models.py from the said application: class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) count = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return "Cart:{} User:{} Items:{} Total:£{}".format(self.id, self.user, self.count, self.total) class Entry(models.Model): product = models.ForeignKey(Product, null=True) cart = models.ForeignKey(Cart, null=True) quantity = models.PositiveIntegerField(default=0) def __str__(self): return self.product.name -
How to save values not in a form into a database
I want to insert two calculated values into the database where they are not involved in an entry in the form. Finance balance and monthly payment are calculated and then sent to the database. The code below doesn't do it, so what can enable me to do it in record_input in views.py? Traceback C:\Python34\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) C:\Python34\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) C:\Python34\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) G:\NEA Computer Science\mysite\finance\views.py in record_input form += Customer(finance_balance=CustomerForm.clean_finance_balance(self) NameError: name 'self' is not defined The version of Django is 1.11.6. forms.py from django import forms from .models import Customer class CustomerForm(forms.ModelForm): def clean(self): super(CustomerForm, self).clean() if self.cleaned_data["list_price"] < self.cleaned_data["deposit"]: raise forms.ValidationError({"list_price": "List price cannot be greater than the deposit."}) try: if self.cleaned_data["interest_rate"] < 0: raise forms.ValidationError({"interest_rate:": "Interest rate must be greater than 0."}) except: raise forms.ValidationError({"interest_rate:": "Interest rate must be a positive number."}) if self.cleaned_data['payment_method'] != "Cash" and self.cleaned_data['list_price'] == self.cleaned_data['deposit']: raise forms.ValidationError({'payment_method': 'Payment method cannot be cash when list price and deposit are the same.'}) def clean_finance_balance(self): if self.cleaned_data["payment_method"] != "Cash": self.finance_balance = self.cleaned_data["list_price"] - self.cleaned_data["deposit"] else: self.finance_balance = 0 self.finance_balance = self.cleaned_data["finance_balance"] return self.finance_balance def clean_monthly_payment(self): if self.cleaned_data["payment_method"] != "Cash": # Formula for monthly … -
Advice on methodology for changing datasource of angular material2 datatable
I have an Angular Material2 Database component that I designed that is populated based on a service which makes an http call to my Django database using the django rest framework. I need to present several of these datatables in my website, each with different data using a different URL to the same backend datasource to get the data. I am new to Angular and to the optimal architecture for the language in designing the site. Do I: Create a new component for each datatable, passing the url to the service? Create a new component for each datatable and a new service for each url? Create a single datatable component with a controller and have it connect to the same service, passing the url? Should directives be used to modify the source of the datatable? Thanks for the help on this. I searched multiple places and can't find an example of the situation that I have. Connecting one datatable to an external source is very straight forward in design but multiple tables is a mystery of how best to design this in a DRY and component fashion. -
Django Database Conection to Postgres
im using the default base script to connect to my postgres db, in production using cpanel. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } but when i try run (env) ./manage.py makemigrations, return this line: FATAL: no pg_hba.conf entry for host "::1", user "databaseser", database "databasename", SSL off. Its possible to fix this by CPanel hosting or just editing the postgres config file?, and how? -
RabbitMQ too many unwanted queues
I'm using celery 4.0.2 with RabbitMQ 3.6.14, configured with five queues on four servers connecting to rabbitmq-server running on one of the servers. before a recent deploy on production server, every things just worked fine, but after that, RabbitMQ generates thousands of unwanted queue and after a few hours, RAM usage goes high (20G or higher), celery logs miss heartbeat from other celery servers and stop working. Look at /var/lib/rabbitmq/mnesia/<server_name>/queues shows thousands of files and rabbitmqctl list_queues shows those files: ... d143e25a2ffe4dbca881978d658739b1 1 6046df6f62bc422c981d416706fe4af2 1 4acc0d442fcd43a1b0ef379c370706b1 1 d24e24a680534e33a8572f38d29ea6cd 1 619f7c89b43c4400ad8bf4556ec968d6 1 ffa5a991910941d3a03b844f85880a26 1 41e66894e5c34ad5b32d3e4e6307138c 1 4dd03ac9171448759a7b964a91d7422b 1 24ff24e8fe074f5b979a9d4e4674ba08 1 16ff4b981c11422ca2d437a5fba05706 1 726271ce0ab04886acd7f59fd930dc82 1 c07a58e36fcd4623ae7c4210ef073bdf 1 .... I never created these files (manually or in the code). Also, deleting all mnesia/queues files and restart RabbitMQ works, but only for a few hours and again the same problem. I really appreciate for any help. -
Haystack with Elastic search autocomplete returning empty list - django
In my autocomplete function I am getting query but SearchQuerySet().autocomplete is returning empty list. Here is my models class ProductCreateModel(models.Model): user = models.ForeignKey('accounts.User', related_name='user',db_index=True, on_delete=models.CASCADE,editable=False) title = models.CharField(max_length=120,db_index=True,) slug = models.SlugField(max_length=255,unique=True,blank=True) description = models.TextField(max_length=250,db_index=True,) category = models.ManyToManyField('categories.SubCategory', related_name= 'product_category',db_index=True,) brand_name = models.CharField(max_length=120) Here is my search_index.py class ProductCreateModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True,template_name='search/indexes/catalogue/product_text.txt') user = indexes.CharField(model_attr='user',faceted=True ) title = indexes.NgramField(model_attr='title') description = indexes.NgramField(model_attr='description',null = True) category = indexes.CharField(model_attr='category' ) brand = indexes.CharField(model_attr='brand_name',faceted=True ) availability_region = indexes.CharField(model_attr='availability_region',faceted=True ) # district = indexes.CharField(model_attr='product_location.') def get_model(self): return ProductCreateModel def index_queryset(self, using=None): return self.get_model().objects.filter(publish_date__lte=datetime.datetime.now()) Here is my product_text.txt {{object.title}} {{ object.description|default:"" }} In views.py def product_autocomplete(request): print('hello',request.GET.get( 'query')) sqs = SearchQuerySet().autocomplete( content_auto=request.GET.get( 'query', ''))[ :5] print(sqs) s = [] for result in sqs: d = {"value": result.title, "data": result.object.slug} s.append(d) output = {'suggestions': s} print('hihi' ,output) return JsonResponse(output) When I search for product in my site it shows empty list as: Quit the server with CTRL-BREAK. [16/Feb/2018 01:30:03] "GET / HTTP/1.1" 200 3256 hello ne PUT http://127.0.0.1:9200/haystack/_mapping/modelresult [status:400 request:0.004s] [] hihi {'suggestions': []} Here query is getting correct but I don't know why the SearchQuerySet().autocomplete() is returning empty list? I am using django-version 2.0.1 ,django-haystack==2.5.1,elasticsearch==5.0.1 -
Custom User model in rest-auth: RelatedObjectDoesNotExist
I am trying to implement the registration using django rest-auth library. I followed every instruction from the installation and usage guide, including the part with a custom user serializer. And here the problems begin. We register a new user, confirm the email and when I try to update the user, i get the same error: "RelatedObjectDoesNotExist at /rest-auth/user/ User has no userprofile." I can't figure out how to make registration to create simultaneously a user and a profile for him. I know that this question has been asked before, but I didn't find anything that would explain why is this happening. I am looking for a bare-simple WORKING example of registration using django-rest-auth and a custom User model models.py: class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, related_name='profile') tagline = models.CharField(max_length=140, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @receiver(post_save, sender=User) def create_profile_for_user(sender, instance=None, created=False, **kwargs): if created: UserProfile.objects.get_or_create(user=instance) @receiver(pre_delete, sender=User) def delete_profile_for_user(sender, instance=None, **kwargs): if instance: user_profile = UserProfile.objects.get(user=instance) user_profile.delete() serilizers.py class UserSerializer(UserDetailsSerializer): curriculumVitaeLink = serializers.CharField(source="userprofile.curriculumVitaeLink", required=False) class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ( 'curriculumVitaeLink' ) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) curriculumVitaeLink = profile_data.get('curriculumVitaeLink') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if … -
Django TestCase creating new test_ functions with exec and setattr in setUp()
The code below is intended to get programmatically created tests to run, which isn't happening. class TestAdminGetViews(TestCase): def setUp(self): self.factory = RequestFactory() self.admin_user = models.UserManager.create_user(email='test@test.com',password='12387343ad!' ,user_type=utils.UserTypes.admin.name) self.client = Client() #create the test methods programmatically where URLNames.object.name = view.name for url in utils.URLNames: #an Enum object #is there a view associated with with this URLName? if callable(getattr(views,url.name)): #placeholder code just to see if tests run str_function = '''def test_{}(self):\n\tself.assertIs(True,True)\nglobal my_function\nmy_function = test_{}'''.format(url.name, url.name) exec( str_function ) print( my_function ) setattr(self,'test_' + url.name,my_function) #factory, admin_user, client and all the functions show themselves #as being attached to self print(str(self.__dict__)) The print function shows that the code runs "successfully". The dictionary contains factory, admin_user and client, all of which are accessable in the hard-coded test_ functions. The programmatically created functions also show in the dictionary with the correct name and function name. However, the Django test environment does not run the programmatically created functions. Why? A little background color: My last staging deployment had an undetected issue with GET requests. I'd like to avoid those simple errors in the future with tests. Instead of writing a new test_function() for every view, I'd like to create GET view tests programmatically. -
Validate two field uniqueness with ParentalKey
I am trying to validate two field uniqueness (product and attribute) with product being a ParentalKey from modelcluster.fields. However, if I try and add a record I get the following error: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: ProductAttribute has no product. If the record already exists then it runs without error. This makes me think that product doesn't get set until after the clean method is called Here is my model class ProductAttribute(Orderable, models.Model): def __init__(self, *args, **kwargs): super(ProductAttribute, self).__init__(*args, **kwargs) product = ParentalKey('products.Product', related_name='attribute') attribute = models.ForeignKey( 'products.ProductGroupAttribute', ) value = models.CharField( max_length=255, ) def clean(self, *args, **kwargs): if self.product.group.name != self.attribute.group.name: raise ValidationError({'attribute':'Product Group and Attribute Group must be the same'}) super(ProductAttribute, self).clean(*args, **kwargs) my question is, where would I validate those two fields together and be able to gracefully handle the error. I also tried unique_together however that throws a constraint error that I can't really handle gracefully. Thank you in advance. -
How to test Django's UpdateView?
As a simplified example, I've written an UpdateView for a Book model, as well as a ListView to redirect to upon success: from django.urls import reverse from django.views.generic import ListView from django.views.generic.edit import UpdateView from .models import Book class BookUpdate(UpdateView): model = Book fields = ['title', 'author'] class BookList(ListView): model = Book The Book model is defined as class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100, blank=True) def get_absolute_url(self): return reverse('books-list') where urls.py is from django.urls import path from books.views import BookUpdate, BookList urlpatterns = [ path('books/', BookList.as_view(), name='books-list'), path('book/<int:pk>/', BookUpdate.as_view(), name='book-update') ] In books/tests.py I've tried to write the following test: class BookUpdateTest(TestCase): def test_update_book(self): book = Book.objects.create(title='The Catcher in the Rye') response = self.client.post( reverse('book-update', kwargs={'pk': book.id}), {'author': 'J.D. Salinger'}) self.assertEqual(response.status_code, 200) book.refresh_from_db() self.assertEqual(book.author, 'J.D. Salinger') However, this test fails because the book's author appears not to be updated after the POST request, even after refreshing from the database: FAIL: test_update_book (books.tests.BookUpdateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/Scratch/book_project/books/tests.py", line 46, in test_update_book self.assertEqual(book.author, 'J.D. Salinger') AssertionError: '' != 'J.D. Salinger' + J.D. Salinger On the other hand, if I run the development server and fill out the fields manually, everything seems to work as expected. How … -
Django Add Toggle Button
I need to add a toggle button as I have two fields for a blog post is_draft and is_published. As only one of them should be true at once, how can I toggle between them? -
How to show multipul pdf's in django view
Is it possible to show multiple PDF files in the Django view, rather than just one? My current view shows just one class PdfView(View): def get(self, request, *args, **kwargs): for pdf in pdfs: with open('/path/to/pdf/file/' + pdf.title + '.pdf', 'r') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=' + pdf.title + '.pdf' return response I'd like to open as many pdf's as needed, but keep running into HTTP ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION edit: here is the traceback Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 86, in run self.finish_response() File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 128, in finish_response self.write(data) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 217, in write self._write(data) File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 328, in write self.flush() File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 41] Protocol wrong type for socket -
Django REST Framework - Contact Form?
I've built a Django based web-application with the REST framework and I now want to implement a contact form. This will just take a message and send an email to an admin. It should be a generic POST endpoint ie. website/contact as there are several pages which should use it ie. "Contact us" or "Support". How do I make this "safe" to use online, to stop spammers. I don't think a captcha is enough as if someone reads the Javascript + finds out the endpoint - they could abuse it? How should I do this? Help is greatly appreciated. -
How can I add a class atribute to django auth login form?
I've just install Django's default authentication app. It is working and everything but I am wondwering how could I change the css of the form. Say I have this: <form ...> <input type = "text" class = "input-class" placeholder = "user"> <input type="submit" value="login" /> </form> which would show a pretty form following the class in the text input. And then, I have the simple ugly login.html template for Django auth: <form method="post" action="{% url 'login' %}"> {% csrf_token %} <div> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </div> What I want to do is to get the second form with the css classes of the first. Is there a way of doing so without messing with models and forms? And, if not, can someone please show me the way? Thank you very much -
Static file not found
I am using Saleor and I am trying to add a new static folder called fonts into the static folder. When I add a file to static/images I can reference the file, but if I create a folder called fonts: static/fonts and add the same file to it, the file is not found in the browser. I have tried "npm run build-assets" and cleared Cached images and files in the browser but the font file is still not found. Works: <link href="{% static 'images/font-awesome.css' %}" rel="stylesheet" type="text/css"> Does not work: <link href="{% static 'fonts/font-awesome.css' %}" rel="stylesheet" type="text/css"> Any idea how to make new folders load into static files? BTW I feel like this must be a nodejs thing. -
Django (imagekit) uploading error: No such file or directory error - 502
Uploading large images, around 5+mb, gives me a 502 error in Django Admin. Nginx tells me its unable to open the file. Seems to be Nginx or Django image-kit related, not 100% sure. Someone familiar with this issue and a possible cause or fix? Seems similar to this question. I'm using Postgress, Gunicorn but this doesnt seem to have anything to do with it. Its running on a lightsale instance (AWS). Versions: Django==1.11.9 django-imagekit==4.0.2 Pillow==5.0.0 Nginx Errors: 2018/02/15 15:25:30 [error] 9532#9532: *2727 open() "/home/martijn/sunstudies-env/static/CACHE/images/image/NIU_2759_60_61_62_63_fused/e1f01586ba89638395c70565844891f2.jpg" failed (2: No such file or directory), client: 145.89.53.228, s$ 2018/02/15 15:25:30 [error] 9532#9532: *2725 open() "/home/martijn/sunstudies-env/static/CACHE/images/image/Luzzu_Marsaxlokk/7e015267fb3f426a7e78f378a84d3885.jpg" failed (2: No such file or directory), client: 145.89.53.228, server: tes$ $/1.1", upstream: "http://127.0.0.1:8000/adminschools/schoolimage/add/", host: "test.sunstudies.nl", referrer: "https://test.sunstudies.nl/adminschools/schoolimage/add/" Image Model: class Image(models.Model): key = AutoSlugField(always_update=True, unique=True, populate_from='alt') title = models.CharField(max_length=35, blank=True, null=True) alt = models.CharField(max_length=120) description = models.CharField(max_length=255, blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) large = ProcessedImageField(upload_to='image', processors=[ResizeToFit(1820, 1024, False)], format='JPEG', options={'quality': 70}, validators=[image_validator]) medium = ImageSpecField(source='large', processors=[ResizeToFit(1024, 680, False)], format='JPEG', options={'quality': 70}) small = ImageSpecField(source='large', processors=[ResizeToFit(270, 180, False)], format='JPEG', options={'quality': 70}) tiny = ImageSpecField(source='large', processors=[ResizeToFit(45, 25, False)], format='JPEG', options={'quality': 20}) Nginx Settings: server { #increase max file size to 20mb client_max_body_size 20M; proxy_read_timeout 300s; proxy_connect_timeout 75s; ... } ... … -
Running python script inside a functional test in Django
The project that I'm recently working on load initial data by running a script: python manage.py shell < add_initial_data.py I'm making functional tests now and have to call this command to load initial data in the test database. I'm trying to use subprocess.call and call_command to run that script but I can't find the option to redirect the script file to shell. Is there a way to do that? I've tried with subprocess.call(['python', 'manage.py', 'shell', '<', 'add_initial_data.py']) and call_command('shell', '<', 'add_initial_data.py') but gives error not recognizing < add_initial_data.py -
Django source files not updating when changing pages
Using Django 1.11 with Viewflow-Pro 1.04 This is probably a very simple question, but I've spent hours googling and reading and have come up completely empty. Each page of my app has various CSS/javascript files that it loads with script and link tags. However, when a user clicks a link and it redirects them to another page, the source isn't refreshed - it is still using the source from the previous page (which is often similar, but not the same). Refreshing the page fixes it, as it pulls the correct source. But basically I'm having to refresh the page every time I get redirected to a new page. This has proven hard to debug, since a lot of pages have the same source and so they "seem" to work correctly - but I think it only happens with links. If my view.py redirects users (using return render or similar) then it doesn't happen. It is just if a user clicks a link to jump from one part of my site to another. Anyone have a clue what it could be? I would include code samples, but it's affecting my entire project - if some specific code would be helpful let … -
while running command Heroku logs Errros are below
2018-02-15T18:19:55.377507+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=shoppingwave.herokuapp.com request_id=551a7986-4cd6-4b43-9b9a-9f1eb46a5bc4 fwd="157.50.221.99" dyno= connect= service= status=503 bytes= protocol=https