Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django inheriting testCases
How can I use subclassing for Django Test case for setUpTestDate(cls) Following code without setUpTestData() works just fine when subclassing, however, if I call super().setUpTestData(), I am getting setUpTestData() missing 1 required positional argument: 'cls' Can we inherit setUpTestData()? because I need to create carrier and dispatcher before setUp is called class DashboardTestCase(TestCase): password = '12345' def authenticate(self): self.client.login(username=self.dispatcher.email, password=self.password) def setUp(self): self.authenticate() def setUpTestData(cls): password = '12345' cls.carrier = Carrier.objects.create( .... ) cls.dispatcher = Dispatcher.objects.create( ... ) cls.dispatcher.set_password(password) cls.dispatcher.save() -
non_form_errors doesn't show
I am working with inlineformset_factory and created a forms.BaseInlineFormSet to override the clean function to make some validations. the validation works and the form isn't accepted but the ValidationError message doesn't appear when the page is reloaded. here is my form class: class BaseDetailFormSet(forms.BaseInlineFormSet): def clean(self): super(BaseDetailFormSet, self).clean() if any(self.errors): return self.errors for form in self.forms: product = form.cleaned_data['product'] if form.cleaned_data['quantity_sold'] > product.quantity_in_stock: raise forms.ValidationError(_('not enough products')) DetailFormset = inlineformset_factory(Invoices, InvoiceDetail, fields=('product', 'quantity_sold'), widgets= {'product': forms.Select( attrs={ 'class': 'search', 'data-live-search': 'true' })}, formset=BaseDetailFormSet, extra=1) and my html code: <form class="form-inline" method="post" action=""> {% csrf_token%} {% include '_layouts/form_snippet.html' %} <table class="table"> {{inlines.management_form}} {%for form in inlines.forms%} {% if forloop.first%} <thead> <tr> {%for field in form.visible_fields%} <th>{{field.label|capfirst}}</th> {%endfor%} {%endif%} </tr> </thead> <tr class="formset_row"> {{ form.non_form_errors }} {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <button type="submit" value="Add" class="btn btn-inverse">{% trans 'Submit Invoice' %}</button> </form> any ideas how to show the validation error message or why it isn't shown. -
How to design crawler process bar in django?
I want to design crawler process bar in django. When I click start button, the process bar will show the crawler is working. But I don't know how to design because I don't know when the crawler ends. -
How to create a custom testsuite and run testsuite for a django app using mongodatabase
I have a django app structure /myapp /myapp/obj1/.. /myapp/obj1/views.py /myapp/obj1/forms.py /myapp/obj2/.. /myapp/obj2/views.py /myapp/obj2/forms.py /myapp/tests/.. /myapp/tests/__init__.py /myapp/tests/obj1.py /myapp/tests/obj2.py I can run each test file under tests directory of django app using python manage.py test myapp.tests.obj1.py Can u help me to create a testsuite and run testsuite of all testcases as report file in django? -
With Django, why do I get 404 errors on static resources during login?
I know very little about Django. I am taking over a project that was developed by someone else. I was asked to implement a new design. Now suddenly I get an error when I try to log in. I get a broken page, which I'm not supposed to see, as it is should simply redirect me to my the user's profile page. Instead, this happens: [31/Jan/2018 13:28:47] "POST /accounts/login/ HTTP/1.1" 200 2829 [31/Jan/2018 13:28:48] "GET /static/core/bundles/main.css HTTP/1.1" 404 1787 [31/Jan/2018 13:28:48] "GET /static/core/img/sugar-notagline-23may.jpg HTTP/1.1" 404 1826 [31/Jan/2018 13:28:48] "GET /static/core/img/tools.png HTTP/1.1" 404 1778 [31/Jan/2018 13:28:48] "GET /static/core/img/library.png HTTP/1.1" 404 1784 [31/Jan/2018 13:28:48] "GET /static/core/img/filter1.png HTTP/1.1" 404 1784 [31/Jan/2018 13:28:48] "GET /static/core/img/settings.png HTTP/1.1" 404 1787 There is the main.css file here: ./sugarlab/core/static/core/bundles/css/main.css I don't get why that is a 404, since on other pages it seems to be included fine. The images don't exist, but that shouldn't matter, because this page is not supposed to be shown to the user. Assuming I've broken some redirect mechanism, what should I be looking for? How would this redirect normally be handled? -
AngularJS $http request fails with custom headers
I am trying to add a custom header to my common request like so: myApp.config(['$httpProvider', function ($httpProvider) { // $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; $httpProvider.defaults.headers.common['test_key'] = 'kkkkk'; }]); Without the above header request works fine. but when added gives the following error: { "data": null, "status": -1, "config": { "method": "GET", "transformRequest": [ null ], "transformResponse": [ null ], "jsonpCallbackParam": "callback", "url": "http://localhost:8900/tt/", "data": {}, "headers": { "Accept": "application/json, text/plain, */*", "test_key": "kkkkk" } }, "statusText": "", "xhrStatus": "error" } On server side I have Django with Django Rest Framework. Server side code is very simple: from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def test(request): return Response({'ddddddd'}) urlpatterns = [ url(r'^tt/$', test) ] What am I doing wrong? How should I add these headers? -
Celery does not start multiple workers
I am trying to set up a server to run multiple workers on Ubuntu using celery. Set up the daemon using the generic scripts and using rabbit-mq as the broker. celery==3.1.23 django-celery==3.1.17 django-celery-beat==1.0.1 /etc/default/celeryd - (internally using celery multi start RRR SSS TTT STST OTS ...) CELERYD_NODES="RRR SSS TTT STST OTS" CELERYD_OPTS="-c 4 -Q:RRR r,e,h -Q:SSS s,p -Q:TTT d -Q:STST sd -Ofair --detach --time-limit=1500 CELERYD="/x/home/ks/wb/manage.py celeryd" $ service celerd start $ ps -ef | grep celery /etc/init.d/celeryd start root 25636 25631 0 01:37 pts/4 00:00:00 /usr/bin/python /usr/local/bin/celery multi start RRR SSS TTT STST OTS -c 10 --uid=celery --gid=celery --workdir=/x/home/ks/wb --pidfile=/var/run/celery/%n.pid --logfile=/var/log/celery/%n.log --loglevel=DEBUG --cmd=/x/home/ks/wb/manage.py celeryd -Q:RRR r,e,h -Q:SSS s,p -Q:TTT d -Q:STST -Ofair --detach --time-limit=1500 celery 27440 25636 0 01:53 pts/4 00:00:01 [celeryd: STD@dt:MainProcess] -active- (--time-limit=1500 -c 4 --executable=/usr/bin/python --gid=celery --detach --logfile=/var/log/celer/STD.log -n STD@dt-ss-app-3040 --loglevel=DEBUG --uid=celery --pidfile=/var/run/celery/STD.pid --workdir=/x/home/ks/wb -Ofair -Q standard) celery 27452 27440 1 01:53 pts/4 00:00:05 [celeryd: STD@dt:Worker-1] celery 27453 27440 0 01:53 pts/4 00:00:01 [celeryd: STD@dt:Worker-2] celery 27455 27440 0 01:53 pts/4 00:00:01 [celeryd: STD@dt:Worker-3] Only one worker (STD) gets started. The other workers are not starting. when I tried to stop the service service celeryd stop Worker STD stops and another worker RRR starts. which signifies that … -
Django tag based on model and view not showing on webpage
I am trying to show another table with postgresql data on my django webpage. The page does show the normal HTML content, but it is not showing the postgresql data. Interestingly, the Django shell does indicate the data is available: In [1]: Companystats.objects.all() Out[1]: , etc I tried: restarting the server (python3 manage.py runserver) python3 manage.py makemigrations python3 manage.py migrate Simplified code: HTML webpage {% for compstat in compstats %} {{ compstat.symbol }} {% endfor %} models.py class Companystats(models.Model): company_name = models.TextField(blank=True, null=True) symbol = models.TextField(primary_key=True) class Meta: managed = False db_table = 'companystats' views.py from django.shortcuts import render from .models import Companystats def companystats_list(request): compstats = Companystats.objects.all() return render(request, 'blog/post_list.html', {'compstats': compstats}) any ideas on what i could try to fix it would be very much appreciated. -
Passing a costant in a template using include filter with variables
In a custom widget I have: <img src="{% static 'img/placeholders/whitepaper-color.png' %}" height="80" width="90"/> I want the src to contain a variable that I sent using a template with variables, something like: {% include "name_snippet.html" with variable='whitepaper-color.png' %} It is possible tto take this variable from constants ? I know that I can attach the constants to the view, but I have a more complex situation using multiple formsets(some of them derived from same model) etc. So I want to see if there is a more cleaner way. -
ModuleNotFoundError: No module named 'googlemaps'
I am a newcomer to Django python programming. Now I am working on the server side. I want to use google maps API, my view.py is like this: from django.shortcuts import render from django.shortcuts import HttpResponse from googlemaps import * # Create your views gmaps = googlemaps.Client(key='A') def index(request): if request.method=="GET": geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA') return geocode_result Also, I have already installed 'googlemaps' using pip. And when I import it in IDE, nothing goes wrong. But when I want to start the server to test the code, the server won't run and tells me ModuleNotFoundError: No module named 'googlemaps', I am confused that I have already downloaded it and added it in settings.py, importing in IDE also seems fine. But where I did wrong makes it fail to start the server? -
Django REST: 'Request' object has no attribute 'field_name'
I'm trying to create a post request to add a job application to the list of applicants. This is done by POST /task-worker/<task_id> However, I get the error: 'Request' object has no attribute 'task' Models.py class Task_worker(models.Model): worker = models.ForeignKey(Worker) task = models.ForeignKey(Task) class Meta: unique_together = ('worker', 'task') class Task(models.Model): ... class Worker(models.Model): ... views.py class TaskWorker(generics.ListCreateAPIView): serializer_class = TaskWorkerSerializer def get_queryset(self): task_id = self.kwargs.get('task_id', '') queryset = Task_worker.objects.filter(task__user=self.request.user, task_id=task_id).distinct() return queryset def perform_create(self, serializer): worker = Worker.objects.get(user=self.request.user) task = Task.objects.get(pk=self.kwargs.get('task_id', '')) serializer.save(task=task, worker=worker) #ALSO TRIED #serializer.save(task_id=self.kwargs.get('task_id', ''), worker=worker) Even if I don't have task explicitly in perform_create(), I still get the same error, saying request has no task attribute. urls.py url(r'^task-worker/(?P<task_id>[0-9]+)/$', views.TaskWorker.as_view()), -
ImportError: No module named 'app.settings.ci'; 'app.settings' is not a package
I got an error,ImportError: No module named 'app.settings.ci'; 'app.settings' is not a package.I wanna install CircleCI 2.0 into Django application.Traceback says Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/xxx/anaconda/envs/rf/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ImportError: No module named 'analytics_api.settings.ci'; 'analytics_api.settings' is not a package I run command,python manage.py makemigrations --settings app.settings.ci,so the error happens.I think this command is necessary to install CircleCI 2.0,but is it wrong?How can I fix this?What is wrong in my code? -
Django: Form widget not accepting date format provided by bootstrapdatetimepicker
I have the following problem: I have a django form that uses the 'bootstrapdatetimepicker' widget for a datetimefield. However, when I try to post the form it throws a 'format is invalid' error. I am using a local (Dutch) timeformat, but I have included this new format in both the forms.py code (see below) class Meta: model = Quotation fields = [ 'full_name', 'organisation', 'address', 'date', 'type', 'description', 'budget', ] widgets = {'date': DateTimeInput( attrs={'id': 'datetimepicker1'}, format='%d-%m-%Y %H:%M:S')} and in the template as well, <div class="col-md-12 speaker-form" id="offerte"> {% csrf_token %} {% crispy form %} </div> <script> $(function () { $('#datetimepicker1').datetimepicker({ format:'DD-MM-YYYY HH:mm:ss', defaultDate: new Date(), icons: { up: "fa fa-chevron-circle-up", down: "fa fa-chevron-circle-down", next: 'fa fa-chevron-circle-right', previous: 'fa fa-chevron-circle-left', } }); }); </script> Does anyone know what I am doing wrong? Why are my 'format' overrides in both the Python and Javascript code not working as they should? -
Django-orm Queryset for Find object by count a particular field
Lets say i have two model class Testmodel1(): amount = models.IntegerField(null=True) contact = models.ForeignKey(Testmodel2) entry_time = models.DateTimeField() stage = choicesfiled class Testmodel2(): name = models.CharField() mobile_no = models.ForeignKey() I want to find out the object of Testmodel1 for contact > 3 which is created in last 24 hours last = arrow.utcnow().shift(hours=-24).date(). I am applying a query n1=Testmodel1.objects.filter(entry_time__gte=last, stage=1).annotate(t_count=Count('contact')).filter(t_count__gt=3) But it's seems, it' not working. Because I am getting a empty queryset. Any help would be appreciated. -
Django-hvad _clone() got an unexpected keyword argument 'shared_model'
I'm trying to implement django-hvad on a django app but I'm getting this error _clone() got an unexpected keyword argument 'shared_model' when I'm trying to launch python manage.py runserver. Did I made any mistakes to translate my models? Thanks for your help! models.py class Opponent(TranslatableModel): name = models.CharField(max_length=255, unique=True, null=True) companyType = models.ForeignKey(CompanyType, on_delete=models.SET_NULL, blank=True, null=True, related_name='opponents') pricing = models.ManyToManyField(Pricing, blank=True) translations = TranslatedFields( description = models.TextField(null=True, blank=True) ) def __str__(self): return "{}" .format(self.name) def save(self, *args, **kwargs): super(Opponent, self).save(*args, **kwargs) # Call the "real" save() method. serializers.py class OpponentSerializer(TranslatableModelSerializer): class Meta: model = Opponent fields = '__all__' views.py class OpponentViewSet(viewsets.ModelViewSet): queryset = Opponent.objects.language().all() serializer_class = OpponentSerializer def get_queryset(self): user_language = self.request.GET.get('language') return Opponent.objects.language(user_language).all() -
Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualst udio.com/visual-cpp-build-tools
I have tried all methods mentioned on the internet but there is no use. I am trying to install misaka by writing pip install misaka it keeps complaining by showing the same message. I have downloaded and installed MS build tool 2015 and 2017, Restarted my laptop. Whatever I did, couldn't figure out why it complains. Python version 3.6.4 Windows 10 -
Remove blank lines from Django template output of render_to_string
I am trying to add contents to models.py dynamically using templates. For this i have the following line in views.py model_content = render_to_string('myapp/models.txt',{'table':table_name, 'fields':fields}) models.txt in templates class {{ table }}(models.Model): {% for field in fields %} {{ field.field_name }} = models.{{ field.field_type.name }} {% endfor %} But when i wrote model_content string to a file say models.py i am getting the below class Mytable(models.Model): order = models.CharField cust_name = models.CharField I am getting an extra line after every line. How to avoid this. I will provide additional information if required. -
Django Test Not Getting Model Object
I am just scratching the surface of testing in Django. Here is my testing code, inside tests.py: class AdvertisingTests( TestCase ): def test_get_ad( self ): ''' Test if the get ad feature is working, should always load an ad ''' url = reverse('advertising:get_ad') response = self.client.get( url ) self.assertEqual(response.status_code, 200) This test is just a basic test of a view that should return an Ad. Here is the view code: from .models import Ad, Impression def get_ad(request): FirstAd = Ad.objects.first() # +1 impression Impression.objects.create(ad = FirstAd) import json data = { 'url': FirstAd.url, 'image_url': FirstAd.image.url, 'title': FirstAd.title, 'desc': FirstAd.desc } json_data = json.dumps( data ) return HttpResponse(json_data, content_type='application/json') I am working in a heroku local environment, so I run the tests like this: heroku local:run python manage.py test advertising And this test fails, coming from the Impression.objects.create(ad = FirstAd) line: ValueError: Cannot assign None: "Impression.ad" does not allow null values. What that tells me is that the FirstAd object is null. OK so I wind up the local shell like this: heroku local:run python manage.py shell to double check. Replicating that code there are no errors: In [2]: from advertising.models import Ad, Impression In [3]: print Ad.objects.first() Flamingo T-Shirt Corporation … -
Django dinamically add forms to inline formsets
In my application i made an inline formset where the user can select multiple languages. In order to make this dynamic i tried to make a javascript function where he can press an 'add' button and another form would appear. Sadly i couldn't make it done, I've tried other examples from stack, but i couldn't make it work for my formset. views.py @login_required() def translator_data(request): data = dict() if request.method == "POST": t = get_object_or_404(Translator, user=request.user) form = TranslatorForm(request.POST, request.FILES, instance=t) formset = TranslatorFormSet(request.POST) if form.is_valid(): translator = form.save(commit=False) formset = TranslatorFormSet(request.POST, instance=translator) if formset.is_valid(): translator.user = request.user translator.save() for form in formset.forms: form.save() return redirect(reverse_lazy('translator:translator_test')) else: t = get_object_or_404(Translator, user=request.user) form = TranslatorForm(instance=t) formset = TranslatorFormSet() data['formset'] = formset data['form'] = form data['checkbox_fields'] = ['available_monday', 'available_tuesday', 'available_wednesday', 'available_thursday', 'available_friday', 'available_saturday', 'available_sunday'] data['formset_fields'] = ['language', 'type', 'experience'] return render(request, 'translator/data_middleware.html', data) forms.py class TranslatorDataForm(ModelForm): class Meta: model = TranslatorData fields = ['language', 'type', 'experience'] exclude = ['translator', 'id', 'delete'] labels = { 'language': _('Limbă'), 'type': _('Tip'), 'experience': _('Experiență'), } def __init__(self, *args, **kwargs): super(TranslatorDataForm, self).__init__(*args, **kwargs) self.fields['language'].widget.attrs.update({'class': 'form-control m-bootstrap-select m_selectpicker', 'required': True}) self.fields['type'].widget.attrs.update({'class': 'form-control m-input', 'id': 'exampleSelect2', 'required': True}) self.fields['experience'].widget.attrs.update({'class': 'form-control m-bootstrap-select m_selectpicker', 'required': True}) TranslatorFormSet = inlineformset_factory(Translator, TranslatorData, form=TranslatorDataForm, … -
graphene relation using RESTfull API as data source
I'm using django graphene for building a graphql server, it consume a RESTfull API to get data, following this schema: class DeviceType(graphene.ObjectType): id = graphene.ID() reference = graphene.String() serial = graphene.Float() class InstallationType(graphene.ObjectType): id = graphene.ID() company = graphene.Int() device = graphene.ID() class AllDataType(graphene.ObjectType): device = graphene.Field(DeviceType) installation = graphene.Field(InstallationType) class Query(graphene.ObjectType): installation = graphene.Field( InstallationType, device_id=graphene.Int(required=True) ) all = graphene.Field( AllDataType, serial=graphene.Float(required=True) ) def resolve_installation(self, info, device_id): response = api_call('installations/?device=%s' % device_id)['results'][0] return json2obj(json.dumps(response)) def resolve_all(self, info, serial): response = api_call('devices/?serial=%s' % serial)['results'][0] return json2obj(json.dumps(response)) The query I need to do is like this: query { all(serial:201002000856){ device{ id serial reference } installation{ company device } } } So, my problem is how to make a relation with this two types, as described in AllDataType, the resolve_installation needs a device id and resolve_all needs a serial number of device. To resolve the installation I need the device id returned by resolve_all resolver. How can I achieve this? -
Tracking a Google Analytics Conversion Event
I have a website running on the Django framework and I need to incorporate Google Conversion Tracking onto the page that tracks clicks when the user clicks on an link. My current setup for links uses Django template language like so: <a href="{% url 'redirect_click' argument1 argument2 .... %}" target="_blank"> The problem is the Django URL used by the link. When a user clicks it, a view is called in the Django framework that logs details about the click and then redirects them to the links page. I've tried fiddling with the sample Google Tracking code here but I do not know how to modify it to wait until the redirect finishes before checking for the google_trackConversion variable on the page its redirected to: <!-- Google Code for Add to Cart Conversion Page In your html page, add the snippet and call goog_report_conversion when someone clicks on the chosen link or button. --> <script type="text/javascript"> /* <![CDATA[ */ goog_snippet_vars = function() { var w = window; w.google_conversion_id = 12345678; w.google_conversion_label = "abcDeFGHIJklmN0PQ"; w.google_conversion_value = 13.00; w.google_conversion_currency = "USD"; w.google_remarketing_only = false; } // DO NOT CHANGE THE CODE BELOW. goog_report_conversion = function(url) { goog_snippet_vars(); window.google_conversion_format = "3"; var opt = … -
Heroku, Django. Automatically delete record in db after sertain time
I want that old record in db are deleted automatically. Iam trying to set something like scheduler or apscheduler on my heroku server but it not seems to be worked. What i did was create management command for heroku scheduler (import django; django.setup() is needed to fix settings error): ` import django django.setup() from django.core.management.base import BaseCommand, CommandError from shortener.models import ShortURL from datetime import datetime, timedelta from django.utils import timezone from url_shortener.settings import SHORT_URL_LIFE_TIME class Command(BaseCommand): help = 'Delete short-url record in db older than {0} day(s)'.format(SHORT_URL_LIFE_TIME) def handle(self, *args, **options): # ShortURL.objects.filter(creation_date__lte=timezone.now() - timedelta(days=SHORT_URL_LIFE_TIME)).delete() ShortURL.objects.filter(creation_date__lte=timezone.now() - timedelta(minutes=1)).delete()` This command successuffly deletes record in local server but in heroku it doesnt. I also tried set clock-processes with setting clock.py as: `import django django.setup() from apscheduler.schedulers.blocking import BlockingScheduler from shortener.models import ShortURL from datetime import datetime, timedelta from django.utils import timezone # from url_shortener.settings import SHORT_URL_LIFE_TIME sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def timed_job(): ShortURL.objects.filter(creation_date__lte=timezone.now()-timedelta(minutes=1)).delete() sched.start()` But it's not working either. -
to edit queryset in python django
total_trans_today = Addfuel.objects\ .filter(date_created__year=datetime.today().date().year, date_created__month=datetime.today().date().month, date_created__day=datetime.today().date().day) In above queryset, it gives data for today or day wise, how do i edit it to get data for month or month wise. Please help -
CRSF incorrect to Django from AJAX
I Know this is a common problem but after tring every web solution, I still got "CSRF token missing or incorrect." error. The ajax call use correctly the cookie crsf token DJango has created using on the the common csrf solution: beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", window.csrftoken); } } This is the POST header: Accept:*/* Accept-Encoding:gzip, deflate, br Accept-Language:it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6 Connection:keep-alive Content-Length:31 Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Cookie:csrftoken=PV730Sh7PhMM4WKlnSmzMv726Y5wspf4LKHz8XR9TfHVeY167a8aAzbU8Oci6VMf Host:127.0.0.1:8000 Origin:http://localhost:3000 Referer:http://localhost:3000/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 X-CSRFToken:uD3NP6tHllrSSnx4qi23EVgIZy0dkVE5qhZCYN5A9ZETI8SITPb0NGtamIezFTPv In DJANGO, im using the middleware: 'django.middleware.csrf.CsrfViewMiddleware', Django View doens't have any @csrf option because is an authenticate POST. As you see from headers, my Ajax Call start from another "port" (a React Application). For development, i have disabled in Chrome the cross-origin check to ensure my call goes normally. This is a piece of Django view: def login(request, *args, **kwargs): username = request.POST['username'] password = request.POST['password'] c = {} try: user = authenticate(request,username=username, password=password) if user is not None: return JsonResponse(user.id, safe=False, status=200) Im worried about the headers. As you can see, the X-CSRFToken (created by Django after a first GET call with the option @ensure_csrf_cookie) is different from Cookie:csrftoken= which value I don't know … -
Django 2 static files
I know this has been ask about a million times, but just don't get djangos static file handling. In prod I will deploy in s3 wich already works nicely. But in dev (local running) not so much. Problem 1: If I set the config to this: if ENVIRONMENT == "dev": BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] I can not run collectstatic as of the following error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. OK, makes sense, so I configure it to the following Problem 2: if ENVIRONMENT == "dev": BASE_DIR = os.path.dirname(os.path.dirname(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Now I can run collectstatic. But if run the server it will not find the static files: "GET /static/css/bootstrap.min.css HTTP/1.1" 404 What I dont't get: The Problem 1 can server the static files, which Problem 2 collects... How do I configure Django 2 to simply collect and server static files within one simple 'static' folder within the root of my project?