Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django syntax error after activated venv and checking python and django version
I've already activated my venv FYP2, and also check my python and django version, they are all compatible, I have no idea why this error keeps coming up. Python = 2.7.16 Django = 1.11 (base) C:\Users\Gary>cd FYP2 (base) C:\Users\Gary\FYP2>activate FYP2 (FYP2) C:\Users\Gary\FYP2>python manage.py runserver File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax (FYP2) C:\Users\Gary\FYP2>python --version Python 2.7.16 :: Anaconda, Inc. (FYP2) C:\Users\Gary\FYP2>python -m django --version 1.11 (FYP2) C:\Users\Gary\FYP2> -
Form not displaying form instance ChoiceField and DateField
Hello I'm trying to edit my form instance but the ChoiceField or DateField dont use the default value I wrote. I tried with and without Widget Tweaks. The IntegerField instance data is showing up though so I don't understand why arent the other ones working. These are the files: models.py class Venta(models.Model): Empresa=models.ForeignKey(Cuenta,default=None,on_delete=models.CASCADE) Facturacion=models.DateField(blank=True , null=True) Cobro=models.DateField(blank=True , null=True) Monto=models.FloatField() meses=( ('ENERO','ENERO'), ('FEBRERO','FEBRERO'), ('MARZO','MARZO'), ('ABRIL','ABRIL'), ('MAYO','MAYO'), ('JUNIO','JUNIO'), ('JULIO','JULIO'), ('AGOSTO','AGOSTO'), ('SEPTIEMBRE','SEPTIEMBRE'), ('OCTUBRE','OCTUBRE'), ('NOVIEMBRE','NOVIEMBRE'), ('DICIEMBRE','DICIEMBRE') ) espacios=( ('OFICINA A','OFICINA A'), ('OFICINA B','OFICINA B'), ('OFICINA C','OFICINA C'), ('OFICINA D','OFICINA D'), ('ESTUDIO 1','ESTUDIO 1'), ('ESTUDIO 2','ESTUDIO 2'), ('ESTUDIO 3','ESTUDIO 3'), ('AUDITORIO','AUDITORIO'), ('OPEN SPACE','OPEN SPACE') ) medios=( ('EFECTIVO','EFECTIVO'), ('TRANSFERENCIA','TRANSFERENCIA'), ('CHEQUE','CHEQUE'), ('MERCADOPAGO','MERCADOPAGO'), ('TARJ DE CREDITO','TARJ DE CREDITO'), ('TARJ DE DEBITO','TARJ DE DEBITO'), ) Iva=models.FloatField(default=0 ,blank=True) Mes=models.CharField(max_length=30,choices=meses , null=False ) Total=models.FloatField(default=0) Espacio=models.CharField(max_length=30,choices=espacios,default="OFICINA A", null=False ) Medio=models.CharField(max_length=30,choices=medios,default="TRANSFERENCIA", null=False ) def __str__(self): return self.Empresa.Cliente def get_absolute_url(self): return f"{self.id}/" forms.py from django import forms from .models import Cuenta , Venta from .my_choices import respuestas class CuentaForm(forms.ModelForm): class Meta: model=Cuenta fields=['Cliente','Descripcion','Tipo','Estado'] class VentaForm(forms.ModelForm): class Meta: model=Venta fields=['Empresa','Mes','Medio','Monto','Iva','Facturacion','Cobro'] views.py @login_required(login_url='/login/') def venta_edit_view(request,my_idd,my_id): venta=get_object_or_404(Venta,id=my_idd) my_form=VentaForm(request.POST,instance=venta) if my_form.is_valid(): my_form.save() return redirect("../") context={"form" : my_form , "obj":venta} return render(request,"keyaccounts/venta_edit.html",context) venta_edit.html <form action='.' method='POST'>{%csrf_token%} <div id="empresa"> <h3>Empresa</h3> {{form.Empresa}} </div> <div id="mes"> <h3>Mes</h3> {{form.Mes}} </div> <div id="medio"> … -
Why can't i create an inherited model?
Im a newbie in Django and have model inheritance problem. My models: class Interaction(models.Model): nom = models.CharField(max_length=128, unique=True) lieu = models.ForeignKey(Lieu, on_delete=models.CASCADE, blank=True, null=True) description = models.TextField(default='...') acces_libre = models.BooleanField(default=True) class Heros(Interaction): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) ############# Attributs ########## corps = models.IntegerField(default=0) coeur = models.IntegerField(default=0) esprit = models.IntegerField(default=0) def __str__(self): return self.nom class Personnage(Interaction): # Attributs corps = models.IntegerField(default=50) coeur = models.IntegerField(default=50) esprit = models.IntegerField(default=50) def __str__(self): return self.nom My migrations: migrations.CreateModel( name='Interaction', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nom', models.CharField(max_length=128, unique=True)), ('description', models.TextField(default='...')), ('acces_libre', models.BooleanField(default=True)), ], ), migrations.CreateModel( name='Heros', fields=[ ('interaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='aventures.Interaction')), ('corps', models.IntegerField(default=0)), ('coeur', models.IntegerField(default=0)), ('esprit', models.IntegerField(default=0)), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], bases=('aventures.interaction',), ), migrations.CreateModel( name='Personnage', fields=[ ('interaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='aventures.Interaction')), ('corps', models.IntegerField(default=50)), ('coeur', models.IntegerField(default=50)), ('esprit', models.IntegerField(default=50)), ], bases=('aventures.interaction',), ), migrations.AddField( model_name='interaction', name='lieu', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aventures.Lieu'), ), If i try to creeate a heros in django admin i have: no such column: aventures_heros.interaction_ptr_id If i try to create a Personnage: no such table: aventures_personnage I tried to delete my migrations but it didn't work. I did delete all my old instance from my old models, it didn't work too... I don't anderstand why it doesn't works can … -
Pass a curly braced data in Ajax in Django
In my Django project the user can add some saved products into a database. I have a view where the saved products are displayed. The user can then delete them if he wants to. To do so I am trying to implement an AJAX call. My HTML: <div class="col-md-1 my-auto mx-auto"> <form id="form_id" method='post'>{% csrf_token %} <button type="submit"><i class='fas fa-trash'></i></button> </form> </div> My AJAX: $("#form_id").on('submit', function(event) { event.preventDefault(); var product_id ='{{ saved.original_product.id }}'; console.log(product_id); var url = '/register/delete/'; $.ajax({ url: url, type: "POST", data:{ 'product_id': product_id, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { if (data['success']) console.log(product_id) } }); }); And my view.py: def delete(request): data = {'success': False} if request.method=='POST': product_id = request.POST.get('product_id') print (product_id) data['success'] = True return JsonResponse(data) My view is not doing much for now but I am a learning Ajax for now and I do it one step at a time. What I want now is my print() and console.log() to display the value of {{ saved.original_product.id }} because for now then don't display it's value but {{ saved.original_product.id }} literal. I think the problem comes from my HTML. How can I pass the curly braced value into AJAX? -
django signals do not send mail
I have a blog and I want to send e-mail my subscribes when I published new post. I used django signals. My problem is that signal is not working. I can send mail when I try django shell. My files following : signals.py -
Django request.FILES gets name, filename but not file (blob)
I'm trying to send an audiofile via a POST request to the server (aws, ec2) and I'm using Django, but my request.FILES doesn't receive the blob file, but it DOES receive the key and the filename. How can I get the file? Main.js: var fd = new FormData(); fd.append('text', speech); fd.append('audio', blob, 'test.wav'); $.ajax({ type: 'POST', enctype: 'multipart/form-data', url: url, data: fd, processData: false, contentType: false, success: function(response) { console.log(response); } }) speech is String, blob in console is Blob {size: 221228, type: "audio/wav"}, so it does exist. Views.py: def get_blob(request): thislist = [] for key in request.POST: thislist.append(request.POST.get(key)) for key in request.FILES: thislist.append(request.FILES.get(key).name) json_stuff = json.dumps({"check": thislist}) return HttpResponse(json_stuff, content_type="application/json") I've tried with and without enctype, doesn't make a difference. I've tried setting contentType to multipart/form-data, doesn't make a difference. The formdata seems to be sent correctly, because I can get the speech correctly (request.POST). And I can get the key from request.FILES ('audio'), and get the filename ('test.wav'). If I try request.FILES['audio'].read(), it says MultiValueDictError. If I try request.FILES.get('audio').read() it says AttributeError, 'NoneType' object has no attribute 'read'. Does anyone know what's going on and/or can help me with the problem? -
Use buttons (not radiobuttons) for Choicefield in Django?
I have a Django form: class Form0(forms.Form): # Do you agree to the terms? CHOICES = [ (1,'Yes'), (0, 'No')] response = forms.ChoiceField(widget=forms.RadioSelect,choices=CHOICES) It is being rendered in my HTML template. I have made a script to enable submitting the form when clicking on a radio button which works perfectly: <form method="POST"> {{ form.as_table }} {% csrf_token %} <script> $("input[type=radio]").on("change", function () { $(this).closest("form").submit(); }); </script> </form> It looks like this: The problem Is it possible to display the 'Yes' and 'No' radioselect as normal buttons? E.g. using bootstrap buttons like: <button class="btn btn-primary" type="submit">Yes</button> <button class="btn btn-primary" type="submit">No</button> -
How do you add form-#-DELETE to form in Django using Javascript?
I'm trying to delete a form from a formset using javascript. In the Django docs it states: ... if you are using JavaScript to allow deletion of existing objects, then you need to ensure the ones being removed are properly marked for deletion by including form-#-DELETE in the POST data. How do I interact with the POST data using javascript? They even provide an example of what they're looking for: data = { 'form-TOTAL_FORMS': '3', 'form-INITIAL_FORMS': '2', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'Article #1', 'form-0-pub_date': '2008-05-10', 'form-0-DELETE': 'on', 'form-1-title': 'Article #2', 'form-1-pub_date': '2008-05-11', 'form-1-DELETE': '', 'form-2-title': '', 'form-2-pub_date': '', 'form-2-DELETE': '', } So I want to somehow add something like 'form-0-DELETE': 'on', to the POST data. But this seems to be Python code. I want to manipulate it in the client with js. -
Extending IntegrityError class in Django
I'm trying to handle this error django.db.utils.IntegrityError: duplicate key value.... The problem is I don't want to catch all the integrity errors, just the one that has the message "duplicate key value" in it. For example, this is what I'm doing: try: activity.save() except IntegrityError as e: # if the error is not a key duplication one then throw again if 'duplicate key value' not in e.args[0]: raise e My question is if there is a way to extend the IntegrityError class so that the child class can check the error message of the IntegrityError class? -
Unable to successfully use axios with React Native to make a request (IOS)
I'm unable to make a successful request with Axios. I have tested with Postman to make sure the server is correct and it works without a problem there. The error I'm getting is Network Error - node_modules/axios/lib/core/createError.js:15:17 in createError - node_modules/axios/lib/adapters/xhr.js:80:22 in handleError - node_modules/event-target-shim/dist/event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:574:29 in setReadyState - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:388:25 in __didCompleteResponse - node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0 - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0 * [native code]:null in callFunctionReturnFlushedQueue The way I'm making my call to the backend is const onSubmit = (e) => { axios.get(`https://127.0.0.1:8080/tasks/`).then((res) => {}).catch((e) => console.log(e)); }; Am I doing something wrong in regards to axios? I don't even hit the endpoint since my print("hit")never gets logged through the phone (works with postman though) Thank you for all the help -
Is there a way in Django CBV post function to add information to context
I've got the following code class MusicFileUploadView(TemplateView): template_name = "music_file_upload.html" def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): if 'csv-file' in request.FILES.keys(): csv_file = request.FILES['csv-file'] upload = FileUpload(csv_file=csv_file) if request.user.is_authenticated: upload.user_uploaded = request.user response = upload.save() if response['error']: #add error to context pass else: pass else: pass return super().get(request, *args, **kwargs) where in the post section I save an upload file and parse it, incase of an error I want to include the message in the context so I can display it on the same page. Is there a way to include that in the post function? -
Change query string to allow for multiple values
I have an issue with my query string, the problem is when multiple values are selected my Django search breaks. I get this in the URL ?Query=value1&Query=Value2. In this scenario, it's only the last value that is searched. What I want to happen is that both values are searched (with the equivalent of an AND operator in-between). This is the desired result ?Query=value1+Value2. I've added my search form that uses Select2 and my Django search view below. If you need anything else let me now. Any help would be much appreciated. Search form on the front end <form id="makeitso" role="search" action="" method="get"> <select class="js-example-placeholder-multiple" name="query" multiple="multiple"> <option value="Value 1">Value 1</option> <option value="Value 2">Value 2</option> <option value="Value 3">Value 3</option> </select> <script> $(".js-example-placeholder-multiple").select2({ placeholder: "Search here", }); </script> <div class="form-inline justify-content-center"> <button type="submit" class="btn btn-xlarge">Search</button> </div> </form> views.py def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = TestPage.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = TestPage.objects.none() # Pagination paginator = Paginator(search_results, 3) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, 'search/search.html', { 'search_query': search_query, 'search_results': search_results, }) -
RawSQL to djago ORM queryset conversion
Here I have a queryset where I am using raw SQL to get data. But this approach is not fulfilling my requirements. I want to convert this query into pure django ORM query queryset = Model.objects.raw("select id,category,count(category) as total_orders,\ count(distinct ra, category) as order_type,\ SUM(CASE WHEN service_status = 'success' THEN 1 ELSE 0 END) as total_success_order,\ SUM(CASE WHEN service_status = 'failed' THEN 1 ELSE 0 END) as total_failed_order\ from table group by ra;") Could you guys please help me here. Thanks -
Django wishlist feature implementing
I want to do dynamic icon in the CourseListView in the template to show different icons to change color if Course object in a wishlist, but I don't know how to do loop to fetch data, for example (if course in wishlist.objects.all) models class Wishlist(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) wished_course = models.ForeignKey(Course,on_delete=models.CASCADE) slug = models.CharField(max_length=30,null=True,blank=True) added_date = models.DateTimeField(auto_now_add=True) views def add_to_wishlist(request,slug): course = get_object_or_404(Course,slug=slug) wished_course,created = Wishlist.objects.get_or_create(wished_course=course,slug=course.slug,user=request.user,) return redirect('courses:courses') class WishListView(ListView): model = Wishlist template_name = 'courses/wishlist.html' paginate_by = 10 context_object_name = 'wishlist' def get_queryset(self): return Wishlist.objects.filter(user=self.request.user) class CourseListView(LoginRequiredMixin,ListView): model = Course paginate_by = 10 template_name = 'courses/my_courses.html' context_object_name = 'mygroups' def get_queryset(self,**kwargs): user = get_object_or_404(CustomUser,username=self.request.user.username) return user.tutor_courses.all() template <div class="card"> <a href="{% url 'courses:course_detail' course.slug %}"> <div class="blurring dimmable image"> {% if course.image %} <img src="{{course.image.url}}" style="height: 200px; width: 100%;"> {% else %} <img src="{% static 'img/image.png' %}" style="height: 200px; width: 100%;"> {% endif %} </div> </a> <div class="content"> <a class="header" href="{% url 'courses:course_detail' course %}">{{course.title}}</a> <a class="header right floated">${{course.price}}</a> </div> <div class="extra content"> <span class="right floated like"> <a href="{{path}}"><i class="{{color}} like icon"></i></a> </span> <div class="ui star rating left floated"></div> </div> <div class="extra content"> <div class="right floated author"> <a href="{% url 'users:tutor_profile_view' course.tutor.username %}"> <img class="ui avatar image" src="{{course.tutor.profile.get_picture}}"> {{course.tutor.username}} … -
How can I enable my html page to check the user with two boolean field value and display their data using the "if" statement?
so I've created an account and I want to display details of that account. So I've used Boolean fields to regulate the data of each account on the html page, I didn't want to use filters because the application has specific functions that I didn't want complicate it with. I've created the Account_checker model that uses BooleanFields to regulate data. But if an account has two BooleanField=True, how can I display two information based on that two BooleanField=True on the HTML page?. models.py class Account_checker(models.Model): is_Type_A=BooleanField(default=False) is_Type_B=BooleanField(default=False) is_Type_C=BooleanField(default=False) html page {% for player in players %} {% if player .is_Type_A %} display type A data {% elif player.is_Type_B %} display type B data {% elif player.is_Type_C %} display type C data {% elif player.is_Type_A and player.is_Type_B %} #This code isn't working display type A data and type B data {% elif player.is_Type_B and player.is_Type_C %} #This code isn't working display type B data and type C data {% elif player.is_Type_B and player.is_Type_C and player.is_Type_C %} #This code isn't working display type B data and type C data {% endif %} {% endfor %} -
want to success message django
i have created the user profile registration in django...please tell me anyone...where i should write success message after creating profile ....in the api... views.py class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating and updating profiles""" serializer_class = serializers.UserProfileSerializers queryset = models.UserProfile.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) filter_backends = (filters.SearchFilter,) search_fields = ('email', 'name',) serializers.py class UserProfileSerializers(serializers.ModelSerializer): """Serializers user profiles object""" class Meta: model = models.UserProfile fields = ('id', 'email', 'name', 'password') extra_kwargs = { 'password': { 'write_only': True, 'style': {'input_type': 'password'} } } def create(self, validated_data): """create and return a new user""" user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], password=validated_data['password'], ) return user -
Django session issue while after redirecting from paytm payment portal
I have a session issue in Django, after redirecting from Paytm portal to a payment success page (local server ), user is getting logout.enter image description here enter image description here -
Django file upload with ajax without JQuery
everything is in the title, so before any further explanations there is my code. {% extends 'informations/userpage.html' %} {% load static %} {% block redaction %} <div class="redaction"> <form method="POST" enctype="multipart/form-data" action="/redaction/" class="article-post"> {% csrf_token %} <div class="article-picture"> {% if article.image %} {{article.image}} {% else %} <img class="generic-image" src="{% static 'informations/images/none-picture.svg' %}" alt="Image article"> {% endif %} <img class="edit" id="article-image" src="{% static 'informations/images/edit.svg' %}"> </div> <div id="id01" class="modal" style="display: none;"> <div class="upload-container"> <input type='file' name="newImage"> <div class="button" id="uploadImage" name="upload" value="envoyer">Envoyer</div> </div> </div> </form> {% csrf_token %} <script id="picturesend"> var csrf_token = document.getElementsByName('csrfmiddlewaretoken').value </script> <script type="text/javascript" id="django-admin-popup-response-constants" src="{% static 'informations/redaction.js' %}"> </script> </div> {% endblock %} var articleImage = document.getElementById('article-image'); var uploadImage = document.getElementById('uploadPic'); uploadImage.addEventListener('click', displayUpload); articleImage.addEventListener('click', displayUpload); function displayUpload() { var uploadfile = document.getElementById('id01'); var uploadPicture = document.getElementById('uploadImage'); uploadPicture.addEventListener('click', uploadFile); uploadfile.style.display='block' } function uploadFile() { var formData = new FormData(); var file = document.getElementsByName('newImage'); var image = document.getElementsByClassName('generic-image')[0]; formData.append('newImage', file); var xhr = new XMLHttpRequest(); xhr.open('POST', '/upload/', true); xhr.onload = function () { if (xhr.status === 200) { console.log(xhr.responseText); image.setAttribute('src',JSON.parse(xhr.responseText)); } else { alert('An error occurred!'); } }; xhr.setRequestHeader('Content-Type', file.type); xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken')); xhr.send(formData); } my file model def userDirectoryPath(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.username, filename) … -
This backend doesn't support absolute paths. Django to delete file in gd_storage
Sorry, I'm a newbie on Django platform, now I was trying to delete file from google drive, and error occur. I really don't know the meaning of This backend doesn't support absolute paths. Here is my code, hope anybody can help. model view error -
I am getting theses errors in Django admin can any one help me this
I am new to Django and i am trying to make custom authentication for my project by while running the server I am Getting these errors please help me to resolve this issue . ERRORS: <class 'users.admin.UserAdmin'>: (admin.E008) The value of 'fieldsets[1][1]['fields']' must be a list or tuple. <class 'users.admin.UserAdmin'>: (admin.E033) The value of 'ordering[1]' refers to 'name', which is not an attribute of 'users.user'. <class 'users.admin.UserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'name', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'users.user'. my admin code is: from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.contrib import admin User=get_user_model() from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .forms import UserAdminCreationForm, UserAdminChangeForm # Register your models here. class UserAdmin(BaseUserAdmin): form = UserAdminChangeForm add_form = UserAdminCreationForm list_display = ('name', 'phone', 'admin') list_filter = ('staff','active','admin') fieldsets = ( (None, {'fields':('phone', 'password')}), ('Personal info',{'fields':('name')}), ('Permissions', {'fields':('admin','staff','active')}), ) add_fieldsets = ( (None, { 'classes': ('wide'), 'fileds': ('phone', 'password1', 'password2',),} ), ) search_fields = ('phone','name') ordering = ('phone','name') filter_horizontal = () def get_inline_instances(self, request, obj=None): if not obj: return list() return super(UserAdmin,self).get_inline_instances(request, obj) admin.site.register(User,UserAdmin) admin.site.unregister(Group) -
Advantages and Disadvantages of using Django over Parse Server
Is it better to write your own backend with Django or use Parse Server, if the scale of your app is very large? and also is it easy to migrate from one to another? -
How can I write a Django custom save method that will get or create a foreign key before saving
I have following Django models for City and State set up like this: class State(models.Model): name = models.CharField(max_length=55) abbreviation = models.CharField(max_length=2) class City(models.Model): name = models.CharField(max_length=55) state = models.ForeignKey( State, on_delete=models.CASCADE, null=True, blank=True ) I'm importing json company data that includes NAME, CITY, and STATE. It looks like this: {'NAME': 'Company Name', 'ADDRESS': '123 Main St.', 'CITY': 'Bethel', 'STATE': 'Connecticut'} I'm trying to set up a custom save method to my Company object that would get or create the necessary City object upon creating or updating the company. Creation of a City object will, in turn, require the getting or creating of a State object. class Company(models.Model): name = models.CharField(max_length=55) address1 = models.CharField(max_length=200, blank=True) address2 = models.CharField(max_length=200, blank=True) city = models.ForeignKey( City, on_delete=models.CASCADE, null=True, blank=True ) zipcode = models.CharField(max_length=20, blank=True) def save(self, *args, **kwargs): self.city, created = City.objects.get_or_create(name=city) super(Company, self).save(*args, **kwargs) Since the state field in City is not required, I'm starting with just trying to create the city. But Django is returning this error: Cannot assign "'Bethel'": "Company.city" must be a "City" instance. -
Django DRF with React: How to obtain CSRF cookie?
I have a React frontend running at frontend.example.com and a Django backend with DRF running at backend.example.com. I am using Django Session Authentication and I want to properly implement CSRF protection. Taking the React login page frontend.example.com/login as an example. It's the first time for a user to visit the page. There is a form with a user and password and on submit a new POST request is created to the Django backend. To the best of my knowledge, the CSRF token cookie should already be included in this request, right? How to obtain that CSRF token from the Django backend? I am thinking of doing a GET request to the Django backend on loading the login-page to obtain that CSRF token cookie. Is that the way to do it or is there any other best practice? -
Why am I managing two versions of a Django static file?
I'm still confused by some Django static file management and have a suspicion I'm doing something wrong/stupid. I have a core css file - /app/static/base.css But for some reason, cannot recall why, I also have - /static/css/base.css Here's everything in my settings file that I think relates to static files: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( BASE_DIR+'/other_app_1/static/', BASE_DIR+'/other_app_2/static/', BASE_DIR+'/app/static/', ) STATICFILES_LOCATION = 'static' # uncomment and run collect static before pushing to live - python manage.py collectstatic # remember to change back for when you continue to develop #STATICFILES_STORAGE = 'custom_storages.StaticStorage' I've pasted that as it might reveal why I originally started doing this, there has to be a reason. Am I correct in thinking I can stop updating /static/css/base.css and simply use the other one? I can't recall why I started, but I'm sorry to say that I still find Django static file management very confusing. -
very unexpected IndentationError: unexpected indent in django urls.py
first this is urls.py for django project here all things are fine from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] but when i add my app url from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('movie/', include('movie.urls')), ] it says File "/storage/emulated/0/netflix/movie/urls.py", line 5 urlpatterns = [ ^ IndentationError: unexpected indent