Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to filter tree nodes
I have a tree, which looks like this: RootCategory Category1 Category2 Category3 RootCategory2 Category4 Category5 Category6 Each category has active field and if category is inactive exclude from tree with its childs for example if Category2 is inactive exclude - Category2, Category3 from the tree, should look like this: RootCategory Category1 RootCategory2 Category4 Category5 Category6 Should I somehow add to filter anything or do I need to write sql script for this: categories = Category.objects.filter(is_active=True) Model: class Category(MPTTModel): name = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children', db_index=True) -
Django Autocomplete light : How to enable typing?
I used Autocomplete light in my form for one of the fields , but it just shows the list and typing is disabled , when i add this : (create_field='name') in the url.py ,according to the tutorial , to enable the create new text to add the value to list, it POST the text and save it to the database but i dont want to save it because i will save all the field of my form after filling. so how can i just enable typing in autocomplete field and not save automatically ? -
Django class based views: Posting form data returns 302 Found status code
I'm using django's generic class based view CreateView to upload images to a book. Here's the code: # models.py class Upload(models.Model): image = models.ImageField(upload_to=get_upload_path, help_text='Image to process') uploader = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='uploader') language = models.ForeignKey(Language, models.CASCADE) book = models.ForeignKey(Book, models.CASCADE) def __str__(self): return str(os.path.split(self.image.name)[-1].split('_', 1)[-1]) @models.permalink def get_absolute_url(self): return ('book:upload_new', (self.book.id,)) # upload_new is linked to the view below def save(self, *args, **kwargs): super(Upload, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.image.delete(False) super(Upload, self).delete(*args, **kwargs) # views.py @method_decorator(login_required, name='dispatch') class PictureCreateView(CreateView): model = Upload fields = ("image",) book_id = None def dispatch(self, *args, **kwargs): # book_id is passed as a URL parameter self.book_id = self.kwargs['book_id'] return super().dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(PictureCreateView, self).get_context_data(**kwargs) context['book_id'] = self.book_id return context def form_valid(self, form, **kwargs): book = Book.objects.get(id=self.book_id) form.instance.book = book form.instance.language = book.language form.instance.uploader = self.request.user self.object = form.save() # Running the command below prints # <TemplateResponse status_code=200, "text/html; charset=utf-8"> # implying the upload was successful # # print(self.render_to_response(context=self.get_context_data())) return super(PictureCreateView, self).form_valid(form) def form_invalid(self, form): print(form.errors) data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') When I'm trying to upload an image, I get a 302 Found error for this request (as seen in the my browser's dev tools) implying the page has … -
Trying to configure formset in Django, queryset error
So I have the below models: Teacher, TeacherData, Lecture and Course. Due to some of my app behaviour, I am using two teacher models for different things, which are related by teacher_ID. Also each teacher from TeacherData has its own courses and for each course, specific lectures. I was trying to build a formset which would allow the user to display a form where courses and lectures appear as choices and he will be able to submit a file for that lecture. Problem is, in the query set I get the following error: The QuerySet value for an exact lookup must be limited to one result using slicing. Also, by default my formset will allow 3 file upload, how do I limit that to only one ? FileFormset2 = inlineformset_factory(Lecture, FileUpload, fields=('lecture',)) form3 = LecturePostForm(request.POST, user=request.user.teacher) if form3.is_valid(): lecture = form3.save() formset2 = FileFormset2(request.POST, request.FILES, instance=lecture, prefix='files') if formset2.is_valid(): formset2.save() formset2.save() class LecturePostForm(forms.ModelForm): lecture_title = forms.ChoiceField() course = forms.ChoiceField() def __init__(self, *args, **kwargs): user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['course'].choices = self.get_courses(user) self.fields['lecture_title'].choices = self.get_lectures(user) @staticmethod def get_courses(teacher): teacher_data = TeacherData.objects.get(teacher_ID=teacher.teacher_ID) return [(x.id, x.name) for x in Course.objects.filter(Q(teacher1=teacher_data) | Q(teacher2=teacher_data))] @staticmethod def get_lectures(teacher): teacher_data = TeacherData.objects.get(teacher_ID=teacher.teacher_ID) course_data = Course.objects.filter(Q(teacher1=teacher_data) | Q(teacher2=teacher_data)) … -
How to get and process Input for django-multiselectfield in Django rest framework via form-data
I have User model with food_prefrence field for which a user has the option to select multiple choices. In models, I am using MultiSelectField from django-multiselectfield to solve my problem. and in my User serializer, I am using fields.MultipleChoiceField provided by rest-framework. now my problem is how to get input from the user using form-data and how to process that in my view or serializer, as of now when I am trying to insert choices using postman with form-data selected, this is giving me an error when serializer.is_valid() is called { "food_preference": [ "\"'Indian', 'Continental'\" is not a valid choice." ] } below is my code snippet. #models.py class User(AbstractUser, BaseClass): food_preference = MultiSelectField(_('Food Preference'), choices=CONST_Food, blank=True, null=True) #serializer.py class UserSerializer(serializers.HyperlinkedModelSerializer): food_preference = fields.MultipleChoiceField(choices=CONST_Food, required=False) def update(self, instance, validated_data): instance.food_preference = validated_data.get('food_preference', instance.food_preference) instance.save() return instance, "Updated Successfully" #views.py def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.serializer_class(data=request.data, context={"request": self.request}) print(serializer.initial_data) if serializer.is_valid(raise_exception=True): ##<<<<<Execution stops here print("is valid") result = serializer.update(instance=instance, validated_data=request.data) if result[0] is None: return _error_response(400, EPHISH, result[1], {}) data = self.serializer_class(result[0], context={"request": self.request}).data return _response(data, status.HTTP_201_CREATED) else: return _einval_serializer_response(status.HTTP_400_BAD_REQUEST, self.serializer_class) also here is the screenshot from my postman -
Django Rest Framework Creating Foreign Key Serializer context object empty?
I'm trying my hand at creating a little django api for school. At the moment I'm having trouble getting the authorized user when I attempt to create a model with a foreign key. Here is the code I've been trying MODEL: class JobListing(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) company_name = models.CharField(max_length=80) job_position = models.CharField(max_length=50) job_phone = models.CharField(max_length=10) job_email = models.EmailField() job_description = models.TextField() job_schedule = models.CharField(max_length=500) job_post_date = models.DateField(auto_now_add=True) VIEW: class CreatePostView(generics.CreateAPIView): """ API endpoint that allows a Job Post to be created """ #queryset = '' authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = JobPostingSerializer SERIALIZER: class JobPostingSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = JobListing fields = ('user', 'company_name', 'job_position', 'job_phone', 'job_email', 'job_description', 'job_schedule') def create(self, validated_data): post = super().create(validated_data) post.save() return post def get_user(self, instance): user = self.context['request'].user return user.id URLS: urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth', include('rest_framework.urls', namespace='rest_framework')), path('home/', views.Home.as_view(), name='home'), path('login/', views.Login.as_view(), name='login'), path('getUserDetail/', views.TestSimpleUserJsonAuth.as_view(), name='getUserDetail'), path('getPosts/', views.getPosts.as_view(), name='getPosts'), url(r'signup/', views.CreateUserView.as_view(), name='signup'), url(r'createPost/', views.CreatePostView.as_view(), name='createPost') I have tried a number of different variations of this including overriding the get context method and trying to change the viewset I'm using. Nothing seems to get it working. Error I'm seeing right now is IntegrityError at /createPost/ NOT NULL … -
How can I customize default to django REST serializer
http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault I wants to read default value from userprofile automatically. Right now the offical method support User and DateTime. But I want my customized value. How can I do that? owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) -
Is it possible to change LDAP user attributes in Django?
So I am currently trying to programm a webapplcation for ldap-user to login and change their attributes. As of now, I can authenticate ldap-accounts (using django-auth-ldap), but I do not know how to modify their attributes (i.g. first_name etc.) I could not find anything helpful for a GUI-based webapp and I am wondering what I should use and how? Which library is the right on? django-ldapdb? django-ldap3 or anything else? But most importantly, where do I programm it. Do I have to work with form (EditProfileForm), models, views... I am quite new to Python and Django, so do not mind my knowledge. If you have any idea, a link or anything helpful, do not hesitite to post it. Thanks in advance. -
django not work alert
django 2.0.2 mac os 10.13 python 3.6.4 i want use alert to templates django settings.py MESSAGE_TAGS = { messages.DEBUG: 'alert-info', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } views.py def list(request) messages.ERROR(request,'invalid user', extra_tags='alert') return redirect('/') templates.html i tried in 2 ways 1. not work {% if messages %} <script> {% for message in messages %} alert({{message}}) {% endfor %} </script> {% endif %} 2. not alert just text + x <div class="content container"> {% if messages %} {% for message in messages %} <div class="alert {{ message.tags }} alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {{ message }} </div> {% endfor %} {% endif %} <div class="row"> <div class="col-md-8"> enter image description here way2 result this why not work alert and if you know set min_length at charfield tell me this -
Save a generated PIL image into an ImageField in django
I am using qrcode to generate qrcode. When a ticket is bought, or when bought is true, I would like to generate a qrcode image and make some changes using PIL. Finally save the modified canvas into the Image field of the model. class Ticket(models.Model): booked_at = models.DateTimeField(default=timezone.now) qrcode_file = models.ImageField(upload_to='qrcode', blank=True, null=True) bought = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.bought: ... ... qrcode_img = qrcode.make('some data') canvas = Image.new('RGB', (total_width, total_height), 'white') draw = ImageDraw.Draw(canvas) position = (left, top) canvas.paste(qrcode_img, position) self.qrcode_file = canvas self.booked_at = timezone.now() super(Ticket, self).save(*args, **kwargs) canvas.close() qrcode_img.close() else: self.booked_at = timezone.now() super(Ticket, self).save(*args, **kwargs) But this throws an error: AttributeError: 'Image' object has no attribute '_committed' How can I save a generated PIL image into an ImageField in django? -
Allow import/export functions for super users only
I would like to allow the import/export functions for superusers only. How can this be achieved? I managed to hide the import/export buttons through custom css. But I also would like to disable the corresponding function calls: http://localhost:9012/admin/persons/person/import/ http://localhost:9012/admin/persons/person/export/ -
Send notification on creating new object in DB
What I am using: I am using Django-REST-FrameWork & Django-Channels (WEBSocket). I have an app called "Tasks" (project/apps/tasks) and users allowed to create new Tasks via CREATE-endpoint. What I want: To send notification to Client when new object has been created via REST's CREATE-endpoint. project/apps/tasks/consumers.py: from channels.consumer import SyncConsumer class TaskConsumer(SyncConsumer): def websocket_connect(self, event): self.send({ 'type': 'websocket.accept', }) def websocket_receive(self, event): self.send({ 'type': 'websocket.send', 'text': event['text'], }) project/apps/tasks/views.py: from rest_framework.viewsets import ModelViewSet from tasks.consumers import TaskConsumer class TaskViewSet(ModelViewSet): serializer_class = TaskSerializer queryset = Task.objects.all() def create(self, request): serializer = TaskSerializer(data=request.data) if serializer.is_valid(): serializer.save() # My attempt to pass message to WEBSocket on creating new Task-object: instance = TaskConsumer() mydict = dict() mydict.update({ 'message': 'New Task has been created: {}'.format(serializer.data['task_name']) }) instance.websocket_receive(mydict) The problem: The problem is that I am not understanding the context of what I'm doing very well, is the concept of above is right ? Can I even achieve what I want using DRF and Channels ? And if so, how to do it in the right way ? Thank you. -
Need to go one level deeper into json but am not able, upon ajax server response
I am able to have the browser send the server the initial http post, and from the server I am able to send the browser the json which contains the json represented objects. But from here I am not able to populate the select options. We'll actually I am but it is only one level deep, and also for some season add it all into one option (least of my worries atm). It places this within the select option, if the data variable contains objects "[object, Object], [object, Object], [object, Object]" View Code if request.is_ajax(): selected_date = request.POST['selected_date'] slots_on_day = Calendar.objects.filter(date=selected_date) data = [] for cal in slots_on_day: data.append(model_to_dict(cal)) return JsonResponse(status=200, data={'slots_on_day': data}) json structure (data variable) [{'id': 47, 'date': datetime.date(2018, 3, 12), 'timeslot_A': datetime.time(10, 0), 'timeslot_B': datetime.time(12, 0), 'booked': True}, {'id': 45, 'date': datetime.date(2018, 3, 12), 'timeslot_A': datetime.time(8, 0), 'timeslot_B': datetime.time(10, 0), 'booked': False}] The Ajax Success success: function(data){ $.each(data, function(key, value){ $('select[name=slot]').append('<option value="' + key + '">' + value2 +'</option>'); }); } -
Issues with background-image: url in Webpack and sass-loader
Ok, so I am stuck despite going through relevant documentation line by line. Basically, I am trying to use in image in the background-image: url(...) statement and it isn't loading. Based on configuration, sometimes there are error messages from Webpack and sometimes not; there is always an error response from the server that it can't find the file. Note: All other styles are loading fine; just not url(). Here is the webpack.config.js: var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); const VENDOR_LIBS = [ 'axios', 'history', 'lodash', 'prop-types', 'react', 'react-dom', 'react-dropzone', 'react-redux', 'react-router-dom', 'react-router-redux', 'redux', 'redux-form', 'redux-thunk', 'reactstrap', 'react-responsive' ] module.exports = { context: __dirname, entry: { app: '../react/index', vendor: VENDOR_LIBS }, output: { path: path.resolve('./src/assets/bundles/'), filename: './js/[name].[chunkhash].js' }, module: { rules: [ { loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/, query: { presets: ["react", "es2015", "stage-1"] } }, { test: /\.json$/, loader: ['json-loader'] }, { test: /\.png|jpg$/, use: [ { loader: 'file-loader', options: { publicPath: path.resolve('./src/assets/bundles/img/'), outputPath: 'img/' } } ] }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'resolve-url-loader' }, { loader: 'sass-loader?sourceMap', options: { sourceMap: true } … -
Overriding Django Manager class
In my Django project I don't use database as a backend, but rather data from REST api endpoints. I understand I can override Manager class get_queryset() to return all objects. What would be simple case how to do it? Example here still uses a database: https://docs.djangoproject.com/en/2.0/topics/db/managers/ -
Django url/views
I have no idea why my code is not working? I am trying to return user_id, parse it to url and then open up details.html with that user_id. I realize this may not be the most efficient way of doing this. Any suggestions and help appreciated. @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def patientDetails(request): return render(request, 'personalInfo/details.html', {}) @login_required(login_url="http://127.0.0.1:8000/accounts/login/") def after_login(request): return HttpResponseRedirect('/personalInfo/details/%d/'%request.user.id) urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/$', views.after_login, name='patient'), url(r'^details/(?P<personalInfo_id>[0-9]+)/&', views.patientDetails), ] -
How to desplay multiple images for django model
Here is my image model, that I tied to the model Product class Image(models.Model): name = models.CharField(blank=True,max_length=20) product = models.ForeignKey(Product) image = models.ImageField(blank=True,null=True) def __str__(self): return self.name Here is the view that I am using to try and display the images def category(request, category_id): categories = Category.objects.all() images = Image.objects.all() products = Product.objects.all() try: category = Category.objects.get(id=category_id) except Category.DoesNotExist: category = None; template = loader.get_template('index.html') context = { 'category': category, 'categories': categories, 'images': images, 'products': products } return HttpResponse(template.render(context,request)) and here is the html {% for image in images %} <a href="#" class="image"><img src="{{ image.url }}"></a> {% endfor %} I know this definitely wouldn't work,but atleast this code displays the page instead of an error so i have been using it, can anyone please point me in the right direction to dipslay each image associated with each product. Thank you! -
Attempting to override update method in django rest framework to return entire queryset after update
I am attempting to override the update method for a put request in django rest framework. Instead of returning just the updated object. I want it to return the entire queryset including the updated object. For the use case I am working on, its just easier. Starting from the top. I am using Django Rest Frameworks Generics. class SearchCityDetail(RetrieveUpdateDestroyAPIView): queryset = SearchCity.objects.all() serializer_class = SearchCitySerializer I override the classes PUT method and inherent from my custom mixin. class SearchCityDetail(RetrieveUpdateDestroyAPIView, UpdateReturnAll): queryset = SearchCity.objects.all() serializer_class = SearchCitySerializer def put(self, request, *args, **kwargs): return self.updatereturnall(self,request, *args, **kwargs) the custom mixin looks like this (my custom added code which differs from the normal update code had the commment #Custom Code above it: from rest_framework import status from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.mixins import UpdateModelMixin """ Update a model instance and return all. """ #Custom Code class UpdateReturnAll(UpdateModelMixin): #custom name normally just update def updatereturnall(self, request, model, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on the instance. instance._prefetched_objects_cache = … -
dockercoompose can't run local file, no such file or dir
Now I have such a folder with files like this: drwxrwxr-x 16 hehe hehe 4096 3月 2 10:05 adminset <===dir which contain all the code to run -rwxrwxr-x 1 hehe hehe 537 3月 2 10:33 docker-compose.yml drwxrwxr-x 2 hehe hehe 4096 3月 2 10:14 mysql_db -rwxrwxr-x 1 hehe hehe 4079 3月 2 10:08 wait-for-it.sh And my docker-compose file like this: version : "2" services : srv_db: build : ./mysql_db/ command : mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci --init-connect='SET NAMES UTF8;' --innodb-flush-log-at-trx-commit=0 expose : - "3306" environment: - MYSQL_DATABASE=xxx - MYSQL_ROOT_PASSWORD=xxx srv_web: build : ./adminset/ # command : bash -c "./wait-for-it.sh srv_db:3306 && python ./adminset/manage.py runserver 0.0.0.0:8000" <==Number 1 # command: ["./wait-for-it.sh", "srv_db:3306", "--", "python", "./adminset/manage.py runserver 0.0.0.0:8000"] <===Number 2 volumes : - ./adminset:/code ports : - "8000:8000" depends_on : - srv_db My purpose is to run wait-for-it script to wait until mysql service starts and then run python manage.py to start Django app. But if I use this line in my docker-compose file: command : bash -c "./wait-for-it.sh srv_db:3306 && python ./adminset/manage.py runserver 0.0.0.0:8000" <===Number 1 the out put it always: srv_web_1 | bash: ./wait-for-it.sh: No such file or directory If I use another line : command: ["./wait-for-it.sh", "srv_db:3306", "--", "python", "./adminset/manage.py runserver … -
Django Form not rendering on HTML
I'm a beginner in developing with django, I've been having a problem with a form I've made, I've been searching for similar problems but none of them could solve my problem. No field of the form render in the HTML but the button renders fine my form: class Meta: model = Aluno nome = forms.CharField(min_length=15, max_length=100) direccion = forms.CharField(min_length=10, max_length=250) ciudad = forms.CharField(min_length=3, max_length=50) provincia = forms.CharField(min_length=4, max_length=50) comunidad = forms.CharField(min_length=4, max_length=50) cp = forms.IntegerField() faixas = ['Blanco', 'Gris', 'Amarilla', 'Naranja', 'Verde', 'Azul', 'Roxa', 'Marrón', 'Preta'] graduacion = forms.ChoiceField(choices=faixas) inicio = forms.DateInput() nacimento = forms.DateInput() lic = ['Basica', 'Completa'] licencia = forms.ChoiceField(choices=lic) documento = forms.CharField(min_length=4, max_length=9) email = forms.EmailField(min_length=10) profesor = forms.CharField(min_length=5, max_length=100) centro = forms.CharField(min_length=5, max_length=50) my view: def novo(request): if request.method == "POST": form = NovoAluno() if form.is_valid(): form.save() return redirect('aluno_detalhes', pk=form.pk) else: form = NovoAluno() return render(request, 'academia/cadastro.html', {'form': form}) my model: class Aluno(models.Model): nome = models.CharField(max_length=100) direccion = models.CharField(max_length=250) ciudad = models.CharField(max_length=50) provincia = models.CharField(max_length=50) comunidad = models.CharField(max_length=50) cp = models.IntegerField() nacimento = models.DateField() inicio = models.DateField() documento = models.CharField(max_length=9) email = models.EmailField() profesor = models.CharField(max_length=100) centro = models.CharField(max_length=50) graduacion = models.CharField(max_length=10) licencia = models.CharField(max_length=8) content block that the form goes {% block content %} <h1>Novo … -
Django REST framework: "invalid keyword argument" error but field exists in the model
I'm using Django with the REST Framework. I'm defining an APIView and in it, I create an ORM object using create(). One of the fields I pass the create function is failing, saying it's not a valid keyword argument. This is a new field I'm adding. The field exists in the model and the serializer. Another similar new field is NOT failing. Traceback: Internal Server Error: /api/new_thing Traceback (most recent call last): File "/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/local/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch response = handler(request, *args, **kwargs) File "/other_app/rest_apis.py", line 336, in post flag=false File "/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/local/lib/python2.7/site-packages/django/db/models/query.py", line 346, in create obj = self.model(**kwargs) File "/local/lib/python2.7/site-packages/django/db/models/base.py", line 480, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'doohickeys' is an invalid keyword argument for this function API View: class NewThing(APIView): renderer_classes = (JSONRenderer,) serializer_class = StuffSerializer @detail_route(methods=['POST']) def post(self, request, pk, format=None): # do stuff whatsits_list = [] # list … -
Problems with nginx. How to make an authenticated call to the API using jwt (Django)?
I have some problems with nginx and django-rest-framework. I've already been trying to figure out how to make an authenticated request to the API for about 24 hours. I'm really exhausted and hope somebody can help me. I have the following nginx conf: location / { if ($request_method = OPTIONS ) { add_header 'Access-Control-Allow-Origin' "*; add_header 'Access-Control-Allow-Methods' "GET, PUT, POST, PATCH, DELETE, OPTIONS"; add_header 'Access-Control-Allow-Headers' "Authorization, 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range"; add_header 'Access-Control-Allow-Credentials' "true"; } uwsgi_pass django; include /path/to/your/mysite/uwsgi_params;, } And the following code on the client side: var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.open('POST', 'http://api/v0/api-token-auth/', true); xhr.setRequestHeader('Authorization', 'JWT ' + getCookie("token")) xhr.send(JSON.stringify(json)); And I always get 401 Unauthorized. I don't know what else I need to do to fix this problem. -
Django - Performance between images as fields vs images as ForeignKey model
I have a model called Listing. Users can upload up to 20 photos for each Listing. My question is: Performance-wise, is it better to create 20 fields for Listing, and leave them blank if the user doesn't fill them, or create a ListingPhoto foreignkey and create 1 ListingPhoto for each uploaded image? class Listing(models.Model): img_1 = models.ImageField(blank=True) img_2 = models.ImageField(blank=True) ... img_20 = models.ImageField(blank=True) OR class Listing(models.Model): ... class ListingPhoto(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) photo = = models.ImageField() -
AJAX: Having trouble retrieving queryset from server and appending to select options
I am able to send the value of the input field with the id datepicker to the server. And with this in the view I filter the time slot by the ones that occur on the same date. Where I am having difficulties is sending this queryset to the browser and then appending this to the options. I'm still relatively new to javascript I apologize if this is a newb question. I definitely appreciate any feedback! My View: if request.is_ajax(): selected_date = request.POST['selected_date'] slots_on_day = Calendar.objects.filter(date=selected_date) return HttpResponse(slots_on_day) My Javascript: $(document).ready(function() { $("#datepicker").change(function(){ document.getElementById("display_slots").style.display ="block"; $.ajax({ type: 'POST', data: { 'selected_date':$('#datepicker').val(), 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: function(resp){ console.log('slots_on_day') for (var i=0; i < resp['slots_on_day'].length;++i){ addOption( document.getElementById("display_slots"), resp['slots_on_day'][i], resp['slots_on_day'][i]); } } }); }); }); Notes: the id=datepicker field triggers the ajax event. I then want to receive the response from the server and append the options to the input with the id=display_slots -
Django static files not loading. Fix settings.py to load files on relative paths
I downloaded this template https://github.com/BlackrockDigital/startbootstrap-resume and I am trying to use it in Django. I am having problems with static files, that is .css and .jpg. My project is called Djangoresume and the app is resume. I copied the template files to my /home/kinkyboy/Djangoresume/resume/templates/resume (if you think the last resume folder is not the common way to do organize the project, please let me know): > pwd /home/kinkyboy/Djangoresume/resume/templates/resume > tree -L1 . ├── css ├── gulpfile.js ├── img ├── js ├── index.html ├── scss ├── static │ ├── css │ ├── img │ ├── js │ ├── scss │ └── vendor └── vendor Notice that I added the same static files to a new folder "static" to increase my chances of making Django work, but I'd rather not use it. This is the IMO relevant part of settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/resume/templates/resume/static') ] But I tried many different folders. I see that {% static %} uses STATIC_URL, and probably staticfiles will use STATICFILES_DIRS. BASE_DIR is where manage.py is, right? I copy here a shorter version of the index.html in the repository: <!DOCTYPE html> <html lang="en"> {% load static %} {% load staticfiles …