Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django user_passes_test: Is it better to return False or raise a PermissionDenied?
According to django documentation, we can simply use the user_passes_test decorator to manage the access to a given view. The function called should return True or False depending on the test result. Now, I simply want to throw a 403 HTTP error when the test fails. Option 1 If I follow the documentation logic, I should: call the @user_passes_test(func, login_url='/errors/403') create a view def permission_denied(request): raise PermissionDenied update the urlpatterns in urls.py with: path('errors/403', views.permission_denied, name="error_403"), Option 2 Simply raise PermissionDenied in the test function instead of returning False (no need for the view and change or the urls.py) In terms of code readability, the second option seems cleaner. However, it breaks the logic of django. Would someone have an advice on which method is best? -
Render s3 template with context without actually downloading it?
I have my emails HTML on amazon-s3. I got the specific file from amazon-s3 and got its content in a variable. Now I need to render that email content with my context. Is there any way in Django to achieve it? Any built-in functions? I initially tried downloading that file from s3 but doing that was complete nonsense. So I tried this code of getting only the file content. s3 = boto3.resource( 's3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, region_name='ap-south-1' ) response = s3.Object(settings.AWS_STORAGE_BUCKET_NAME, 'static/seller_order_invoice_pdf.html').get() decoded_file = response['Body'].read().decode('utf-8').splitlines() render(None, decoded_file, context) I need to render my email content with the context I am passing. -
Connections Aborts with WinError 10053 after series of Errors in Python when using bootstrap.min.css in Django with SQL Lite
If you look at first few lines you will understand that bootstrap.min.css is linked and is accessed easily with no error. The error line starts with Favicon.ico not being available. Starting of Error The mark 1 in the image is when i open the localhost:8000. I added favicon.ico and related icons in the main directory But no luck. Ask for the things you require ...i'll reply as soon as possible. I have tried searching online and there is nothing i can find related to error which starts like this. I have all requirements complete as bootstrap is working. ERRORLOG CMD -
What's the name of the header progess bar on websites?
I'm trying to find the term for the progress bar of headers some websites now have (particularly many Microsoft documentation websites now). It seems similar to the concept of Breadcrumbs but is either a distinct version of them or something separate. An example of that I mean is here: https://www.agiliq.com/blog/2018/07/using-django-on-windows-with-wsl/ All similar search terms however (bar, breadcrumbs, headers, progress bar) have so many results for other irrelevant things that I can't seem to find the right phrase. My searching so far has landed me on breadcrumb-related sites that then discuss breadcrumbs in the header. After fairly exhaustive attempts my Google-fu has failed me; what should I be searching here? Also, my interest is particularly oriented toward implementing the same thing in a Django/Wagtail website. I'd be happy to just get the name of what I should be searching here, but if anyone has specific pointers toward good resources for how to implement in that framework that would be even one step better. -
Passing multiple responses to D3.csv function
I have a D3js website up and running. The approach I am following is getting files from aws S3 and creating url patterns and then use them with d3.csv functions. It is taking too much time to load all the visualizations because it is hitting AWS S3 five times to get 5 different CSVs as datasource. sample code for views.py is given below - def func1(request): LOCAL_PATH = '/var/www/dashboard/templates/graph/' AWS_ACCESS_KEY_ID = '*********' AWS_SECRET_ACCESS_KEY = '***********' bucket_name = 'bucket_name' # connect to the bucket conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(bucket_name) # go through the list of files bucket_list = bucket.list() for l in bucket_list: keyString = str(l.key) if os.path.exists(LOCAL_PATH+keyString): os.remove(LOCAL_PATH+keyString) #this deletes the file l.get_contents_to_filename(LOCAL_PATH+keyString) csv_data = open('/var/www/dashboard/templates/graph/file1.csv', 'r+').read() response = HttpResponse(csv_data,content_type='text/csv') return response I have created 5 functions for 5 files I have used as datasource for my dashboard. urls.py code - urlpatterns = [ path('', views.graph, name='graph'), path('func1/', views.func1, name='func1') ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = format_suffix_patterns(urlpatterns) I have added 5 url patterns for all the files. javascript file with d3.csv function - d3.csv("/func1/", function(data) { freqData = data.map(function(d) { return { hour: d.hour, freq: { val1: +d.val1, val2: +d.val2, val3: +d.val3, val4: +d.val4 }} }); dashboard('#id',freqData); }); The … -
Developing with celery and docker
I have noticed that developing with celery in container, something like this: celeryworker: build: . user: django command: celery -A project.celery worker -Q project -l DEBUG links: - redis - postgres depends_on: - redis - postgres env_file: .env environment: DJANGO_SETTINGS_MODULE: config.settings.celery if I want to do some changes on some celery task, I have to completly rebuild the docker image in order to have the latest changes. So I tried: docker-compose -f celery.yml down docker-compose -f celery.yml up Nothing changed, then: docker-compose -f celery.yml down docker-compsoe -f celery.yml build docker-compose -f celery.yml up I have the new changes. Is this the way to do it? seems very slow to me, all the time rebuilding the image, is then better have the local celery outsite docker containers? -
Django-rss-plugin not working for same origin urls
I am having trouble using the same origin URL in Django RSS plugin. I am using this plugin here to display feeds on my website. This is only a problem when the feeds I am using come from the same website e.g using local server my website is at http://127.0.0.1 and the feeds are accessed at http://127.0.0.1/rss. This never works. But if the website is at http://127.0.0.1 and feeds at a different server like http://www.example.com/rss this works well. Also using the website at http://www.example.com/rss to access feeds at http://127.0.0.1/rss works well I expect it to work with when the feeds and the website are on the same host address but this is not the case What might be the problem? -
AttributeError 'str' object has no attribute 'read'
I want to integrate my existing PHP app with new Django framework. I am using the django-php-bridge https://github.com/winhamwr/django-php-bridge What i want is to be authenticated into the django app by using existing PHP authentication method. I am able to generate session key by PHP and want to put it on Django Session table using the bridge. but i am running into errors. can you suggest a better alternative to the problem ? def _unserialize(): type_ = fp.read(1).lower() if type_ == b'n': _expect(b';') return None if type_ in b'idb': _expect(b':') data = _read_until(b';') if type_ == b'i': return int(data) if type_ == b'd': return float(data) return int(data) != 0 if type_ == b's': _expect(b':') length = int(_read_until(b':')) _expect(b'"') data = fp.read(length) _expect(b'"') if decode_strings: Request Method: | GET -- | -- http://localhost:8000/ 2.2.2 AttributeError 'str' object has no attribute 'read' C:\xampp\htdocs\test\dbs\env\lib\site-packages\phpserialize.py in _unserialize, line 473 C:\xampp\htdocs\test\dbs\env\Scripts\python.exe 3.7.3 ['C:\\xampp\\htdocs\\test\\dbs', 'C:\\xampp\\htdocs\\test\\dbs\\env\\Scripts\\python37.zip', 'C:\\xampp\\htdocs\\test\\dbs\\env\\DLLs', 'C:\\xampp\\htdocs\\test\\dbs\\env\\lib', 'C:\\xampp\\htdocs\\test\\dbs\\env\\Scripts', 'c:\\users\\arjun soota\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\arjun soota\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\xampp\\htdocs\\test\\dbs\\env', 'C:\\xampp\\htdocs\\test\\dbs\\env\\lib\\site-packages'] Thu, 20 Jun 2019 11:46:50 +0530 -
How to solve static files of other app can't load to my app in Django?
I use https://github.com/adamcharnock/django-adminlte2 as my template base. However, when debug false, static file use in that template can't not load. I tried to use python manage.py collectstatic but it doesn't fixed. How to make to load that template static files? May I need to copy all adminlte2 static file to project static folder? I use default wsgi server and there is no apache, nginx. I am totally new to django and python. -
Django send image with Json object and arrays
I have this view: class CommitmentList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = CommitmentSerializer .... and this serializer: class CommitmentSerializer(serializers.ModelSerializer): commitment = serializers.ListField(child=serializers.DictField(), write_only=True) class Meta: model = Commitment fields = .... my model: class Commitment(models.Model): signature = models.ImageField(upload_to='signatures/') dealer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='dealer_commitment') grower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='grower_commitment') is_original = models.BooleanField(default=True) I in json it look like: { "dealer": "123", "grower": "321", "signature": IMAGE HERE "commitment": [ { "brand": 3, "is_original": true, "commitment_unit": 300 } ] } In the postman i to try send data like this(for test) But in the postman i have an error: { "dealer": [ "This field is required." ], "grower": [ "This field is required." ], "commitment": [ "This field is required." ] } Then i tryed to add parser_classes = (MultiPartParser, ) in my view and it look like: class CommitmentList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = CommitmentSerializer parser_classes = (MultiPartParser, ) But now in the postman i have an error: A server error occurred. Please contact the administrator. And in Django project a have an error: AttributeError: 'NoneType' object has no attribute 'decode' How i can to send data like this?: { "dealer": "123", "grower": "321", "signature": IMAGE HERE "commitment": [ { "brand": 3, "is_original": … -
how to code to create a new table for every user register on site
As my site performing a specific task of user which need a db. So, how to code to create a new table in db every time a user register on site using django or mysql. -
How can I use fieldsets with a partial template in admin.py?
In admin.py I'm using fieldsets to display my fields in the change view. I want to keep using fieldsets, but also add a partial html template that renders an editable table on the same view. I've looked through the django docs and I haven't been able to find a way to include both fieldsets and add a template https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#modeladmin-objects -
How to efficiently check if name exists in database
I would like to efficiently check if a certain name is shared by any other name of the items of a shop Of course I could just cycle through all of the items in the shop and compare their names, but I'm sure that there is a contains() sort of method, just for the name. Perhaps using filter()? But how? There are too many broad answers and I can't figure it out for my unique problem models.py ... class Item(models.Model): item_name = models.CharField(max_length=200) ... class Shop(models.Model): shop_name = models.CharField(max_length=200) items = models.ManyToManyField('Product') ... views.py ... def check(name): if name in Shop.items.filter(name) # do something ... My code doesn't seem to pick up that there are any items with the same name in the shop (even though I can prove that there is) -
django serialize and deserialize object with SerializerMethodField
I'm using djangorestframework 3.7.7 I have 'Item' model which doesn't include 'owner' field. The item model serializer looks something like this: class ItemSerializer(serializers.ModelSerializer): id = serializers.CharField(required=False, max_length=1000, allow_null=True) owner = serializers.SerializerMethodField() class Meta: model = Item fields = [ 'id', 'owner' ] def get_reviewer(self, item): return item.package.reviewer if item.package else None When serializing it using: ser_item = ItemSerializer(item) I get the owner field in ser_item.data But when deserializing, using: serializer = ItemSerializer(data=ser_item) serializer.is_valid(raise_exception=True) obj = Item(**serializer.validated_data) The obj doesn't contain the owner field. It doesn't even seem to go through the serializer (when debugging). Any idea how can I deserialize so this fields, which is not part of the model will be part of the new instance? -
Is there any interest using more than 1 worker when you only have a singe core?
I'm currently setting up a Gunicorn application on a single core machine, and I have a limitation on memory so I would rather use 1 Worker and 8 threads than 2 workers with 4 threads. However, I still asking myself about a possible performance issue with a 1 worker configuration as on the Gunicorn official documentation recommend using the following setting. 2 * (number of cores) + 1 Considering the fact that with Python I'll be natively blocked by the GIL If I want true parallelism using threads, I still don't see any interest using more processes than the number of core. -
what is mysite.socket in uwsgi-tutorial?
i'm trying to find out configuration of Nginx , Uwsgi , django and socket to run my project on server . I found this tutorial , that I'm moving forward on it all the steps went well but know i'm stuck in this socket part.the error say 2019/06/20 02:31:37 [error] 9546#9546: *19 connect() failed (111: Connection re$ i try below as tutorial say: uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 # (very permissive) and uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=664 # (more sensible) but the problem still exist and same error appear in nginx log.any help to pass this step?thank you -
How to upload excel file and read it insert into database in dango
I want to read excel file and whatever that excel file containing data that data insert into MySQL when uploading excel file using Django -
Django-Haystack clear_index not deleting database entries
I am using django and haystack and my problem is that when I try to clear the index it does not remove the entries from the database. As a result, if I rebuild the index the documents appear again. Is this an issue of haystack or am I doing something wrong? Thank you in advance -
Recurring code in Django views: how to avoid repetition?
For many - but not all - of my views I have to do some validation to make sure the user that is logged in has access to the object they are trying to access. For 30+ views I have this code: def whatever_view_name(request, id, access_id): check = Access.objects.filter(user=request.user, id=access_id) if check: access_object = check[0] else: return redirect(reverse("create_new_access_object")) .... and now my view-specific code will follow ... So I need to check if a particular database record (Access) exists for this particular user. This code is repeated a lot, which does not seem to be right. I've been thinking about using middleware, but there are two problems: a) I need to use this object in the view (see variable access_object so I fear I'd have to query it twice if I put it in the middleware), and b) I don't need to do this ALWAYS so I wonder how to only run it for some views and not all if this is middleware. Any thoughts? -
Saving country name from country field
I need country selection field on my form, my models.py: class ContactForm(models.Model): first_name = models.CharField(max_length=10) Country = models.CharField(max_length=10) And my forms.py: from django_countries.fields import CountryField class UserContact(forms.Form): first_name = forms.CharField(label='your first name', max_length= 10) country = CountryField().formfield() My views: def get_data(request): form = UserContact() if request.method == 'POST': form = UserContact(request.POST) if form.is_valid(): ContactForm.objects.create(**form.cleaned_data) return render(request, '# some url', { 'form': form} My problem is, when I submit the the form, in my admin page, in my ContactForm model, I have my first name that I entered, and just the country code! Not the full name of the country. I don't know how to do that. But I know that I can get the country name in shell using: from django_countries import countries dict(countries)['NZ'] 'New Zealand' So, for example, I need the New zealand to be saved in my database, not NZ. -
Django REST not rendering form correctly
I have the following code, that should render a list of FooBars. I have two problems: The first is, when I uncomment the state, foo and bar objects, the list renders them with actual data from the database (they're choice fields), but when I leave them commented, it just displays the choice integer. The second problem is, that when I then navigate to rest/foo/1/?html_form=true and look at the HTML form, it only renders the state, foo and bar fields, if I leave them commented. I want to leave them uncommented, so that the user can view the actual data, however that disables me or the user from editing those fields. What am I doing wrong? rest.py class FooBarSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) #state = serializers.SerializerMethodField(label=_('State')) #foo = serializers.SerializerMethodField(label=_('Foo')) #bar = serializers.SerializerMethodField(label=_('Bar')) def get_state(self, obj): return obj.get_state_display() def get_foo(self, obj): return obj.get_foo_display() def get_bar(self, obj): return obj.get_bar_display() class Meta: model = FooBar fields = ('id', 'state', 'foo', 'bar', 'bool1', 'bool2', 'bool3') class FooBarViewSet(viewsets.ModelViewSet): serializer_class = FooBarSerializer permission_classes = (IsAuthenticated, IsAdminUser) queryset = FooBar.objects.all() def render_form(self, request, serializer, status): from django.shortcuts import render return render(request, 'foo/foobar_item.html', { 'intent_form': serializer, 'intent_style': {}, }, status=status) router.register(r'rest/foo', FooBarViewSet, 'foobaritem') -
Not Recognizing New Models When Trying to Load Data
I added a model in Django project after building my database. It's PostgreSQL, not the standard SQLite. My initial import line works. This runs: from project import model1 When I try to load data into this model, I get the following error. django.db.utils.ProgrammingError: relation "project_model1" does not exist Not sure how to fix this. Do I need to delete the database and start again. -
AttributeError at /swagger/ 'NoneType' object has no attribute 'title' django python rest api
i am using python rest framework api and i want to install this package on it for documenation my api on swagger : https://github.com/axnsan12/drf-yasg/ i installed rest framework and its working fine and i installed the packge and added that to installed packages and here is what i changed in my url.py : from django.contrib import admin from django.urls import include, path from rest_framework import routers from django.shortcuts import redirect from tutorial.quickstart import views from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) SchemaView = get_schema_view( openapi.Info( title="asdasdsad", default_version='v1', ), public=False, permission_classes=(permissions.AllowAny,) ) swagger_info = openapi.Info( title="Snippets API", default_version='v1', description="""This is a demo project for the [drf-yasg](https://github.com/axnsan12/drf-yasg) Django Rest Framework library. The `swagger-ui` view can be found [here](/cached/swagger). The `ReDoc` view can be found [here](/cached/redoc). The swagger YAML document can be found [here](/cached/swagger.yaml). You can log in using the pre-existing `admin` user with password `passwordadmin`.""", # noqa terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ) SchemaView = get_schema_view( validators=['ssv', 'flex'], public=True, permission_classes=(permissions.AllowAny,), ) and in the end i use paths like below : urlpatterns = [ path('', include(router.urls)), # re_path("^swagger(?P<format>.json|.yaml)$", SchemaView.without_ui(cache_timeout=0), name='schema-json'), path("swagger/", SchemaView.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path("redoc/", SchemaView.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('admin/', admin.site.urls), ] … -
How to apply discount to basket line?
New to Django-oscar and can't have answers on the official docs I'm trying to add a discount I tried this: line, created = self.request.basket.add_product(product=product, quantity=serializer.validated_data['quantity'], options=options) line.discount(discount_value=20, affected_quantity=1) line.save() and when I try to print basket.total_excl_tax_excl_discounts or basket.total_excl_tax I always get the same result (which is the total of basket no matter discounts I added) what am I missing ?? -
Dockerized Django app not applying unique constraint
I have two issues both of which are inter-related Issue #1 My app has an online Postgres Database that it is using to store data. Because this is a Dockerized app, migrations that I create no longer appear on my local host but are instead stored in the Docker container. All of the questions I've seen so far do not seem to have issues with making migrations and adding the unique constraint to one of the fields within the table. I have written shell code to run a python script that returns me the contents of the migrations file in the command prompt window. I was able to obtain the migrations file that was to be applied and added a row to the django_migrations table to specify the same. I then ran makemigrations and migrate but it said there were no changes applied (which leads me to believe that the row which I added into the database should only have automatically been created by django after it had detected migrations on its own instead of me specifying the migrations file and asking it to make the changes). The issue is that now, the new migrations still detect the following change …