Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm struggling with making search function with multi condition using django queryset
def influencer_board(request): user_input = [] index_list = [] influencer = Influencer_DB.objects.all() if request.method == 'GET': sns_type = request.GET.get('sns_type') #0 follower_num_min = request.GET.get('follower_num_min') #1 follower_num_max = request.GET.get('follower_num_max') #2 name = request.GET.get('name')#3 gender = request.GET.get('gender')#4 sns_id = request.GET.get('sns_id')#5 keyword = request.GET.get('keyword')#6 user_input.append(sns_type) user_input.append(follower_num_min) user_input.append(follower_num_max) user_input.append(name) user_input.append(gender) user_input.append(sns_id) user_input.append(keyword) for col in user_input: if col != "": index = user_input.index(col) index_list.append(index) influencer = Influencer_DB.objects for index in index_list: if index == 0: influencer = influencer.filter(sns_type=sns_type) if index == 1: influencer = influencer.filter(follower_num__gte = follower_num_min) if index == 2: influencer = influencer.filter(follower_num__lte = follower_num_max) if index == 3: influencer = influencer.filter(name=name) if index == 4: influencer = influencer.filter(gender = gender) if index == 5: influencer = influencer.filter(sns_id=sns_id) if index == 6: influencer = influencer.filter(keyword__icontains = keyword) return render(request,"influencer_board.html",{'influencer':influencer,"sns_type":sns_type,'follower_num_max':follower_num_max, 'followever':follower_num_min,'name':name, 'gender':gender,'sns_id':sns_id,'keyword':keyword}) return render(request,"influencer_board.html",{'influencer':influencer}) Like the code above, I get 7 search condition from user. Also if user inputs less than 7 conditions, still I want to filter Database with those conditions. However, it keep making enter image description here this error. the function seems to work properly because url "http://127.0.0.1:8000/influencer_board/GET?sns_type=%EC%9D%B8%EC%8A%A4%ED%83%80%EA%B7%B8%EB%9E%A8&follower_num_min=18000&follower_num_max=&name=&gender=&sns_id=&keyword= containing condition what I submitted but making 404 error. How can I solve this problem -
Why I can't pass the widget attr to form constructor in UserChangeForm in Django?
I have a form which inherited from UserChangeForm. I have given the form field a bootstrap class but why when i rendered it out there was not bootstrap class inside that field? # my model class CustomUser(AbstractUser): teacher_type = models.ForeignKey(Type, on_delete=models.CASCADE, blank=True) # my form class EditUserForm(UserChangeForm): class Meta: model = CustomUser fields = ['teacher_type',...] def __init__(self, *args, **kwargs): super(EditUserForm, self).__init__(*args, **kwargs) self.fields['teacher_type'].widget.attrs.update({'class': 'form-control'}) # view def home(request): template_name = "app/home.html" eForm = acc_forms.EditUserForm(instance=request.user) return render(request, template_name, {'eForm': eForm}) # template {{eForm.teacher_type}} When I inspected in browser I saw like this <select name="teacher_type" id="id_teacher_type"> <option value="1">Full</option> <option value="2">Time</option> </select> it supposed to has class="form-control" inside the select tag but why it doesn't? -
How to redirect to the ?next=url instead of the success_url in a generic class based view in django?
I'd like to know how to redirect to the ?next=url instead of the success_url in a generic class based view in django. the view class CategoryUpdateView(UpdateView): model = Category template_name = "categories/category_edit.html" fields = ('name', 'description', 'image') success_url = 'category_list' in the template <a href="{% url 'category_edit' category.id %}?next={% url 'another_url' %}">Add</a> After updating the category, I want to be redirected to the nex value in the link instead of the success_url. How can I do that? Thanks. -
How many spiders can we run in a scrapy?
I want to run many spiders with my scrapy. Does that make the crawling process slower or is there any limit for spiders to run? Is running many unlimited spiders makes the process slow ? Is there anyone who is experienced with Scrapy? -
Excel to django (with Image)
Is it possible to import excel with image to django ? I dont have any error when it comes in foreignkey, i Just wonder if is it possible with image. resources.py class CityResource(resources.ModelResource): category = fields.Field(attribute='category', column_name='category', widget=ForeignKeyWidget(MunicipalityCategory)) class Meta: model = City models.py class City(models.Model): image = models.ImageField(upload_to='image', null=True, blank=True, default='default1.jpg') city = models.CharField(max_length=500, blank=True) category = models.ForeignKey(MunicipalityCategory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Municipality") here is the sample excel file -
django, I want to change array[0] of __ proto__ to an object
console.log(test) (4) [{…}, {…}, {…}, {…}] 0: {d_code: 1, name: "test1", position: "RB", code_id: 1} 1: {d_code: 2, name: "test2", position: "LB", code_id: 2} 2: {d_code: 3, name: "test3", position: "ST", code_id: 2} 3: {d_code: 4, name: "test4", position: "RW", code_id: 1} length: 4 __proto__: Array(0) I would like to change the above code like below. {01: Array(3), 02: Array(3), 03: Array(3), reset: Array(0), test: Array(1)} 01: (3) [{…}, {…}, {…}] 02: (3) [{…}, {…}, {…}] 03: (3) [{…}, {…}, {…}] reset: [] test: [{…}] __proto__: Object view.py class testDoctor(generics.ListCreateAPIView): queryset = DoctorList.objects.all() serializer_class = DoctorListSerializer def list(self, request): test = DoctorList.objects.values() return Response(test) How do I change 'proto'? I want to change it in view. -
django.db.utils.IntegrityError: NOT NULL constraint failed; Django TestCase
I'm attempting to create a model instance of the Photo model and adding a User to it for the below TestCase. Upon running the test, I get an IntegrityError: django.db.utils.IntegrityError: NOT NULL constraint failed: photos_photo.photographer_id. Not sure why I'm getting the error when every other field is automatically populated? test_forms.py class RedundantImageUpload(TestCase): @classmethod def setUpTestData(cls): cls.test_image = SimpleUploadedFile( "test_image.jpg", content=b'''GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc, \x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00''', content_type="text/html" ) user = User.objects.create_user("User") form = PhotoForm({'title': "Image Title"}, {'source': cls.test_image}) form.save(commit=False) form.photographer = user form.save() cls.submitted_form = PhotoForm( {"title": "Image Title"}, {"source": cls.test_image} ) def test_image_upload_path_exists(self): with self.assertRaisesMessage(ValidationError, "Image already uploaded: test_image.jpg"): self.submitted_form.errors forms.py from django import forms from django.core.exceptions import ValidationError from django.core.files.storage import get_storage_class from .models import Photo class PhotoForm(forms.ModelForm): title = forms.CharField(strip=False, validators=[validate_title]) def clean_source(self): stored_user_uploads = get_storage_class()() file_name = self.cleaned_data["source"].name if stored_user_uploads.exists(file_name): raise ValidationError(f"Image already uploaded: {file_name}") return self.cleaned_data["source"] class Meta: model = Photo fields = ["source", "title"] models.py from django.db import models from django.conf import settings # Create your models here. class Photo(models.Model): source = models.ImageField(upload_to='uploads/%Y/%m/%d/') title = models.CharField(max_length=50) upload_date = models.DateField(auto_now_add=True) likes = models.IntegerField(default=0) photographer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.title -
Django forms.ModelForm slugfield db_index=True
I have a slug field in my Model with db_index true... When a new record is added through my form, i want slug field to be filled with slugified text that i have coded in my model save() method. However, this never happens as i am stuck at form field level validation. I have tried many options like clean(), clean_field() etc but all of them runs only after slug field has something entered. Please help class Student(models.Model): ... slug = models.SlugField(max_length=100, db_index=True) -
I am not able to understand this error: TypeError: cannot convert dictionary update sequence element #0 to a sequence
I am getting stuck with the new_entry functionality , This is a project in the crash course for python book , I have tried to verify my code a number of times not able to figure out why I get this error TypeError: cannot convert dictionary update sequence element #0 to a sequence , please help me to resolve this issue , thanks!! **views.py** from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic from .forms import TopicForm from .forms import EntryForm # Create your views here. def index(request): return render(request, 'learning_logs/index.html') def topics(request): # display all the topics topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): # display entries pertaining to a topic topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) def new_topic(request): # fill a new topic if request.method != 'POST': # No data submitted , create a blank form form = TopicForm() else: # post data submitted , process data form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) def new_entry(request, topic_id): # Enter a new entry into any topic … -
How to user tesseract in django to convert image in form request?
[![enter image description here][1]][1] ** [1]: https://i.stack.imgur.com/oXYwf.png ** -
Django: I'm almost positive my code is right but it's not working
Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order: admin/ hello/ newyear/ tasks/ [name='index'] tasks/ add [name='add'] The current path, tasks/add/, didn't match any of these. I'm become frustrated because I'm very confident that my code is right. Here is my urls.py code from tasks directory: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("add", views.add, name="add") ] Here is my urls.py code from project directory: urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")), path('newyear/', include("newyear.urls")), path('tasks/', include("tasks.urls")) ] I don't think anything is wrong with the project directory because tasks works but tasks/add does not. -
Django getting related objects from M2M
For example, I have three Models in django: class Car(models.Models): range = models.DecimalField() speed = models.DecimalField() def __str__(self): return self.speed class Group_of_Cars(models.Models): name = models.CharField() starting_city = models. CharField() car = models.ManyToManyField(Car) def __str__(self): return self.name class Arrival_time(models.Models): Location_of_ArrivalPoint = models.CharField() Last_known_location_of_CarGroup = models.CharField() Group_of_Cars = models.ForeignKey(Group_of_Cars) def function(self): "Get speed of the "Car" in "Group_of_Cars" def __str__(self): return self. Location_of_ArrivalPoint This is an example of what I want to do, not my actual models. The idea is for the user to input a series of values for the type of "Cars" such as speed and range. I'd like "Cars" to be selected when defining parameters for "a Group_of_Cars". What I'm not sure how to do is how to get the speed of the car, for the Group_of_Cars for which I need to calculate an arrival time (Group_of_Cars consists of one type of car and I'd like 'Arrival_time' to be its own table). Thank you for any input. -
'Next' page - Django
I'm building an ecommerce and there is the following scenario: user is on the cart page and clicks on the checkout page. Two things may happen: If he is not logged in, he is redirected to the login page and if he has an account, then he goes to checkout page: Cart page -> Checkout page -> Login page -> Checkout page It's working perfectly. If the user has not previosly registered, the user clicks on a link to the register page and then he goes to checkout page: Cart page -> Checkout page -> Login page -> Register page -> Checkout page It's not working. Inside the login page there is a link to go to the register page and I tried to attach the 'next' parameter but after the user has registered, he is not going to the checkout page: <a href="{% url 'account:register' %}?next={{ next }}">Do not have an account? Register now!</a> Any help? Do I need to code something inside the views.register? I thought only the link could help me! Thank you! -
How to update django model based form(having choices option) records by using html form
I am trying to update my pre existing model**(ShiftChange)** and in model based form i have used CHOICES as shown below. from django.db import models SHIFT_CHOICES = ( ('9.00-6.00','9.0-6.0'), ('6.30-3.30', '6.30-3.30'), ('12.30-3.30','12.30-3.30'), VENDOR_CHOICES = ( ('genesys','Genesys'), ('rmsi', 'RMSI'), ('tcs','TCS'), ('Cognizant', 'Cognizant'), ('CTS', 'CTS.') ) class ShiftChange(models.Model): ldap_id = models.CharField(max_length=64) Vendor_Company = models.CharField(max_length=64,choices=VENDOR_CHOICES,default='genesys') EmailID = models.EmailField(max_length=64,unique=True) Shift_timing = models.CharField(max_length=64,choices=SHIFT_CHOICES,default='General_Shift') Reason = models.TextField(max_length=256) # updated_time = models.DateTimeField(auto_now=True) And to update i'm using html based form because i wanted to display content to end user(end user will click on update button and if he want he Can change value by selecting dropdown button). I have implemented Create,Retrieve and delete view and it is working fine but update operation is not working.Please find the html code which i am using. update.html <p>User information Update Form</p> <!-- <h5><span3>Note:</span3> For timing please use this format e.g 1.Morning Shift = <span2>6.30-3.30</span2> <br>2.Second Shift= <span1>3.30-12.30</span1><br>3.general Shift =<span4>9.00-6.00</span4></h5>--> <form method="post" class="post-form"> {%csrf_token%} Ldap ID: <input type="text" name="ldap_id" value="{{oneuser.ldap_id}}"><br><br> Email ID: <input type="email" name="EmailID" value="{{oneuser.EmailID}}"><br><br> Company Name:<select name="Vendor_Company" <option value="{{oneuser.Vendor_Company}}">Genesys</option> <option value="{{oneuser.Vendor_Company}}">RMSI</option> <option value="{{oneuser.Vendor_Company}}">TCS</option> <option value="{{oneuser.Vendor_Company}}">Cognizant</option> <option value="{{oneuser.Vendor_Company}}">CTS</option></form></select> <br><br> Shift Timing:<select name="Shift_timing" choices=VENDOR_CHOICES <option value="{{oneuser.Shift_timing}}">9.00-6.00</option> <option value="{{oneuser.Shift_timing}}">6.30-3.30</option> <option value="{{oneuser.Shift_timing}}">12.30-3.30</option></div></select> <br><br> <!-- Shift Timing: <input type="text" name="Shift_timing" value="{{oneuser.Shift_timing}}"><br><br>--> Reason/justification for Change: … -
How to render to specific html div with value from django views?
I am trying to deploy a machine learning model using Django. Here I am trying to do is take input from the HTML form, predicting value using a trained model, and sending that result value to the HTML page. Still here working good. But I want to go to a specific division(div tag) of the HTML page based on division(div tag) id. Please help me, anyone; how can I fix this problem. HTML code File name :- nlpdocs.html <div style='background:pink;height:300px;width:600px;left:150px;position:relative' id="spam_try"> <form action='smsclassifier' method='POST' enctype='multipart/form-data' > {% csrf_token %} <h2 style='left:80px;position:relative'>SMS Spam Classifier</h2> <label>SMS :- </label> <textarea id="smstext" name='smstext' rows="4" cols="50" placeholder="Enter SMS here </textarea> <button type='submit' > Submit</button> </form> </div> <p><h4 style="color: #55CEFF">Input SMS Text :- </h4><h6> {{sms_text}}</h6></p> <p><h4 style="color: #55CEFF">Entered SMS is :- </h4><h6>{{result}}</h6></p> I create urls file within the django app folder. urls.py urlpatterns = [ path('',views.home_view,name='home_view'), path('index.html',views.home_view,name='home_view'), path('nlpdocs.html',views.nlpdocs, name='nlpdocs'), path('smsclassifier', views.sms_spam_classification, name='smsclassifier'), ] views.py @csrf_exempt def sms_spam_classification(request): """ Input :- Text Output :- string Return :- classify input text spam or not """ if request.method == 'POST': sms_text = request.POST.get('smstext') result = predict_new_text(sms_text) result_dict = {'result':result, 'sms_text':sms_text} return render(request, 'nlpdocs.html#spam_try', result_dict) If I send the only nlpdocs.html to render function, that one works but goes to … -
Django - Handle a user vote per set amount of time
I'm working on a Django site that allows users to post to car shows and then vote for entries. Previously you could just vote for your top 3, but now I'm trying to add the ability to re-vote after some configurable amount of time (eg. daily, weekly). The first option lent itself to Django m2m fields nicely. Essentially just added a 'votes' m2m field to each entry and then tracked who voted. With timing involved though I separated it out into a new 'vote' model as shown below. The problem I'm having though is it introduces some pretty complicated queries where anytime I want to get whether a user can vote, I have to check against the timestamps. I was wondering if anyone had a better way to handle this or a clever way of integrating into the model an 'active' indicator in terms of whether the vote has expired based on the timing of the event. class Vote(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="votes", on_delete=models.CASCADE, ) post = models.ForeignKey( Post, related_name='votes', on_delete=models.CASCADE, ) timestamp = models.DateTimeField(auto_now_add=True) An example query: # Returns an active vote of a user/entrant combo that has not been reset by a voting period. def get_active_vote(self, … -
Django: 'int' object is not iterable when different serializers in a Viewset
I have an issue when making a GET request on this endpoint: /api/stock/{bar_id}/. It should return stock information for a specific Bar ID. In my schema, the Stock model contains the following properties: bar_id as a foreign key. ref_id as a foreign key. stock as integer. sold as integer. In order to get the relevant information, I intended on calling the BarDetailsSerializer through the Stock Viewset, thinking it might be easier than having to filter the Stock table according to the bar_id value provided in the URL, as it would automatically provide the Stock collection related to that specific Bar ID. Making a GET request on http://localhost:8000/api/bars/1 (as shown below) provides the information I need. However when I'm trying to get this response via the Stock Viewset with this end-point http://localhost:8000/api/stocks/1 I get the following error: TypeError at /api/stocks/1/ 'int' object is not iterable So is what I'm trying to do even possible in the first place, or is there a better way or some best practise to apply here? Thanks for your responses! Here is my Stock Serializer file: from rest_framework import serializers from ..models.model_stock import Stock from .serializers_reference import * from .serializers_bar import * class StockIndexSerializer(serializers.ModelSerializer): """ Serializer … -
FileNotFoundError at /login/ [Errno 2] No such file or directory: '/app/media/profile pics/photo_0cEQgDs.jpg'
when ever i try to log in this error msg came up in heroku. but in my local machine it's having no problem. dont know wgat to do? here is my setting.py FileNotFoundError at /login/ [Errno 2] No such file or directory: '/app/media/profile pics/photo_0cEQgDs.jpg' Request Method: POST Request URL: https://peaceful-chamber-65312.herokuapp.com/login/ Django Version: 3.1 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/app/media/profile pics/photo_0cEQgDs.jpg' -
Return value for importlib.import_module()
I have a strage problem with importlib.import_module(). I cannot find documentation which return value is expected. It seems that return values sometimes different. I'm using python3.8 with Django 2.2 and there is a function import_string() https://github.com/django/django/blob/stable/2.2.x/django/utils/module_loading.py#L17 def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError as err: raise ImportError("%s doesn't look like a module path" % dotted_path) from err module = import_module(module_path) try: return getattr(module, class_name) except AttributeError as err: raise ImportError('Module "%s" does not define a "%s" attribute/class' % ( module_path, class_name) ) from err The line module = import_module(module_path) imports a module, and sometimes this module has attributes, but sometimes it doesn't. So for example if I do print(dir(module)) sometime I see object like this: ['BaseCache', 'CONNECTION_INTERRUPTED', 'ConnectionInterrupted', 'DJANGO_REDIS_SCAN_ITERSIZE', 'RedisCache', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'functools', 'import_string', 'logging', 'omit_exception', 'settings'] But sometimes it looks like this: ['__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] So obviously for second case next line after import fails: return getattr(module, class_name) I wonder why this may happen? I think it's not backend library problem … -
excel to django 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte
Why is it i am receiving this kind of error? utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte ? def excel_cities(request): if request.method == 'POST': file_format = request.POST['file-format'] City_resource = CityResource() dataset = Dataset() new_city = request.FILES['importData'] if file_format == 'xls': imported_data = dataset.load(new_city.read().decode('utf-8'), format='xls') result = City_resource.import_data(dataset, dry_run=True) elif file_format == 'xlsx': imported_data = dataset.load(new_city.read().decode('utf-8'), format='xlsx') # Testing data import result = City_resource.import_data(dataset, dry_run=True) this is my html <form method="post" action="/excel_cities/" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="importData"> <p>Please select format of file.</p> <select name="file-format" class="form-control my-3"> <option selected>Choose format...</option> <option>xls</option> <option>xlsx</option> </select> <button class="btn btn-primary" type="submit">Import</button> </form> this is the excel i want to import to django this is the documentation i followed https://dev.to/coderasha/how-to-export-import-data-django-package-series-3-39mk -
In django's view.py, I want to change it to a string form rather than a json form
django: view.py class ListPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PalyerListSerializer react: console.log(player) (4) [{…}, {…}, {…}, {…}] 0: {d_code: 4, name: "test4", position: "RW", code: 1} 1: {d_code: 3, name: "test3", position: "ST", code: 2} 2: {d_code: 2, name: "test2", position: "LB", code: 2} 3: {d_code: 1, name: "test1", position: "RB", code: 1} length: 4 __proto__: Array(0) When I use console.log I want it to be output in string format. I can't use JSON.stringify as I can use the map function. I want to convert it to string format in view.py. How can I convert it? -
Improperly configured error when running django-admin check
I'm relatively new to Django and programming, so I have no idea what caused this error or how to fix it. I asked another question related to the same error but got no responses so here's a simpler version. When I run Django-admin check (along with various other commands not including run server) I get the following error. django.core.exceptions.ImproperlyConfigured: Requested setting LANGUAGE_CODE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have spent hours googling and nothing I find works (I either get this error or a module not found error). What can I do? here's the full traceback: Traceback (most recent call last): File "/Users/linnea/opt/miniconda3/bin/django-admin", line 8, in <module> sys.exit(execute_from_command_line()) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/commands/check.py", line 69, in handle databases=options['databases'], File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/management/base.py", line 396, in check databases=databases, File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/checks/registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/core/checks/translation.py", line 60, in check_language_settings_consistent get_supported_language_variant(settings.LANGUAGE_CODE) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Users/linnea/opt/miniconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 68, in _setup % (desc, … -
Using CookieCutter-Django & Docker, how do I get a 'hello, world' app to run on the development server?
I am using Django 3.1 in VSC and Docker Desktop for Mac 2.3.0.5. I am following the cookiecutter-django documentation here (https://cookiecutter-django.readthedocs.io/en/latest/developing-locally-docker.html) I have been able to build the stack, run the stack, and execute management commands without errors. I built an app in the second level per the manual fix specified here: (https://github.com/pydanny/cookiecutter-django/issues/1725#issuecomment-407493176) It's a simple 'hello, world' app that I want to run on my local development server. When I'm in my root directory and I run the server, I get ~/ccdocker34 $ docker-compose -f local.yml run --rm django python manage.py runserver Starting postgres ... done Creating ccdocker34_django_run ... done PostgreSQL is available Watching for file changes with StatReloader INFO 2020-09-24 01:13:43,008 autoreload 8 140145520564032 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 24, 2020 - 01:13:43 Django version 3.0.10, using settings 'config.settings.local' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But when I access http://127.0.0.1:8000/ the error on Chrome reads: This site can’t be reached 127.0.0.1 refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED I get a similar result when I attempt to access the paths listed in the "users" app, … -
Django getting one to many on same query
I need to display a view with Courses with its dependable Lectures on an accordion in html. A Course has many Lectures. class Course(models.Model): title = models.CharField(max_length=1500) def __str__(self): return self.title class Lecture(models.Model): title = models.CharField(max_length=1500) course = models.ForeignKey(Course, on_delete=models.CASCADE) content = models.TextField() def __str__(self): return self.title It seems like all the examples I have found. Get the relationship after doing a filter or getting the first object like this: Course.objects.first().lecture_set.all() This gets all the lectures for the first one. But I need to get all Courses with all lectures. Something like this: Course.objects.all().lecture_set.all() or Course.objects.filter('all').lecture_set.all() This way I could iterate over Courses and then on each Course iterate again with Course.lectures Does anyone know the best practice to achieve this? -
Upload File using Vue axios and Django Python Backend
I have VueJs as my front end where i have upload component and using formdata to create request and axios to make rest api call to backend written in Django Python. My Front upload method looks like: uploadFiles() { if (!this.currentFile) { this.message = "Please select a file!"; return } else { let formData = new FormData(); formData.append("file", this.currentFile); const instance = axios.create({ baseURL: "<URL>", withCredentials: false, }); instance .post("/test/", formData, { headers: { "content-type": "multipart/form-data", }, }) .then((response) => { console.log("Success!") console.log({ response }) }) .catch((error) => { console.log({ error }) }) } }, Now backed micro service is Django Python where I want to use the file. However i am not getting the file here. Code looks like below @api_view(['POST']) def attachment(request): myFile = request.FILES myfile2 = request.data.initial_data i tried above two ways to extract files from request object but no success, however it works if i send request via postman.