Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload multiple images using a single file upload button in django forms
I have been struggling to upload multiple images using single file upload button in django forms in my blog post. I will highly appreciate any assistance especially in creating the views.py that will enable the functionality. Here is part of my code. models.py from django.db import models from django.utils.text import slugify from django.conf import settings from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver def upload_location(instance, filename, **kwargs): file_path = 'posts/{author_id}/-{filename}'.format( author_id=str(instance.author.id), filename=filename ) return file_path class Post(models.Model): title = models.TextField(max_length=100, null=False, blank=False) detail = models.TextField(max_length=500, null=False, blank=False) date_published = models.DateTimeField(auto_now=True, verbose_name='date published') date_updated = models.DateTimeField(auto_now=True, verbose_name='date updated') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.detail class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_location) def __str__(self): return self.post.detail @receiver(post_delete, sender=Post) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) def pre_save_ad_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.author.username + '-' + instance.detail) pre_save.connect(pre_save_ad_post_receiver, sender=Post) forms.py from django import forms from posts.models import Post, PostImage class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['type', 'category', 'sub_category', 'detail', 'currency', 'price'] class ImageForm(forms.Form): images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = PostImage fields = ['images'] home.html <form class="post-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ posts_form }} {{ images_form … -
Django Fullcalendar Not rendering
I will get straight to the point. I'm using FullCalendar in mu application, and it's working fine, as aspected, but somehow, I have bugs when I try to render the calendar with ajax call, so the second time. When I call the landing page, the view, calendar gets rendered properly, but when I try to filter down the calendars using ajax implementation, the rendering is lost! I literally have no idea why is this happening, so any help will be great! The idea is simple, when I land on the page, I have all calendars rendered, and if I want to chose the particular calendar group, I just want to do a basic filtering depending on the users data. First, this is my function which handles the page : @login_required(login_url='registration/login') def add_event(request, pk): cal_group_param = request.GET.get('value_from_the_user', None) #Takes the users input from the frontend context = {} ... # Code which is nor relevant for this question ... events_all = Events.objects.all() if cal_group_param: calendars = Calendar.objects.all().filter( date_valid__gte=now.date(), calendar_master__group__cusopis=cal_group_param, ).order_by('date_valid') else: calendars = Calendar.objects.all().filter( date_valid__gte=now.date(), calendar_master__group__cusopis__icontains='default_group', ).order_by('date_valid') form = ZakaziForma() if request.method == 'POST': form = ZakaziForma(request.POST or None) if form.is_valid(): ... return redirect(success_page) context['cal_groups'] = cal_groups context['calendars'] = calendars context['form'] … -
how to Serve Pdf data from server to client. (Django)
I am working on a ebook reader app in which people can send pdf and get pdf content on more mobile read-friendly way. anyway to serve pdf data from server to client without disturbing images? for more info: i am using djnago rest framework. -
get_field_display() does not return string after saving it
Hereby my (simplified) situation. When I change a choicefield from one to the other, I want to record a message saying "Field changed from (previous) to (new)" In parenthesis I'd like the actual label of the field, so in case of the example below that should be "Field changed from Open to Completed". However, for some reason I am only able to generate "Field changed from Open to 2" I am baffled why this happens given that I use the exact same code. Any ideas? class Task(Record): class Status(models.IntegerChoices): OPEN = 1, "Open" COMPLETED = 2, "Completed" status = models.IntegerField(choices=Status.choices, db_index=True, default=1) Then in my views I try to do this: if request.POST["status"] == 2: description = "Status changed from " + info.get_status_display() + " → " # This works fine, returning "Status changed from Open → " info.status = request.POST.get("status_change") info.save() description = description + str(info.get_status_display()) # Yet for some reason this fails, and I end up with an integer (2)! even though I use the same syntax -
How to enable debugging in a particular app in Django
I want to enable Django debugging in a particular apps in the whole project because when the site is go to production if found something anything bug then I will fix by enabling the debug in the particular view in Django app without affecting the other modules Thank in advance. -
QuerySet for 3 Connected Model
I have a tree model for my ecommerce project. Want to show which product and how many waiting for packaging. I just want to show New Orders' product and quantities. For example: A product - 119 B product - 6 my model is: CHOICES = ( (1, _("New Orders")), (9, _("Canceled")), (10, _("Completed")), ) class Orders(models.Model): order_no = models.CharField(max_length=80) order_date = models.DateField(blank=True,null=True) order_status = models.IntegerField(choices=CHOICES, default=1) class Meta: verbose_name = "Order" verbose_name_plural = "Orders" ordering = ['order_date'] def __str__(self): return self.order_no class Products(models.Model): product_name = models.CharField(max_length=250,blank=True,null=True) barkod = models.CharField(max_length=60,blank=True,null=True) raf = models.CharField(max_length=15,blank=True,null=True) tax = models.DecimalField(blank=True,null=True, max_digits=5, decimal_places=0) class Meta: verbose_name = "Product" verbose_name_plural = "Products" ordering = ['pk'] def __str__(self): return self.product_name class OrderItems(models.Model): order = models.ForeignKey(Orders,on_delete=models.CASCADE,related_name='order') product = models.ForeignKey(Products,on_delete=models.PROTECT,related_name='product_order') quantity = models.CharField(max_length=6,blank=True,null=True) price = models.DecimalField(blank=True,null=True, max_digits=9, decimal_places=2) class Meta: verbose_name = "Item" verbose_name_plural = "Items" ordering = ['-pk'] def __str__(self): return self.order.order_no There is 3 model connected each other. I need the products in the New Orders and total quantity of them. I couldn't find the right way to do it. Is there a suggestion? -
django autocomplete light. Is there any tutorial for it with the post method?
Any help?! I'm trying to follow this tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html And I have many problems with it. One of my question would be... In my form I'm using POST method because I am posting queries in database... But this above tutorial seemingly using GET method... Is there any tutorial to for autocomplete light with the POST method, could you adjust this method to implement POST or autocomplete is not made for POST method. In the last scenario, which method for autocomplete of the search form better to use? -
Django formset errors show up in print but not in templates
When I print out the errors in the form_valid method the errors are shown, but in the template, the errors are not shown. What am I missing here? views.py class ParentManage(LoginRequiredMixin, UpdateView): login_url = reverse_lazy('login') model = Parent form_class = ParentManageForm slug_url_kwarg = 'parent_slug' template_name_suffix = '-manage' def get_object(self): return Parent.objects.get(slug=self.kwargs['parent_slug']) def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["children"] = ChildFormset(self.request.POST, instance=self.object) else: data["children"] = ChildFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() children = context["children"] self.object = form.save() if children.is_valid(): children.instance = self.object children.save() print(children.errors) print(children.non_form_errors) return super().form_valid(form) def get_success_url(self): parent = self.get_object() return reverse("parent-detail", kwargs={'parent_slug': parent.slug}) For the print statement when the POST request process, this is what I see in the shell: [{'__all__': ['Child with this Parent and Order already exists.']}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] <bound method BaseFormSet.non_form_errors of <django.forms.formsets.ChildFormFormSet object at 0x04F24040>> But it won't show up in the template. parent-manage.html: <div> <form method="post" action="{% url 'parent-manage' parent_slug=parent.slug %}"> {% csrf_token %} {{ form }} {{ children.management_form }} {% for dict in children.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor … -
What is the issue here?
python request get source code is different with actual source code. I am trying to web scrapping this web site "https://www.sundhed.dk/borger/guides/find-behandler/?Informationskategori=Psykolog" When I inspect it in the website it shows a different HTML code and when I use get.requests in pycharm and using soup when I print it, it is a different HTML code. Any idea why? ps : I am new to django -
How to execute django background tasks without command line?
I have checked out multiple other posts, but can't use the code I've seen circuling around (see below). I don't know where tasks is coming from on the last line: if not Task.objects.filter(verbose_name="update_orders").exists(): tasks.update_orders(repeat=300, verbose_name="update_orders") I want to be able to execute the function when it is called and only when it is called. So far when I run python manage.py runserver it runs the background tasks without having called them. Thank you. -
Django CSRF token missing or incorrect but CSFR has been added
Django give me the following error CSRF token missing or incorrect. but I don't find the issue. I have created my forms: class ModCollaboratoriForm(forms.ModelForm): class Meta: model = AltriCosti fields = "__all__" and my simple views.py: def collaboratori_commessa(request): collaboratori_commessa=AltriCosti.objects.all() if request.method == 'POST': form = ModCollaboratoriForm(request.POST) if form.is_valid(): print("Il form è valido") new_input = form.save() else : form = ModCollaboratoriForm() context={ 'form':form, 'collaboratori_commessa': collaboratori_commessa, } return render(request, 'commesse/collaboratori_commessa.html', context) And in my collaboratori_commessa.htm the following form: <form id="contact-form" name="contact-form" method="post" > {% csrf_token %} <div class="card card-outline card-info shadow "> <div class="card-header "> <h4 class="mb-0"> <img src="{% static 'icon/plus-circle.svg' %}"> Informazioni generali </h4> </div> <div class="card-body"> {{ form.media }} <div class="row"> <div class="form-group col-2 0 mb-0" > {{form.codice_commessa|as_crispy_field}} </div> ..... </div> <div class="card-footer"> <div class="col-md-2"> <button class="btn btn-info form-control" type="submit" onclick="submitForm()">Registra</button> </div> </div> </form> Why django give me the CSRF Error? -
How can I add custom button beside of add row in django tabularinline?
I want to add custom button and action beside of "add another [inline object]...". But I can't find where can I override the template or what python package can I use. I'm going to add "import" button to reset the standard data. Please help me. Thanks a lot. -
How to find connection between two uers in django rest?
I have one Follower system and here I want to check those are following to me,we have a mutual connection or not. If they are following to me and I'm not following to them, I want to set in frontend follow back. Inside the views, I'm fetching the data and sending them to serializer but I don't, How I can check it? My models and views are in below: models.py class Follow(models.Model): follower = models.ForeignKey(User,on_delete = models.CASCADE,related_name = 'following') followee = models.ForeignKey(User,on_delete = models.CASCADE,related_name = 'followers') created_at = models.DateTimeField(auto_now_add = True, null = True) updated_at = models.DateTimeField(auto_now = True, null = True) class Meta: unique_together = ("follower", "followee") ordering = ('-created_at',) views.py: class FollowerAPIView(APIView,PaginationHandlerMixin): pagination_class = BasicPagination serializer_class = UserFollowerSerializer def get(self,request,*args,**kwargs): follower_qs = Follow.objects.filter(followee = request.user).select_related('follower') page = self.paginate_queryset(follower_qs) if page is not None: serializer = self.get_paginated_response(self.serializer_class(page, many=True).data) else: serializer = self.serializer_class(follower_qs, many=True) return Response(serializer.data,status=status.HTTP_200_OK) -
Django - redefine Form Select using pk URL
I need to set input (select) value using pk sended by URL. Using init in form, almost get the answer, but init method is executed twice and clean my value. Form: class CrearDelitoForm(forms.ModelForm): class Meta: model = Delito exclude = () def __init__(self, numero_pk = None, *args, **kwargs): super(CrearDelitoForm, self).__init__(*args, **kwargs) self.fields["imputado"].queryset = Imputado.objects.filter(numero_id = numero_pk) DelitoFormset = inlineformset_factory( Expediente, Delito, form=CrearDelitoForm, extra=1, can_delete=True, fields=('imputado', 'delito', 'categoria'), } ) Views: class CrearDelito(CreateView): model = Delito form_class = CrearDelitoForm template_name = 'crear_delito.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['formset'] = DelitoFormset() context['expedientes'] = Expediente.objects.filter(id = self.kwargs['pk']) return context def get_form_kwargs(self, **kwargs): kwargs['numero_pk'] = self.kwargs['pk'] return kwargs ** System check identified no issues (0 silenced). June 08, 2020 - 11:33:57 Django version 2.2.12, using settings 'red.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. , ]> ** I think problem is on context = super().get_context_data(**kwargs) but don't know why. -
Django, how to handle fetch request
I'm working on a Django project that uses a flatbed scanner. Since scanning takes a long time I must work around getting a timeout error. After searching and trying multiple things I ended up with threading an a fetch call. How do I alter the fetch call to do what I want? I currently get send to a blank page that shows the dictionary that was returned by free_scan_crop. Please note that I am new to JavaScript. I just copied this bit of JS. What I would like to happen: A modal shows up when the form is submitted When the scanner is done: send user to home page and show message scan.html <div class="modal fade" id="scanDocument" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Scanning</h5> </div> <div class="modal-body"> Please wait... </div> </div> </div> </div> <script> formElem.onsubmit = async (e) => { e.preventDefault(); let response = await fetch("{% url 'core:free_scan' %}", { method: 'GET', body: new FormData(formElem) }); let result = await response.json(); alert(result.message); }; </script> views.py def free_scan_crop(request): form = FreeScanForm(request.GET) if form.is_valid(): file_name = form.cleaned_data['file_name'] # Grab the rest of the fields from the form... x = threading.Thread( target=scan_crop, args=(request, file_name, top_left_x, … -
passing 2D array from JavaScript template to Django web framework
I have a 2D array of values in JavaScript. How do I pass it to the Django framework to perform the operations without saving into the database? -
Django Database Connection
I am simply using Django for endpoints and don't want to use the Django functionality of connecting to databases. Instead, I want to connect to Postgresql and Redis database by creating it at time of starting server. One of the ways I did it was created these connection object in the django app init file and it works. But I don't thinks its the right way as I am not able to close the connection and also each time the server starts a new connection is created. Please help me out with the most efficient way of doing this task. I just need to create the connection to both Redis and postgresql by normal sqlalchemy command while starting server and then disconnect theses connections as soon as teh server stops or crashes. Something like finally block. -
schedule_task() argument after * must be an iterable, not int
Here I am using apply_async method with countdown and expires arguments to execute the task after some countdown and expires the task at certain datetime. But I got this error Django Version: 3.0.6 Exception Type: TypeError Exception Value: schedule_task() argument after * must be an iterable, not int How to solve this error ? tasks @periodic_task(run_every=crontab(minute=1), ignore_result=False) def schedule_task(pk): task = Task.objects.get(pk=pk) unique_id = str(uuid4()) views form = CreateTaskForm(request.POST) if form.is_valid(): unique_id = str(uuid4()) obj = form.save(commit=False) obj.created_by = request.user obj.unique_id = unique_id obj.status = 0 obj.save() form.save_m2m() # schedule_task.delay(obj.pk) schedule_task.apply_async((obj.pk),expires=datetime.datetime.now() + datetime.timedelta(minutes=5), countdown=int(obj.search_frequency)) return redirect('crawler:task-list') -
Reverse for 'openapi-schema' not found. 'openapi-schema' is not a valid view function or pattern name
I am trying to document my Django REST API with built-in methods. Here is the urls.py : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.views.generic.base import TemplateView from rest_framework.documentation import include_docs_urls urlpatterns = [ path('api/', include('api.urls')), path('admin/', admin.site.urls), path('', include('main.urls')), path('swagger-ui/', TemplateView.as_view( template_name='swagger-ui.html', extra_context={'schema_url': 'openapi-schema'} ), name='swagger-ui'), url(r'^.*', TemplateView.as_view(template_name="home.html")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) static/templates/swagger-ui.html : <html> <head> <title>Swagger</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout" }) </script> </body> </html> However I don't understand where should we allocate openapi-schema file? Is it .yml file or .js? And is there a way to generate it authomatically? -
Django - error message: IndentationError: unindent does not match any outer indentation level
enter image description here I'm having trouble solving this portion of my code. This is the model.py inside my app. The "image = models.ImageField(null=True, blank=True)" keeps giving me an error. I install Pillow library but didn't solve the problem from django.db import models from django.contrib.auth.models import User # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False,null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True, blank=False) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address -
How to pass selected row as DB table row value by clicking on button in Django page
function:- def reportposts(request): print("Hello i am from reportposts") query=request.GET.get('q') submitbutton= request.GET.get('submit') CountryID = request.GET.get('Country') print(query) print(submitbutton) print(CountryID) if request.method == 'GET': query=request.GET.get('q') submitbutton= request.GET.get('submit') CountryID = request.GET.get('Country') if query is not None: lookups= Q(id__icontains=query) | Q(name__icontains=query) results= Company.objects.filter(lookups).distinct() data = scraper(object_id=query, object_type='index', Country_ID=CountryID) context={'results': results,'models': json.dumps(data), 'submitbutton': submitbutton} return render(request, 'post/report.html') else: return render(request, 'post/report.html') Above code here is code that not able to receive anything from Django page. -
How to add the LIKE feature in a Django Blog?
enter image description hereI am adding a LIKE feature in my Twitter Clone builded with Django. I added this feature successfully but when I click on a like button only the recent post get liked. I created a model for post and one for likes and dislikes called Preference. Only the first post get liked when i click in the like buttons of other posts. How can i fix this? Below i have pasted the code of models, views and template. models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) def __str__(self): return self.content[:5] @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() class Preference(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) post= models.ForeignKey(Post, on_delete=models.CASCADE) value= models.IntegerField() date= models.DateTimeField(auto_now= True) def __str__(self): return str(self.user) + ':' + str(self.post) +':' + str(self.value) class Meta: unique_together = ("user", "post", "value") views.py @login_required def postpreference(request, postid, userpreference): if request.method == "POST": eachpost= get_object_or_404(Post, id=postid) obj='' valueobj='' try: obj= Preference.objects.get(user= request.user, post= eachpost) valueobj= obj.value valueobj= int(valueobj) userpreference= int(userpreference) if valueobj != userpreference: obj.delete() upref= Preference() upref.user= request.user upref.post= eachpost upref.value= userpreference if userpreference == 1 and valueobj != 1: eachpost.likes += 1 eachpost.dislikes -=1 elif userpreference == 2 and valueobj != 2: eachpost.dislikes … -
python/Django - Need to display filename first and contents of searched string in below for multiple file
views.py def sindex(request): search_path = "C:/AUTOMATE/STRING/TESTFILE/" file_type = ".txt" Sstringform = stringform() Scontext = {'Sstringform' : Sstringform} if request.method == 'POST': SVRFTEXT = Scontext['Enter_VRF_Name_To_Search'] = request.POST['Enter_VRF_Name_To_Search'] ftext = [] Scontext['resultlist'] = ftext for fname in os.listdir(path=search_path): fo = open(search_path + fname) fread = fo.readline() line_no = 1 while fread != '': fread = fo.readline() if SVRFTEXT in fread: ftext.append(fname + fread) line_no +=1 fo.close() return render(request, 'demoapp/VRFFILELIST.html', Scontext) VRFFILELIST.HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>VRF FILE LIST</title> </head> <body> <form method="POST"> {% csrf_token %} <table> {{Sstringform.as_table}} </table> <button type="submit">Send Command</button> </form> <table> <h3>VRF IN LIST OF FILES</h3> <textarea rows="25" cols="120" name="conf" form="conf" id="conf">{% for result in resultlist%}{{result}}{% endfor %}</textarea> </table> </body> </body> </html> managed to get output as below TEST-FILE-A.txt ip vrf forwarding TEST:VRFA TEST-FILE-A.txt ip vrf forwarding TEST:VRFA TEST-FILE-A.txt address-family ipv4 vrf TEST:VRFA TEST-FILE-A.txt neighbor 192.168.252.241 route-map TEST:VRFA-IN in TEST-FILE-A.txt neighbor 192.168.252.241 route-map TEST:VRFA-OUT out TEST-FILE-C.txt ip vrf forwarding TEST:VRFA TEST-FILE-C.txt neighbor 192.168.10.2 route-map TEST:VRFA-IN in TEST-FILE-C.txt neighbor 192.168.10.2 route-map TEST:VRFA-OUT out Required output as below TEST-FILE-A.txt ip vrf forwarding TEST:VRFA ip vrf forwarding TEST:VRFA address-family ipv4 vrf TEST:VRFA neighbor 192.168.252.241 route-map TEST:VRFA-IN in neighbor 192.168.252.241 route-map TEST:VRFA-OUT out TEST-FILE-C.txt ip vrf forwarding TEST:VRFA neighbor 192.168.10.2 route-map … -
Reverse for 'article-create' not found. 'article-create' is not a valid view function or pattern name
I started getting this error all of the sudden. I don't have any thing related to article-create in my urls.py or models.py or views.py After adding the below code: slug = models.SlugField(blank=True, default=False) and the below related i encountered this error. def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) urls.py shop/urls.py models.py -
How to fix the problem 'No module named myModule'
when start the service,as the command 'gunicorn -w 4 -b 0.0.0.0:8000 ApiWangYinParse:server', it shows the error log. plz look the code structure, what command I can start the python service. [2020-06-09 17:24:20 +0800] [28785] [INFO] Starting gunicorn 20.0.4 [2020-06-09 17:24:20 +0800] [28785] [INFO] Listening at: http://0.0.0.0:8000 (28785) [2020-06-09 17:24:20 +0800] [28785] [INFO] Using worker: sync [2020-06-09 17:24:20 +0800] [28788] [INFO] Booting worker with pid: 28788 [2020-06-09 17:24:20 +0800] [28789] [INFO] Booting worker with pid: 28789 [2020-06-09 17:24:20 +0800] [28788] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/signdraft2/ShenDuTool/API/ApiWangYinParse.py", …