Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auth0 save 'sub' instead of 'username'
I finished implementing auth0 to my django and react app. But ever since I signup with a new user, the 'sub' is saved as the username instead of the real 'name'. Is there a way to fix this? django admin user page -
Directed graphs: sons that a mother had with a given father
I am using queries of the form "all descendants of node X with an ascendant called Y". It turns out that Django returns different results depending on which of the parents of the target node one specifies as Y. Illustration: Consider the simple model class Person(models.Model): name = models.CharField(max_length=200, unique=True, blank=False) descendants = models.ManyToManyField("self", symmetrical=False, related_name='ascendants') def __str__(self): return self.name Create a graph with 3 nodes: mother = Person(name="Mother") mother.save() son = mother.descendants.create(name="Son") father = son.ascendants.create(name="Father") Thus, "Father" and "Mother" are the ascendants of "Son". This is the puzzling part. I want to retrieve the sons that "Mother" had with "Father". However, the code q1 = mother.descendants.filter(ascendants__name="Father") print("mother descendants with an ascendant called Father = ", q1) produces an empty QuerySet, which seems incorrect. In contrast q2 = mother.descendants.filter(ascendants__name="Mother") print("mother descendants with an ascendant called Mother = ", q2) correctly produces <QuerySet [<Person: Son>]>. Is this a bug of Django? Thanks! -
What can be the best way for automatic deployment of my application on AWS?
I have an app created in Django and React, but there are few problems that I am facing mainly :- As I will have a large database(postgres) exclusily for a single user, I am creating different AWS instance(t2.micro) for every user. (we are a startup so economical to use t2.micro) Whenever there is a new user then I have to go and manually install postgres, setup nginx and other important things and this is just for Django in EC2, I am not even talking about React in S3. Solutions I am looking for :- If there is a way to automatically create an AWS EC2 instance and deploy backend also same thing for AWS S3 and deploy frontend, whenever there is a new user. There are a lot of things that I will be running when the backend starts namely Huey, Installing Postgres and Creating User for it, installing Redis, making migrations and other trivial stuff. Is there a way to automate every single thing? Things to consider :- We are a startup and can not depend on paid services really much. Please do not ask me to use a single server for every user as we are using 3rd … -
How to find out which data is tenants data in postgres uisng django
so i have 10 tenants, i am using Django with django-tenants with postgresql, every tenants have users, which user data is which tenant data -
Django View Error: Local variable referenced before assignment -> Flaw in if-statement?
In my Django view I have the following if-loop: for i in queryset: if i['mnemonic'] == '#0602###95EUR00': cash_ps_totbank_eur = i['value'] cash_ps_totbank_eur_sub1 = i['value'] if i['mnemonic'] == '#0602###90EUR00': cash_ps_totbank_eur += i['value'] # Working cash_ps_totbank_eur_sub2 = i['value'] if i['mnemonic'] == '#0602###95USD00': cash_ps_totbank_usd = i['value'] cash_ps_totbank_usd_sub1 = i['value'] if i['mnemonic'] == '#0602###2095900': cash_ps_totbank_usd += i['value'] # NOT working & throwing error cash_ps_totbank_usd_sub2 = i['value'] When loading the template, Django throws me an error saying local variable 'cash_ps_totbank_usd' referenced before assignment. I do the same thing here as eight lines above, namely adding a value to a varible that was initiated in the if-loop before and hence should have already a value assigned to it. With the variables ending on _sub1 and _sub2 i tried to check, if there is maybe an error with the equality-check between the queryset and the string. But this is not the case. The variables with _sub1 and _sub2 work perfectly fine and get the correct values assigned to. Any idea what I am missing here? -
Django make query dynamically for filter
this code works well from django.db.models import Q filtered = Article.objects.filter(Q(authers__id=2) | Q(issues__id=1) | Q(issues__id=3) ) However now I have list like this below, and want to make filter dynamically. ids = [1,2,3] for id in ids: eachQ = Q(authers__id=isId) #then...... how can I make query ??? -
Djanng filter for many to many by multiple
Auther has the manytomany entity Article I can use filter for manytomany like this a = Author.objects.get(id=1) Article.objects.filter(authors=a) However I want to filter auther a and auther b like Article.objects.filter(authors=a and authors=b) How can I make it?? -
In Django, how to set value in request object in decorator function and access it from request object in decorated function
I have implemented backend api using django. Environment details are as- Environment : platform : Linux (ubuntu) framework : Django 1.11.28 programming language : python 2.7.12 (will planning to migrate 3.8 in future) Database : Mongodb 3.4 Description : I have developed web services using django. These are plain web services not Restful( earlier there wasn't full support for mongodb for Django rest framework) hence most of the things are customised not as per django standard. Issue details : For authentication I am using Azure AD. I have written simple decorator which receives access token from request sent by front web app/mobile then this decorator validates token and return to view.For authentication I am using django-auth-adfs package decorator authorisation.py def is_authorized(function): @wraps(function) def authorize(request, *args, **kwargs): # access token validation logic if validated(token): # get user details from access token first_name, last_name etc user_info = {"first_name":"foo","last_name":"bar"} return function(request, *args, **kwargs) else: return HttpResponse('Unauthorized', status=401) return authorize View.py @is_authorized def home_view(request): # calling function which decodes access token and return user details. # This function contains same code as in decorator except function it returns user_info **first_name, last_name = get_userinfo_from_access_token(request)** return JsonResponse({"data":{"fname":first_name,"lname":last_name}}) As you can see code got messy, and repetitive … -
Django Dynamic Forms with scratch
I have to make a google form or microsoft form like application in django. kindly give some ideas or example to implement it. -
Django Rest Framework Star Rating System
I have the following structure in my Django models. ratings.models.py class Rating(models.Model): class Meta: verbose_name = 'Rating' verbose_name_plural = 'Ratings' unique_together = [ 'user', 'product'] user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user') product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='product') rating = models.PositiveIntegerField( null=False, blank=False) Product has nothing special to show here. Just a simple Django model. I will omit it. In ProductDetailView in serializers i need the count per rating. A product can be rated from 1 to 5. Example: ... "ratings": { "rating1_star": 6, "rating2_star": 5, "rating3_star": 4, "rating4_star": 3, "rating5_star": 3 } I have achieved this with the following code. class ProductDetailSerializer(serializer.ModelSerializer): ratings = serializers.SerializerMethodField('get_ratings_detail') class Meta: model = Product fields = [...,'ratings',] def get_ratings_detail(self, obj): ratings = Rating.objects.filter( product=obj) r_details = ratings.aggregate( rating1=Count( 'product', filter=Q(rating__iexact=1)), rating2=Count( 'product', filter=Q(rating__iexact=2)), rating3=Count( 'product', filter=Q(rating__iexact=3)), rating4=Count( 'product', filter=Q(rating__iexact=4)), rating5=Count( 'product', filter=Q(rating__iexact=5)), ) return r_details My question is if can i achieve the same result using a better method? I quite do not like how get_ratings_detail looks like, and also i am not sure if this is the best way to do it. Thank you. -
When I save the page as a draft, I get a many-to-many relationship error
class Article(models.Model): """ Article """ nid = models.BigAutoField(primary_key=True) article_title = models.CharField(verbose_name=_('Article title'), max_length=150) summary = models.TextField(verbose_name=_('Article summary'), max_length=255) content = models.TextField(verbose_name=_('Article content'), author = models.ForeignKey(verbose_name=_('Article author'), to=settings.AUTH_USER_MODEL, on_delete=models.PROTECT) category = models.ForeignKey( ArticleCategory, verbose_name=_('Article category'), null=False, blank=False, on_delete=models.PROTECT ) tags = models.ManyToManyField( verbose_name=_('Article tags'), to="Tag", through='Article2Tag', through_fields=('article', 'tag'), blank=True, ) class ArticlePage(Page, Article): content_panels = Page.content_panels + [ FieldPanel('article_title'), FieldPanel('summary', classname="full"), FieldPanel('content', classname="full"), FieldPanel('author'), FieldPanel('category'), FieldPanel('tags'), ] base_form_class = NoTitleForm forms.py class NoTitleForm(WagtailAdminPageForm): title = forms.CharField(required=False, label=_('自带标题'), help_text=_('Title is auto-generated.')) slug = forms.SlugField(required=False, label=_('自带路径'), help_text=_('Slug is auto-generated.')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not self.initial['title']: self.initial['title'] = _('auto-generated-title') if not self.initial['slug']: self.initial['slug'] = _('auto-generated-slug') def save(self, commit=True): page = super().save(commit=False) page.title = strip_tags(self.cleaned_data['article_title']) page.slug = slugify(page.title) if commit: page.save() return page When I wrote an article and saved it as a draft, an error occurred:"" needs to have a value for field "nid" before this many-to-many relationship can be used. I guess, when saving as a draft, it may be that many-to-many this table is not saved, but after the first release, you can continue to edit it, and when you save it as a draft again, you will get an error. I don't know how to save this many-to-many … -
My admin panel gives 500 error when DEBUG=False
"Error:-1" is show when my DEBUG=False and "Error:-2" is show when my DEBUG=True. my setting.py file is:- DEBUG = False ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = '***************' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '*************************' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # #for uploaded image MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #end of uploded image STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), # '/static/', ] This is "Error:1" .... [ When DEBUG=False ] [13/Mar/2020 16:45:33] "GET /admin/ HTTP/1.1" 500 4712 [13/Mar/2020 16:45:33] "GET /admin/js/main2.js HTTP/1.1" 404 21440 [13/Mar/2020 16:45:33] "GET /admin/js/main.js HTTP/1.1" 404 21440 … -
Set different foreign key value in django inline formset initially
I am trying to make a result management system using django. And for storing the subjects marks, I am using the django inline formset. The problem is that the user have to select a subject manually from dropdown which is Select Field in django and I think this will not be a good choice to do. So I decided to set the SelectField initially to those foreign field. But the initial value is always set to the last object of the Subject model. def subject_mark_create(request, grade_pk, exam_pk): subjects = Subject.objects.get_by_grade(grade_pk).order_by('name') SubjectMarkFormset = inlineformset_factory(Exam, SubjectMark, extra=subjects.count(), max_num=subjects.count(), fk_name='exam', form=SubjectMarkForm, can_delete=False) exam = get_object_or_404(Exam, pk=exam_pk) if request.method == "GET": formset = SubjectMarkFormset(instance=exam) for form in formset: for subject in subjects: form['subject'].initial = subject My Current inlineformset What I desired my formset should look like -
Object of type 'ManyRelatedManager' is not JSON serializable
i am working on an dummy app,here i want to select multiple user_name from MuUser model and return that to the Sessions Model. while doing this i am getting this error here is my code my MyUser model class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin my Sessionmodel class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.CharField(max_length=30,blank=False) status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) #Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') Players_Participating=models.ManyToManyField(MyUser,blank=True) def __str__(self): return str(self.Host) class SessionViewSet(viewsets.ViewSet): def create(self, request): try: Host= request.data.get('Host') Sport = request.data.get('Sport') Sports_category = request.data.get('sports_category') #Location = request.data.get('Location') Session_category = data.get('session_category') Session_type=data.get('session_type ') Created=data.get('Created') Session_Date=data.get('Session_Date') Location=request.data.get('Location') Start_time=request.data.get('Start_time') End_time=request.data.get('End_time') Duration=request.data.get('Duration') Level=request.data.get('Level') Player=request.data.get('Player') Gender=request.data.get('Gender') Fee=request.data.get('Fee') … -
Firebase authentication using Python Django
I've created a web page for authentication and added the email in Firebase but when I try to login, I'm getting an error saying missing email -
Django in Docker - Entrypoint to initiate Django App Files
at the moment I am trying to build a Django App, that other users should be able to use as Docker-Container. I want them to easily do a run command or starting a prewritten docker-compose file to start the container. Now, I have problems with the persistence of the data. I am using the volume flag in docker-compose for example to bind mount a local folder of the host into the container, where the app data and config files are located on the container. The host folder is empty on the first run, as the user just installed docker and is just starting the docker-compose. As it is a bind mount, the empty folder overrides the folder in Docker as far as I understood and so the Container-Folder, containing the Django-App is now empty and so it is not startable. I searched a bit and as far as I understood, I need to create a entrypoint.sh file that copies the app data folder into the folder of the container after the startup, where the volume is. Now to my questions: Is there a Best Practice of how to copy the files via an entrypoint.sh file? What about a second run, … -
Subscription Form using Django Allauth
I recently created a Django template using allauth for an Abstract User. I followed William Vincent’s best practices in his book and the settings according to the documentation but I’m currently stuck. I’d like to support multiple signup forms to create a user. The 2 signup forms I’d like to support are: Account creation, which uses the typical convention of: #my_project/setings.py AUTH_USER_MODEL = ‘users.CustomUser’ LOGIN_REDIRECT_URL = ‘home’ LOGOUT_REDIRECT_URL = ‘home’ ACCOUNT_SESSION_REMEMBER = True ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_AUTHENTICATION_METHOD = ‘email’ ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = ‘username’ ACCOUNT_USER_MODEL_EMAIL_FIELD = “email” A User Subscription Form (with simply email and no password), which uses what I came up with: #users/forms.py class CustomUserSubscribeForm(forms.ModelForm): class Meta: model = CustomUser fields = (‘email’, ) email = forms.EmailField( label=_(''), widget=forms.TextInput( attrs={ 'placeholder': _('john@email.com') } ) ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.form_method = 'POST' self.helper.form_class = 'form-inline justify-content-center' self.helper.layout = Layout( Div( FieldWithButtons('email', Submit('Submit', 'submit', css_class='btn btn-outline primary')), Submit('submit', u'Submit', css_class='btn btn-success'), css_class='form-inline' ) ) #users/views.py class SubscribePageView(CreateView): form_class = CustomUserSubscribeForm success_url = reverse_lazy(‘subscribe’) template_name = ‘subscribe.html’ #users/urls.py from .views import SubscribePageView urlpatterns = [ path(‘subscribe’, SubscribePageView.as_view(), name=‘subscribe’), ] These views/html pages render and the … -
In Django, how can I get a count of records based on a subquery of a subquery?
A baseball player plays in a game if he makes one or more appearances in that game. So, to get a count of the number of games a player played in, you need to count the games that have an inning that have an appearance by that player. Here are my models: class Player(models.Model): ... class Game(models.Model): ... class Inning(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) class Appearance(models.Model): inning = models.ForeignKey(Inning, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) The SQL query to achieve what I want is: SELECT COUNT(*) FROM games_game WHERE id IN (SELECT game_id FROM innings_inning WHERE id IN (SELECT inning_id FROM appearances_appearance WHERE player_id = 1)) How could I do this in Django without using Raw SQL? Note that this is for a PlayerDetailView, so I just need it for a single Player object. -
Second app static files not being served in Django
I have two apps in my Django projecto: frontend and backend. The static files from the backend app are being served correctly. The folder hierarchy is backend - static - backend. I am now starting with the frontend app. The hierarchy is frontend - static - frontend. Yet, for this app, files are not being served. When trying to go to the file url I get a 'frontend\assets\vendor\nucleo\css\nucleo.css' could not be found. In my urls.py I have: urlpatterns = [ path('', views.index, name="frontend") ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) And in my settings.py I have: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' -
KeyError at /product/create/ django rest framework
I am trying to create a product but one related field does not accept null value it causes error Traceback (most recent call last): File "/home/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File "/home/venv/lib/python3.8/site-packages/rest_framework/views.py", line 494, in dispatch response = handler(request, *args, **kwargs) File "/home/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post return self.create(request, *args, **kwargs) File "/home/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/home/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 24, in perform_create serializer.save() File "/home/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 213, in save self.instance = self.create(validated_data) File "/home/apps/product/serializers.py", line 194, in create videos = validated_data.pop('product_videos') KeyError: 'videos' class ProductCreateSerializer(serializers.ModelSerializer): product_videos = ProductVideoSerializer(many=True, required=False) class Meta: model = models.Product fields = '__all__' def create(self, validated_data): product_videos = validated_data.pop('videos') phone = self.context.get('view').kwargs.get('phone') user = models.User.objects.get(phone=phone, is_superuser__exact=True) instance = models.Product.objects.create(user=user, **validated_data) for video_uri in product_videos.values(): models.ProductVideoOverview.objects.create(product=instance, **video_uri) return instance It is not accepting the null value I do … -
Possible causes for error: Field cannot be both deferred and traversed using select_related at the same time?
I am trying to use graphene-django-optimizer to remove some of the unnecessary queries. It worked quite well until one certain field where I get this error message Field User.company cannot be both deferred and traversed using select_related at the same time. The only difference with this field is that it is models.OneToOne instead of models.ForeignKey. Why Django make this field deferred? Is it possible to disable field being deferred? -
S3 bucket configuration for open edx (Hawthorn)
I am trying to set s3 for scorm for this I have set: “AWS_ACCESS_KEY_ID” : “access-key”, “AWS_S3_CUSTOM_DOMAIN” : “bucket-name.s3.amazonaws.com 3”, “AWS_SECRET_ACCESS_KEY” : “secret-key”, “AWS_STORAGE_BUCKET_NAME” : “bucket-name”, }, Is there anything. which I have forgot? -
Django doesn't return ajax response with dataType : "JSON"
I have Ajax like this var data = {"data":1} $.ajax({ type: "POST", url: "api/export_csv", data:JSON.stringify(data), // dataType: "JSON", // if I comment out here it works. success: function(response) { console.log("success"); } Then in django view.py @api_view(['POST', 'GET']) def export_csv_view(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=somefilename.csv' writer = csv.writer(response) writer.writerow(['First row', 'A', 'B', 'C', '"Testing"', "Here's a quote"]) return response Very strangely If I comment out the dataType: "JSON" it works, but if I put this line it doesn't work with no error(javascript console). -
Django Template search
In one of my project the template is being searched at <project_root>/<app>/templates/ while in another it is being searched in <project_root>/<app>/templates/<app>/ What exactly does this depend on Both project's settings.py have the following exact same configuration in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
How do I ensure that certain model instances are always present in django database?
My django-application requires a few model instances to always be present in the database to function properly. I currently create the model instances that I require in the Appconfig.ready(self) method for the corresponding app. This way the instances are always present on boot of the django-application. This works but not as well as I'd like, I have to be careful when deleting objects so that I do not delete the required objects. I would like the required model instances to be undeletable or preferably, be created whenever they are not present in the database.