Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve faceook/linkedin Authentication process canceled error?
I have a project in AWS cloud9, when i tryed to login via LinkedIn or Facebook (i write my code in python and i use Django v1.8.4). After i Press the button "allow access" to my LinkedIn or Facebook account i get this error page: facebook linkedin Traceback: Environment: Request Method: GET Request URL: http://8011118167a14663bf26f276beae74fe.vfs.cloud9.us-east-2.amazonaws.com:80/complete/facebook/?redirect_state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR&code=AQCHwhQV29jyqzxZ8_qtAQD6D_baKZvcdaMOL889co7q6N_rerhEvteJ3-1iE-vIhyX87qAHfCTN4XgoFF0IQT_MyWHsIf28ggfZt3IqUMXFODBsXaYY_PJJCvDRniv20gqMF9Pq1Lm2L1x-OFAOsqLsIboYZDrmG6ceFpADyzdKOXZRsy44uiXKhZIzht3VI45je8JbWowZJa-YUcRD1zY5OQnniW5ujq3IYe2l0z6nha6hq7Lk0lzLD5BR4I5O9sd7CdMxeRXX0NBmc9Qz4av2j2xsiHQq9zBASy03dSwENwQ2veIOhpQCMrIkkXwfNGQ&state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR Django Version: 1.8.4 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_social_project', 'django_social_app', 'social.apps.django_app.default', 'facebook_auth') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/apps/django_app/utils.py" in wrapper 51. return func(request, backend, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/apps/django_app/views.py" in complete 28. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/actions.py" in do_complete 43. user = backend.complete(user=user, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/backends/base.py" in complete 41. return self.auth_complete(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/utils.py" in wrapper 232. raise AuthCanceled(args[0]) Exception Type: AuthCanceled at /complete/facebook/ Exception Value: Authentication process canceled I saw How to solve Authentication process canceled error? but It does not work. -
Having problems with a query in Django
I'm building my first app within Django and I'm trying to query a "load" based on the company that i've attached to the load. Here's the model in question. class Load(models.Model): company = models.ForeignKey(UserCompany, null=True, on_delete=models.CASCADE) load_number = models.IntegerField() carrier = models.CharField(max_length=255) pickup_date = models.DateField() delivery_date = models.DateField() shipper = models.CharField(max_length=255) consignee = models.CharField(max_length=255) po_number = models.CharField(max_length=255) pu_number = models.CharField(max_length=255) pieces = models.IntegerField() description = models.TextField() date_created = models.DateTimeField(blank=True, null=True) def publish(self): self.date_created = timezone.now() self.save() def __str__(self): return str(self.load_number) Now I'm trying to display a list on a page, but only display the loads attached to a specific company. The user needs to be attached to that company as well so here are my user models. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class UserCompany(models.Model): company_name = models.CharField(max_length=200) def __unicode__(self): return self.company_name def __str__(self): return self.company_name # User Model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Additional Classes profile_pic = models.ImageField(upload_to='profile_pics', blank=True) company = models.ForeignKey(UserCompany, null=True,on_delete=models.CASCADE) def __str__(self): return self.user.username Then i'm trying to query the "loads" within this view. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, get_object_or_404 … -
Deploying app on Heroku (code=H10 desc="App crashed") Issue
I tried to deploy my app on heroku, but somehow I got this error page. I've run "$ heroku logs" on terminal and got the following messages. 2017-12-23T16:14:37.940528+00:00 heroku[router]:at=error code=H10 desc="App crashed" method=GET path="/" host=www.textory.tw request_id=79f89451-07b7-45b8-bf6d-1230092bcc1a fwd="123.193.63.120" dyno=web.1 connect=5001ms service= status=503 bytes= protocol=https 2017-12-23T16:14:38.308115+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.textory.tw request_id=520f0dab-1a19-42ed-bee5-60846b6c7631 fwd="123.193.63.120" dyno= connect= service= status=503 bytes= protocol=https Here is my Procfile web: gunicorn textory.wsgi VENV *.pyc __pycache__ staticfiles db.sqlite3 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") STATICFILES_STORAGE ='whitenoise.storage.CompressedManifestStaticFilesStorage' -
Why do we pass request as a parameter in the render method of django?
I have noticed that when using the render() function, we pass request as the first parameter, what's the use of this? Also, can somebody explain using an example, when would it be necessary to use render() function instead of render_to_response() function for rending templates? -
How do Meta field names correspond to model attributes
I am writing a Django Model and different Forms to modify the model's data. For simplification let's say my model is as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField() # (...) some other properties __identity_card_front = models.FileField(blank=True) class IdentityCardForm(forms.ModelForm): class Meta: model = Profile fields = ('__identity_card_front',) My question is: must the fields names correspond to the attributes of Profile class (the exact name of the variables definition)? Do these strings determine the HTML form field name that will be searched in form validation? And if so, how can I customise it? I don't want to have to obligatorily call my field name '__identity_card_front', but instead maybe something like 'id_front', 'idf', etc. I have seen labels might be used, but I was not clear how Django treats fields tags. I could not find either a good explanation on the Docs without getting lost around low-level class definitions and properties. Note: I am using django-2.0 -
How to dynamically delete object using django formset
Imagine E-commerce shop. User opens his cart (order), sees products, want to delete a few. The question is how to delete it dynamically using ajax. here we render template with two "elements" - ORDER (order_form) which contains customer's information and SET_OF_ORDERED_ITEMS (formset) views.py def show_cart(request): OrderItemFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=0, can_delete=True) order = Order.objects.get(pk=request.session['order_id']) if request.method == 'GET': order_form = OrderForm(instance=order) formset = OrderItemFormSet(instance=order) return render(request, 'ordersys/cart.html', {'order_form': order_form, 'formset': formset}) elif request.method == 'POST': filled_form = OrderForm(request.POST, instance=order) filled_formset = OrderItemFormSet(request.POST, instance=order) if filled_form.is_valid() and filled_formset.is_valid(): filled_form.save() filled_formset.save() return redirect('catalog:index') else: return render(request, 'ordersys/cart.html', {'order_form': filled_form, 'formset': filled_formset}) template cart.html <form action="... > {{ formset.management_form }} # set of ordered_item forms {% for ordered_item_form in formset %} {{ ordered_item_form.id }} {{ ordered_item_form.instance.name }} {{ ordered_item_form.quantity }} <button type="button" onclick="delete_item_with_ajax();"> DELETE </button> {% endfor %} ... # here i render order_form's fields such as ADDRESS, PHONE_NUMBER... but it is not important for our example ... <button type="submit"> SUBMIT </button> </form> If user press "DELETE" button, it removes ordered_item_form element from the DOM and calls ajax function which passes ID of removable item to the function, which unties ordered_item from the order by deleting it from database. views.py def delete_order_item(request): … -
Django: how to send form data from one page to the next?
The basic problem is that I can not find out a way of taking the form data to pass on to the next page? Extra information: I read somewhere that I should use session, which seems sensible, however, serialization appears not to work with forms without a model, however, I could be wrong. When I click submit the error is 'AttributeError: 'BoundField' object has no attribute '_meta'. Form class ItemCounterForm(Form): item = CharField(max_length=30) counter = IntegerFeild(min_value=1, max_value=1000) def __init__(self, *args, **kwargs): super(ItemCounterForm, self).__init__(*args, **kwargs) View class ItemCounterView(View): FormSet = formset_factory(ItemCounterForm) def get(self, request, *args, **kwargs): context = { 'form': self.FormSet() } return render(request, 'app:template', context) def post(self, request, *args, **kwargs): form = self.FormSet(self.request.POST or None) if form.is_valid(): for single_form in form: data_form = serializers.serialize('json', single_form) request.session['form'] = data_form return HttpResponseRedirect(reverse_lazy('app:next_page') else: context = { 'form': self.FormSet() } return render(request, 'app:template', context) Thank you for your time. -
Configuring a uwsgi.ini file so that a DJango project will work within a Docker container
I am trying to set the uwsgi.ini file so that it will work with a docker container. In the Dockerfile, I have exposed port 8888. Below are the pieces of the Dockerfile that are related to this problem: Dockerfile EXPOSE 8888 ENV DOCKER_CONTAINER=1 #CMD ["uwsgi", "--ini", "/code/uwsgi.ini"] <<< right now, this is commented out CMD ["/bin/bash"] Above, the CMD to run the uwsgi.ini file is commented out because, for me, it did not work initially. I changed the CMD to "/bin/bash" so that I could log in to the OS level of the container. After doing so, I then ran the code below: uwsgi --http 923b235d270e:8888 --chdir=/code/backendworkproj --module=backendworkproj.wsgi:application --env DJANGO_SETTINGS_MODULE=backendworkproj.settings --master --pidfile=/tmp/backendworkproj-master.pid --socket=127.0.0.1:49152 --processes=5 --uid=1000 --gid=2000 --harakiri=20 --max-requests=5000 --vacuum Once complete, I was able to go to port 8888 on the machine and see the website. So, in short, everything worked. The problem I am facing now is to convert the command above to something that will work in the uwgsi.ini file If you look at part of the command above, I used : --http 923b235d270e:8888 to specify a port. The 923b235d270e is associated with the container (since 127.0.0.1 did not work) How can I represent this (and env variables … -
How to include an excel spreadsheet during Heroku build
I'm building a Python application using Django, and deploying using Heroku. Because we have a large number of constants (that we occasionally change), we load them from an Excel spreadsheet (or csv file, both would work). When testing code locally, the Excel file is placed in the same folder as the Python code and loads correctly. However, when we deploy the very same project, Heroku does not seem to 'include' the Excel file. Our program crashes whenever we run a Python script that tries to load the Excel spreadsheet. Any idea how to tell Heroku to include the Excel file during deployment, so it runs as it would when testing code? -
Using Select2 autocomplete with Django project does not work while fetching the data
In my project, I have a Search field. I used Select2 autocomplete with it. I needed to fetch the product_list from my Product model. So I created a rest API that returns the product in json formats. Here is my rest API code: serializer.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = ProductList fields = ('product_id', 'product_name', 'product_image', 'product_available', 'product_description') views.py: class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) def list(request): if request.method == 'GET': products = ProductList.objects.filter(product_name__icontains=request.GET.get('q')) serializer = ProductSerializer(products, many=True) serializer_data = serializer.data customData = {'results': serializer_data} return JSONResponse(customData) Now in my html, in the javascript portion I used this code mentioned in this Select2 doc. The code I used, looks like this: base.html: <script type="text/javascript"> $(document).ready(function() { $('.js-data-example-ajax').select2({ ajax: { url: "/api.alif-marine.com/search/products", dataType: 'json', delay: 250, type: 'GET', data: function (params) { return{ q: params.term, // search term page: params.page }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.results, }; }, cache: true }, placeholder: 'Search for a product', escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 1, templateResult: formatRepo, templateSelection: formatRepoSelection }); function formatRepo (repo) { if (repo.loading) … -
How do I use allow_tags in django 2.0 admin?
Support for the allow_tags attribute on ModelAdmin methods is removed. -
Celery worker concurrency
I have make as scrapper to scrap around 150 Link Each link has around 5k sub link to get info from them i am using celery to run the scrapper in background and store data on Django ORM , i use beautifulSoap for scrap URL When i running the celery using this command celery worker -A ... --concurrency=50 everything working fine but the workers from 1 to 50 sleep how i can make the celery working till the scrapper finish his task -
Can't load homepage.html in templates folder in Django project
Below is the error message: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /var/www/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/dist-packages/django/contrib/admin/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.4/dist-packages/django/contrib/auth/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/site1222/littlethings/templates/homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/site1222/resume/templates/homepage.html (Source does not exist) And here is my project layout, sorry about the image quality: homepage.html is located in site1222/templates/homepage.html. I don't know where went wrong. -
Django queryset count() method raise "TypeError: unorderable types: NoneType() > int()"
My environment is Python3.5, Django1.8.3 and cx_Oracle5.3(They are checked by pip3 freeze). Django query set raises a Type Error exception when count() method is called. When it comes to Python2 + cx_oracle or Python3 + sqlite3 works fine without any exception but Python3 + cx_oracle. Thue, I tried to update cx_Oracle version to 6.1(latest version) because I thought I could be some compatibility problem between cx_Oracle and Python3. However, It generates a different error. I detail with the below code block, please refer it. P.S: I Need to keep Django version to 1.8.3 for compatibility with my Apps. models.py from django.db import models class Device(models.Model): deviceClass = models.CharField(max_length=10) class Meta: db_table = 'TST_G2S_DEVICE' cx_Oracle5.3 $ python3 manage.py shell Python 3.5.2 (default, Nov 23 2017, 16:37:01) Type "copyright", "credits" or "license" for more information. IPython 2.4.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: from polls.models import Device; In [2]: dev = Device.objects.all() In [3]: dev Out[3]: [] In [4]: type(dev) Out[4]: django.db.models.query.QuerySet In [5]: dev.count() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-72a7bdf9f7f7> … -
Referencing SQL model in mongoengine model field
I'm using mongoengine in my workout calendar Django project to store workouts with varying fields, depending on which lifts a user has done, how many of them, etc. I have defined a Workout object that represents one workout done by one person at a certain date. class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) Some of you might notice that there is no field representing the person who did the workout. That is where my question comes in. In my Django project, I have defined a custom User model that I've used instead of the normal django.contrib.auth.models.User object: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( unique=True, }, ) This model is a normal Django model, and is represented in an SQL database, SQLite in my case. I would like this model to act as the user field in my Workout mongoengine model. Something like this: class Workout(Document): id = IntField(unique=True, null=False) date = DateTimeField() lifts = EmbeddedDocumentListField(LiftSerie) cardio = EmbeddedDocumentListField(CardioSerie) person = ReferenceField(User) #New row Is this possible to achieve in some way? Or do I need to introduce redundancy to my web app by simply adding an email … -
Django: how to correctly pass an URL in include template tag?
In two different templates, I have two blocks almost identical, only the url is different: template1.html <div class="col-sm-4"> <a href="{% url 'bo:article-list' %}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> </div> template2.html <div class="col-sm-4"> <a href="{{ article.get_absolute_url }}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> </div> I'd like to make this dry, creating a template, and making an include then. For example: _cancel.html <div class="col-sm-4"> <a href="{{ cancel_url }}" class="btn btn-block btn-secondary btn-sm" role="button"> <i class="fa fa-chevron-left"></i> Annuler </a> For template2.html, it will work with: {% include 'includes/_cancel.html' with cancel_url=article.get_absolute_url %} But what about template1.html ? This obviously does NOT work : {% include 'includes/_cancel.html' with cancel_url={% url 'bo:article-list' %} I guess there is a trick. Thanks for your help :) -
OneToOneField is nor related
this me again. I have some trouble with my code. I made a form from ModelForm which have a model with 8 attributes, but i want to user fill only one of them,and one from the system. The one that user fill is okay, but the one filled with system is not working. models.py class SeminarProposal(md.Model): # diisi oleh mahasiswa fileProposal = models.FileField() # This is the one is filled with system proposal = models.OneToOneField(Proposal, on_delete=models.CASCADE, related_name="propSid", unique=True, blank=True, null=True) masabimbingan = models.BooleanField(default=True) # disi oleh admin tanggal = models.DateField(default=timezone.now, blank=True,null=True) tempat = models.CharField(max_length=30, blank=True, null=True) # diisi oleh dosen pembimbing dospemsetuju = models.BooleanField(default=False, blank=True) # diisi oleh kaprodi penguji1 = models.ForeignKey(Dosen, on_delete=models.CASCADE, related_name="penguji1", blank=True, null=True) penguji2 = models.ForeignKey(Dosen, on_delete=models.CASCADE, related_name="penguji2", blank=True, null=True) def __str__(self): return "Sidang untuk " + self.proposal.judul view.py def daftarSeminar(request): if request.method == 'POST': form = FormSeminar(request.POST, request.FILES) print(request.user) if form.is_valid(): form.save(commit=False) form.cleaned_data['proposal'] print(request.user) prop = Proposal.objects.get(akun=request.user) form.proposal = prop print(form.proposal) #to confirm that this is not None form.save() return redirect('proposal:bimbingan') else: return render(request, 'sidprop.html' , {'oke': 'oke'}) return redirect('proposal:index') form.py class FormSeminar(forms.ModelForm): class Meta: model = SeminarProposal fields = ['fileProposal','proposal'] Thanks in advance. Terimakasih. -
django_apscheduler remove_all_jobs on django startup
I have used django_apscheduler to schedule jobs. And it's working fine. When I start server new job is added and periodically it's doing what I need to do. However if I exit django and start it again then django will fail with error. apscheduler.jobstores.base.ConflictingIdError: u'Job identifier (myapp_db.jobs.test_job) conflicts with an existing job' Basically old job exists in database and new job can not be created. How can I remove all jobs during django startup. I notice there is remove_all_job() function in apscheduler but I do not know from where to execute it? I'm starting job.py from url.py with import myapp.jobs Thanks. -
invalid view function or pattern name in Django project
I keep getting an error which says "Reverse for favourite not found". It has something to do with either my favourite function in the views.py or presumably the way I have called it in the detail.html file. music/views.py code from django.shortcuts import render, get_object_or_404 from .models import Album, Song # Create your views here. #each URL is connected to a view or an Http Response def index(request): all_albums = Album.objects.all() return render(request,'music/index.html',{'all_albums':all_albums}) def detail(request,album_id): album = get_object_or_404(Album,pk=album_id) return render(request,'music/detail.html', {'album':album}) def favorite(request,album_id): album = get_object_or_404(Album,pk=album_id) try: selected_song=album.song_set.get(pk=request.POST['song']) except(KeyError,Song.DoesNotExist): return render(request,'music/detail/html',{ 'album':album, 'error_message':"You did not select a valid song", }) else: selected_song.is_favorite=True selected_song.save() music/templates/music/detail.html code <img src="{{album.album_logo}}"> <h1>{{album.album_title}}</h1> <h3>{{album.artist}}</h3> {% if error_message %} <p>{{error_message}}</p> {% endif %} <form action="{%url 'music:favorite' album.id %}" method="post"> {%csrf_token%} {%for song in album.song_set.all%} <input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}"> <label for="song{{forloop.counter}}"> {{song.song_title}} {%if song.is_favorite%} <img src="http://www.iconninja.com/files/51/927/609/favourite-favorite-star-bookmark-icon.png"/> {%endif%} </label><br> {%endfor%} <input type="submit" value="Favorite"> </form> Error message: (on page load) The error message seems to suggest that the favourite function is not valid, but I cannot see what I have done wrong. NoReverseMatch at /music/1/ Reverse for 'favorite' not found. 'favorite' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/music/1/ Django Version: 2.0 … -
how to switch to path instead of url in urlpatterns [django]
django noobie. ive been going through tutorials but in urlpatterns they use url instead of path which is now introduced in django 2.0 i want to make /appname/anything-gibberish take the user back to the view im giving in /appname/ urlpatterns = [ path('', views.index, name='index'), path('contact/', views.contact, name='contact'), ] i want 127.0.0.1:8000/contact/asaskhask to go to views.contact is there any way to do this without using url and regular expression? -
How to create a survey with some options in django
I want to create survey. I have below models: class Survey(models.Model): question = models.CharField(max_length=100) description = models.CharField(max_length=500, blank=True, null=True) end_date = models.DateTimeField() class SurveyOptions(models.Model): survey = models.ForeignKey(Survey, related_name='s_id', on_delete=models.CASCADE) text = models.CharField(max_length=50) the survey options might be 2 or 3 or 10 or etc. How can I create that? I don't know how to create a form for it. I googled it, but I didn't find any useful links. I need an example of it. thanks. -
Override setting for unittest in django
django version: 1.11, python version: 3.6.3 When writing unit tests, avoiding interaction with external services (for example the filesystem or network) is considered best practice because you can’t rely on external services’ availability, nor do they present a consistent, predictable state when running your tests. I have a model which uses a custom storage location for image: from django.conf import settings from django.db import models from django.core.files.storage import FileSystemStorage class Example(models.Model): media = models.ImageField( storage=FileSystemStorage(location=settings.PROTECTED_ROOT) ) protected root is defined in settings.py: PROTECTED_ROOT = os.path.join(BASE_DIR, "cdn", "protected") then in the tests.py: import tempfile from example_app.models import Example from django.test import TestCase, override_settings from django.conf import settings temp_directory = tempfile.mkdtemp() @override_settings(PROTECTED_ROOT=temp_directory) class LoginTestCase(TestCase): @classmethod def setUpTestData(cls): cls.example = Example.objects.create( media = 'mock_file_or_image' ) To avoid the file system for as much as possible i would like to use temporary directory, however, files are still added to PROTECTED_ROOT, why? What can i do about it? Or is my thought process completely off and should i go for a different approach altogether? -
Preventing security exceptions in production
I am developing a Django App and I was writing a method in a class model when I realised that there was a possibility in which I would accidentally call the method with a key out of the dictionary that it uses to check the Tier level: def has_tier(self, tier_code="01A"): # it defaults to tier 1 current_tier = self.__verification_tier() # Type: int tiers = {'00X': 0, '01A': 1, '02A': 2, '02B': 3} required = tiers[tier_code] return bool(current_tier >= required) I was going to write a try-except clause since I thought: what if in production the method is accidentally called with a tier level out of the dictionary and it raises a KeyError? But then I also thought: that won't possibly happen since I am the one writing the validations and manually injecting the string into the method, it is not user input that might "mis-processed". Also if I don't catch the exception, I might assure in development stage that the application won't rise any error once all of its functionalities are tested. That way I am able to correct all the errors. I also thought that I could implement a logging module that writes into a file/database all the exceptions … -
Static file in django without Using {% static "abc.jpg" %}
I had static files in django. Project Structure Sample I have project structure like above i want to use js and img from asset folder. How can i do this ? How i can avoid using {% static "abc.jpg" %} ? -
Custom primary key in Django model
Here is my model: class InvitationCode(models.Model): code = models.CharField(max_length=6, primary_key=True) group = models.OneToOneField(Group, on_delete=models.PROTECT) According to doc, primary_key=True implies null=False and unique=True. However this is not what I see: >>> from app.models import InvitationCode >>> c = InvitationCode(group_id=1) >>> c.save() >>> c.pk '' >>> c1 = InvitationCode(group_id=1) >>> c1.save() >>> InvitationCode.objects.all() <QuerySet [<InvitationCode: InvitationCode object ()>]> Why Django allowed me to have primary key as empty string? Why uniqueness constrain didn't work?