Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CreateView not saving item to model
My Django CreateView is not working. There are no bugs, but a new item is not being created when I submit the form. For example, when I go to the url and submit the form, a new item is not being added. Could you please help? You can also check out my GitHub repo for this project. Code for new_pattern.html {% extends 'patterns/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Perler Pattern</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-success" type="submit">Add Pattern</button> </div> </form> </div> {% endblock %} Code for views.py from django.views.generic import (``` ListView, CreateView, ) from django.contrib.auth.mixins import LoginRequiredMixin from .models import Pattern class PatternListView(ListView): model = Pattern template_name = 'patterns/home.html' context_object_name = 'patterns' ordering = ['title'] class PatternCreateView(CreateView): model = Pattern fields = ['title', 'image'] template_name = 'patterns/new_pattern.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Code for settings.py from . import views from django.urls import path urlpatterns = [ path('', views.PatternListView.as_view(), name='beadz-home'), path('new/', views.PatternCreateView.as_view(), name='new-pattern'), ] Code for models.py from django.db import models from django.contrib.auth.models import User class Pattern(models.Model): title = models.CharField(max_length=45) image = models.ImageField() author = models.ForeignKey(User, on_delete=models.CASCADE) def … -
does not appear to have any patterns in it. or circular import
recently i started to studying django but there is a problem into my code and i cant find what exactly could be a decent fix to this problem so i thought i would be good to ask. ... from django.urls import path from . import views ulrpatterns = [ path('' , views.index) ] ... well this is my code for urls.py into the articles directory. ... from django.contrib import admin from django.urls import path , include from home import views as home_views urlpatterns = [ path("" ,home_views.index ), path("about", home_views.about), path("Contact" ,home_views.contact ), path('admin/', admin.site.urls), path('articles/' , include('articles.urls')), ] ... this one is my main urls.py from what im seeing i called articles.urls but when im running my server it keeps givin me this error raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
IBM Cloud db2 django migrations python manage.py migrate
Created my first ibm db2 database on ibm cloud and connected it with django. With following settings: 'default':{ 'ENGINE' : 'ibm_db_django', 'NAME' : 'BLUDB', 'USER' : 'xxxxxxxxxxxxxxxx', 'PASSWORD' : 'xxxxxxxxxxxxxxxx', 'HOST' : 'dashdb-xxxxxxx-sbox-xxxxxxxxxx.services.eu-gb.bluemix.net', 'PORT' : '50000', 'PCONNECT' : True, } Connection works very well because I can run migrations for custom django app which I added. Even for session and content types. Problems arises due while running migrations for auth and admin. I get following error message: Exception('SQLNumResultCols failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0551N The statement failed because the authorization ID does not have the required authorization or privilege to perform the operation. Authorization ID: "XXXXXXXX". Operation: "SELECT". Object: "SYSIBMADM.ADMINTABINFO". SQLSTATE=42501 SQLCODE=-551' I understand that I dont have privileges to perform select operation on SYSIBMADM.ADMINTABINFO. My question is how can I give myself (admin account) privileges so that my python manage.py migrate does'nt throw an error. Or there is something wrong I am doing in django app itself. (INITIAL MIGRATIONS) -
sending email from django app doesnt work from server
I have an app that sends out an email when an object is create, this is the code for sending email: send_mail("New entryis added", "Hi a new entry is added", "myemail@gmail.com", [c.email for c in CustomUser.objects.all()], fail_silently=False) and this is my setting: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True I also made sure that my "Less secure app access" is on in google security setting. So with all thses I am able to send email with no issue in local server. However when I push the code to digital ocean droplet linux server, it throws some errors: SMTPAuthenticationError at /a/b/c/add/ (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu\n5.7.14 VVGrAjSoYzu_W9fGpWsq5B3qMs04qWLzeqnxkFdrMaeVJumRRljQzXEyYpA9xt1MSYaii\n5.7.14 iyVCj2qaXbQzY5Tvc3mux9qViJSKE5yOozpCzao_qU0FhjYGX8IZ1xgd9PUep41I>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 g9sm2079574pgj.89 - gsmtp') Exception Type: SMTPAuthenticationError I apreciate if someone can shed some light on what is the issue, Thanks, -
How to create asynchronous result submission based on table data using django-tables2
I am currently using django-tables2 to display some results to users. The results is coming from a RDF graph, so the results and number of columns may vary. I wrote the following code to deal with variable length of table columns: def createData(queryResults): if not queryResults: return (DummyTable,[]) else: myTableCol={} mylist = [] for i in queryResults: mydic = {} for j in i: className=str(type(j)).split(".")[1] mydic.update({className: j.name}) myTableCol.update({className: tables.Column()}) mylist.append(mydic) myTableCol.update({'Action': tables.TemplateColumn(template_name="secReqViews/radionbuttons.html", verbose_name=("Actions"), orderable=True)}) Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},}) myTableCol.update({'Meta':Meta}) QueryTable2=type('QueryTable', (tables.Table,), myTableCol) return QueryTable2, mylist Not to dwell on the algorithm, but you can see that I dynamically created the table columns using myTableCol={} and dynamically created class QueryTable2. I added a column call "Actions", which is my focus for this post. I would like to use this column to get information from the users asynchronously. So, for the results in the table, the user can select the "Yes" or "No" radio button to say whether the a row of results is correct or not. By selecting the "Yes" or "No" radio button, the information from the row will be sent and then save the row that is correct or not. Can this be done using Django-tables2? … -
Validation in case of multiple objects serializer
My data input is in the form of list of 'n' number of dicts "contact_person":[ { "contactperson_salutation[0]":"sddd", "contactperson_first_name[0]":"santoorr", "contactperson_last_name[0]":"", "contactperson_email[0]":"gfgh", "contactperson_mobile_number[0]":"", "contactperson_work_phone_number[0]":"jio" }, { "contactperson_salutation[1]":"dfsf", "contactperson_first_name[1]":"lux", "contactperson_last_name[1]":"", "contactperson_email[1]":"", "contactperson_mobile_number[1]":"", "contactperson_work_phone_number[1]":"9048" }, .............] My model is like this: class ContactPerson(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) contactperson_salutation = models.CharField(max_length=4, choices=SALUTATIONS) contactperson_first_name = models.CharField(max_length=128) contactperson_last_name = models.CharField(max_length=128, blank=True) contactperson_email = models.EmailField(blank=True, null=True) contactperson_mobile_number = models.CharField(max_length=20, blank=True) contactperson_work_phone_number = models.CharField(max_length=20, blank=True) How to write serializer when the fields names are changing for every dict in the input list.. And if errors occurs the Error Response should be in this format: [ { "contactperson_email[0]":"Invalid Email", "contactperson_mobile_number[0]":"Invalid mobile phone", "contactperson_work_phone_number[0]":"Invalid workphone number" }, { "contactperson_mobile_number[1]":"Invalid mobile phone", "contactperson_work_phone_number[1]":"Invalid workphone number" } ] -
declaring a global timer variable django
Good day, I have a django project up and running which has a users profile feature, users that register complete their profile with their personal information and other people on the site can view their profile. i have a field in my model for each user called profileVisits which counts each time a users profile is visited in the views.py. profileVisits = models.IntegerField(blank=True, null=True, default= 0) I want to use the profileVisits number to display the data in some kind of line graph which creates a average profileVisits graph. What i had in mind to approach this is to use a queue in python which has a max size of 5 integers q = Queue(maxsize = 5) this is because the data in q will be used in the data field for the chart.js. now the problem im facing is the use of a global variable in django. I want to add the data to q once a day with the number of profile visits and remove the oldest element in it, FIFO sequence, does anyone know how to initialize such a global timer variable in django or any better way to accomplish this -
how to do Django extract zip file after uploading
I am trying to upload a zip file and extract it into the static folder, bellow codeshare working file for uploading the zip file, how to extract the zip file to the static folder after uploading class Article(TimeStampModel): article_type = models.CharField( max_length=256, choices=ArticleTypeChoice.choices(), default=ArticleTypeChoice.ARTICLE.name) language = models.CharField(max_length=256, choices=LanguageChoice.choices()) title = models.CharField(max_length=1020) description = models.TextField(null=False, blank=True) article = models.FileField(null=False, blank=True, upload_to='static/') ``` -
DRF Custom Permission is not firing
I wrote a custom permission class for a drf project to protect my view: views.py class Employee(APIView): permission_classes = [BelongsToClient] serializer_class = EmployeeSerializer def get(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) serializer = EmployeeSerializer(employee, many=False) return Response(serializer.data) def delete(self, request, pk, format=None): employee = EmployeeModel.objects.get(pk=pk) employee.Employees_deleted = True employee.save() return Response(status=status.HTTP_200_OK) My permission class: permission.py from rest_framework import permissions class BelongsToClient(permissions.BasePermission): message= "You are only authorized to view objects of your client" """ Object-level permission to only see objects of the authenticated users client """ def has_object_permission(self, request, view, obj): if obj.Mandant == request.user.Mandant: return True else: return False Unfortunatly this permission class isn't blocking my view even when it should. I dont know why. Did I miss something? -
how to compress django output with your own script?
I am new to Django and I know that it comes with many libraries that can compress the html, css and js files but i want to do this with my own script I have a python script which can compress these files and it works perfectly i want to use this script to compress my Django project output. I am using python 3.7.3 and django 3.0.5 -
Django: If I start a table, and then have a {% block %}{% endblock %} and close the table after, does it break the table?
I am making an html email template, and the header and footer for various email templates are on a single page that is included on each email. They are set up in tables, and the header and footer are contained in a single table. Because I am providing the body of the email in a separate file, it has to be broken up with a block. Apple mail renders the tfoot wrong, as if the footer is separate from the rest of the table. Is this because it is broken up by the block tags? How can I make it work, if so? This is the barebones setup for reference. <body> <table> <th> ---- </th> {% block body %} {% endblock %} <tfoot> <tr> <td> ----- </td> </tr> </tfoot> </table> </body> -
Operational Error: table "users_userscore" already exists
For my web app, I have two apps, one is morse_logs, the main app; second, is the users app, which mainly handles the users details and authentication, etc. At the moment in my users app, I have a UserProfile model, which only have one variable which is description, and now I am struggling to add one more variable score to user, so that each user will have one score variable to store their score, and the user's score will be updated after certain actions in morse_logs game1.html and morse_logs/views.py (the main app). I am really not familiar with modelling and create table, columns these sort of stuff... And when I do migrations, it gives me error like Operaional Error: table "users_userscore" already exists... I did try deleting the migrations py files... all my code are on github: https://github.com/phl6/morse_log So, my question is how can I update my model so I can have a score variable/field for each user which this variable can be updated in the morse_logs(main app). users/model.py from django.db import models from django import forms from django.contrib.auth.models import User from django.db.models.signals import post_save # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) description = models.CharField(max_length=100, … -
Session Authentiction not working with django and vuejs
I am getting the csrf token and i am using axios to send a get request to the rest api. when i set the CSRF token and try to get the data, i get a 403 forbidden error. axios.get("my-api-url",{ header:{ 'X-CSRFTOKEN': csrftoken } }) .then(res -> console.log(res)) .catch(error => console.log(error)) -
KeyError 'OPTIONS' when trying to run Django Heroku project locally
I'm currently trying to run my Django Heroku project locally to develop after making local changes. Upon issuing the command heroku local I get the error seen below. I believe that I'm missing some local environment configuration, as everything works as expected on my production deployment. Below the error message is my settings.py file. 12:05:35 PM web.1 | [2020-04-10 12:05:35 -0500] [3553] [ERROR] Exception in worker process 12:05:35 PM web.1 | Traceback (most recent call last): 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 12:05:35 PM web.1 | worker.init_process() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process 12:05:35 PM web.1 | self.load_wsgi() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 12:05:35 PM web.1 | self.wsgi = self.app.wsgi() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 12:05:35 PM web.1 | self.callable = self.load() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 12:05:35 PM web.1 | return self.load_wsgiapp() 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 12:05:35 PM web.1 | return util.import_app(self.app_uri) 12:05:35 PM web.1 | File "/Library/Python/3.7/site-packages/gunicorn/util.py", line 358, in import_app 12:05:35 PM web.1 | mod = importlib.import_module(module) 12:05:35 PM web.1 | File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module 12:05:35 … -
Logical error in Model & View files - Django Rest Framework
I am creating a Blog app backend using Django Rest Framwork. I use Djoser for user management. Authenticated users can do CRUD operation in their blog post and any logged in user can like and comment the posts. I cannot establish relationship between Posts and comments.Please help MODELS.PY from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): # codes here for user creation,removed codes for simplicity of stackoverflow readers class OwnedModel(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True) class Meta: abstract = True class Post(OwnedModel): name = models.CharField(max_length=100,null=True) likes = models.ManyToManyField(User) class Comment(models.Model): body = models.TextField() friend = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments") author = models.ForeignKey(User, on_delete=models.CASCADE) VIEWS.PY from rest_framework import viewsets,permissions from . import models,serializers from .permissions import IsOwner from rest_framework.permissions import IsAuthenticated class PostViewset(viewsets.ModelViewSet): queryset = models.Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = [IsOwner] class CommentViewset(viewsets.ModelViewSet): queryset = models.Comment.objects.all() serializer_class = serializers.CommentSerializers permission_classes = [IsAuthenticatedOrReadOnly] ** SERIALISERS.PY** from rest_framework import serializers from .models import Post,User,Comment from djoser.serializers import UserCreateSerializer,UserSerializer class PostSerializer(serializers.ModelSerializer): owner = serializers.HiddenField( default=serializers.CurrentUserDefault()) class Meta: model = Post fields = ('id', 'name',"owner",'likes') class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields=('id','email','username','phone','first_name','last_name','password',) class CommentSerializers(serializers.ModelSerializer): class Meta: model = Comment fields=('__all__') ** PERMISSIONS.PY ** from rest_framework import permissions class IsOwner(permissions.BasePermission): message … -
django_tables2: Pagination by Alphabet
I am using django_tables2 to display some data - however. I would like the pagination to occur by letters of the alphabet. I.e. page 1 is all entries that start with A, page 2 is all entries that start with B. etc. I though this would be relatively straightforward to do - but I can't find any examples of this anywhere! Is this not possible? Perhaps I have been using the wrong search terms. Currently my inputs are quite simple - although just pointing me to some materials would be just as helpful as telling me how to change the code. tables.py: import django_tables2 as tables from .models import Person, Languages from django_tables2.utils import A # alias for Accessor class LanguagesTable(tables.Table): name = tables.LinkColumn("language_detail", args=[A("glottocode")]) class Meta: model = Languages template_name = "django_tables2/bootstrap.html" fields = ("name", ) urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ #url(r'^$', views.home, name='home'), path('', views.home, name='home'), path('about/', views.about, name='about'), path('languages/', views.LanguagesTable.as_view(), name='languages'), #path('languages/', views.LanguagesTable, name='languages'), path('languages/<str:pk>/', views.language_detail, name='language_detail'), path('phylogeny/', views.phylogeny, name='phylogeny'), #path("people/", views.PersonListView.as_view()), ] models.py class Languages(models.Model): id = models.TextField(db_column='ID', blank=True, null=False, primary_key=True) # Field name made lowercase. name = models.TextField(db_column='Name', blank=True, null=True) # Field name made … -
Video element in HTML5 won't let me change the time?
I'm using Django as a back end for a website I'm making. I want to load the page and the page start on a variable time using the currentTime property. I've done this exact same thing using a static website and it worked, but as soon as I added django it stopped working. At first I though that maybe it was taking longer to load since the video has to be ready to play in order set the currentTime, but when I did that the video stopped being able to played all together. Another thing that is behaving weird is that the video won't let me use the scrubber to change the time if I enable controls (I would guess this is related), but if I open the video in a new tab I can change the time just fine. -
Django3/DRF: Custom Queryset __init__() gets called multiple times. [ Chaining Querysets is applied ]
Greeting there ! i have built a custom queryset and i have noticed that its __init__() method gets called multiple times. let's take into consideration that i am also applyingQueryset Chaining models.py class Todo(...): ... objects = TodoQueryset.as_manager() manager.py from types import MethodType from django.conf import settings from django.db import models from django.utils import timezone from .settings import TODO_PRIORITY, TODO_STATUS, today_start_date class TodoQueryset(models.QuerySet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.priorities = TODO_PRIORITY print('\t weird 0') def starting_from_today(self): return self.filter(start_time__gte=today_start_date) def flag_as_missed(self): """ Flag Todos which end_time is lower than the current datetime as `TODO_MISSED` """ return self.filter(status=settings.TODO_PROGRESS, end_time__lt=timezone.now).update(status=settings.TODO_MISSED) def specific(self, priority=None, status=None): """ Fetch Todos with a specific priority: => {self.}request.user.todos.specific(priority='HIGH') Or call the specific method set for each priority: => {self.}request.user.todos.high() // NOT IMPLEMENTED YET """ assert priority is not None or status is not None, '.specific() must be called with either `status=...` or `priority=...`, got None instead.' return self.filter(priority=priority.upper()) serializers.py class TodoListSerializer(serializers.Serializer): todo_id = serializers.IntegerField(read_only=True) author_id = serializers.IntegerField(read_only=True) content = serializers.CharField(read_only=True) start_time = serializers.DateTimeField(read_only=True) end_time = serializers.DateTimeField(read_only=True) timestamp = serializers.DateTimeField(read_only=True) priority = serializers.CharField(read_only=True) status = serializers.CharField(read_only=True) path = serializers.SerializerMethodField() def get_path(self, instance): reverse_view = reverse(viewname="todo-detail", args=[instance.pk]) request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(reverse_view) return … -
How to save fomrset data
I am trying to display some data from my contact table and update it in the same time, but the data that I should passe to the formset is always empty so the formset is unbound that's mean invalid formset,the form data are displayed but they can't be edited, so any solution ?? views.py def see(request,slug): data = dict() ProductFormSet = modelformset_factory(Contact, fields=('Nom','post','Tel','email','contact_type','client'), extra=0) client = get_object_or_404(Client_Data, slug=slug) attig = request.POST or None formset = ProductFormSet(data=attig, queryset=Contact.objects.filter(client=client)) print(formset.is_bound) if request.method == 'POST' and formset.is_valid(): formset.save() else: for form in formset: form.fields['client'].queryset = Contact.objects.filter(client=client.id) context = {'form': formset} template_name = 'Client_Section/partial_client_contact.html' data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) forms.py class Contact_Form(forms.ModelForm): class Meta: model = Contact fields = ('Nom','post','Tel','email','contact_type','client') def __init__(self,*args, **kwargs): super(Contact_Form, self).__init__(*args, **kwargs) self.fields['client'].queryset = Client_Data.objects.all() parital_client_contact.html <form method="post" class="js-book-create-form"> {% csrf_token %} <div class="modal-body" > {% include 'Client_Section/partial_client_contact_form.html' %} </div> <br><br> <div style="pos"> <button style="float : right" type="submit" class="btn btn-primary ">Update Contacts</button> <button style="float : right" type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> parital_client_contact_form.html : {% block content %} {{form.as_p}} {% endblock %} -
python manage.py shell nothing happening
I'n new to django and I'm practicing through Django's Documentation on setting up my first project. All worked well until it asked to invoke the Python shell with the command python manage.py shell As a result, nothing really happens apart from showing the following text: Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) Could someone please help? I tried finding an answer in very different sources but no one has really answered it. Thank you in advance. -
Saving a tweaked form request data in Django
My form accepts URL as input and before the URL can work it should have 'http' or 'https', example: http://apexrice.com. So my issue is that some times users enter the url without https. so am trying to tweak the data and add http or https here's a sample code: def get_link(request): form = shortenerModelForm(request.POST) if form.is_valid(): check_http = form.cleaned_data['link'] print(check_http) if request.is_secure() and not check_http.startswith('https'): link = f'https://{check_http}' u = form.save(link) elif not request.is_secure() and not check_http.startswith('http'): link = f'http://{check_http}' u = form.save(link) else: u = form.save() return render(request, 'index.html', {'form': form, 'users': users}) return render(request, 'index.html', { 'form': form, }) So doing form.save() does not save the changes to databese, but it saves the original data. Please how do I save the changes to the database. -
Django many to one reverse query on the same field
I have a one to many relationship between two tables ... Item - id, title ItemAttribute - id, item_id, attribute_code(string, indexed) where attribute_code can have values for colors, sizes, qualities, dimensions, etc, - like codes for 'Blue', 'Black', 'White', 'S', 'L', 'XL', '250g', '400g', etc Question: How do I query for all Items that are either ('Blue' OR 'White') AND 'XL' I prefer using Django's ORM, but if someone could even help out with raw SQL it would do just fine. Thanks. -
Google Storage creating signed url for multiple objects at once
I have been succesfully using signed urls for my image and video content in google storage. My Django Apis return 100 Google Storage objects and creating 100 signed urls takes literally a long time. Is there any other way to generate signed urls faster or multiple of them at once? -
AttributeError: module 'django.conf.global_settings' has no attribute 'X'
I am writing some tests in a Django project that use settings. When I run what I think is a correct test, I get the error AttributeError: module 'django.conf.global_settings' has no attribute 'X' As a contrived example, I add a constant to my settings file: FOO = 'foo' Then I write a test for it: from django import test from django.conf import settings class FooTest(test.TestCase): def test_foo(self): self.assertEqual('foo', settings.FOO) The last line gives the error AttributeError: module 'django.conf.global_settings' has no attribute 'FOO' I assume I have something configured incorrectly in my project. For what it's worth, I am developing with IntelliJ IDEA and in Project Settings, I have the Django facet set to my settings file at settings/development.py in my project. When I add a breakpoint or print() call to my this file, I see that it is executed. So why do I get this error? -
Get access token from cookies via RestSharp
We have a Django application we need to integrate with, and the developers of the system has no exposed API calls, at this point for us to hit. They have noted to use that we can crab the access_token via a POST scrap, as we don't want to expose their login screen to our API users, but we're stuck trying to get the token cookie after the redirect. Basically, we're using RestSharp to do a simple POST of form data to the page indicated by the developers in the 's action attribute, which just results in a response back to the same page, via RestSharp, but the access token is set when the site redirects to the landing page after successful authentication. Is there a way in either RestSharp, or the standard WebClient to perform the POST but wait for the site to redirect, so the cookies can be set accordingly? Their upgrade path for a viable API set is only December, unfortunately, the data we're exposing is for government purposes, and this project cannot wait that long. Here's the URL path we're hitting: POST: url=https://www.bigdata.analytics/login Once you login here, it sets a result and then redirects the users back …