Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models filter by foreignkey?
I want to make a big request. In this query, a field is taken from one table passing through 2 tables. How can I make a filter? paymentsss = Transaction.objects.select_related('currency', 'payment_source__payment_type', 'deal__service', 'deal__service__contractor').filter( payment_date__range=[date1, date2], payment_source__deal__service__contractor__name=contractor) .order_by('-id') As you can see, I'm trying to access the table contractor through deal, service and contractor. How can I make a filter? -
How to send HttpResponse Object
I am trying to call the view for my homepage but throw error when i click on the link to access the page I had tried several things code are given class Dashboard(LoginRequiredMixin, TemplateView): template_name='dashboard.html' # model=models.Account # context_object_name='account' login_url='login' def get(self,request): transaction=models.Transaction.objects.all() for trans in transaction: if trans.from_account == None: trans.delete() return render(request, 'dashboard.html', context = { 'selected_accounts':selected_accounts, }) ValueError at /account/dashboard/ The view accounts.views.Dashboard didn't return an HttpResponse object. It returned None instead. -
How can I populate a manytomanyfield , using view, without django pré-built forms?
I'm building a storage web system using django, I'm very newbie on the framework, so the problem is that, there is a bussiness rule, wich demands, two kinds of products, the inside products, and the finished ones. And the finished ones, always are composed by one or more inside products, I have the idea of using the manytomanyfields, but now, I don't really know how to extract this data , that should be a multiple choice, from the form and save in the database, does anyone has any tips or better ideas? Models.py class Produto(models.Model): codigo = models.CharField(max_length=254, null=True) produto_desc = models.CharField(max_length=200, null=False) tipo = models.CharField(max_length=2) qtd = models.IntegerField(null=True, default=0) created = models.DateTimeField(default=timezone.now, editable=False) last_updated = models.DateTimeField(default=timezone.now, editable=False) #Relationship Fields estrutura = models.ManyToManyField( 'storage.Produto', related_name="produto" ) def __str__(self): return self.produto_desc Views.py def CadastroProd(request): temp = 0 lista_produto = Produto.objects.order_by('id')[:20] for i in lista_produto: temp += 1 if request.method == 'POST': form = NovoProduto(request.POST) if form.is_valid(): obj = Produto() obj.save(commit=False) obj.codigo = form.cleaned_data['codigo'] obj.produto_desc = form.cleaned_data['produto_desc'] obj.tipo = form.cleaned_data['tipo'] # obj.estrutura = form.cleaned_data['estrutura'] obj.save() return HttpResponseRedirect('/storage/produtos') lista_produto = Produto.objects.order_by('id')[:20] lista_pi = Produto.objects.filter(tipo='PI') lista_pa = Produto.objects.filter(tipo='PA') context = {'lista_produto': lista_produto, 'temp': temp, 'lista_pi': lista_pi, 'lista_pa': lista_pa, } return render(request, 'storage/cadproduto/cadproduto.html', context) forms.py … -
Create number of fields based from choices
*I'm trying to figure out how to populate fields in my model based on previous field selection. For example, if FIELD_CHOICES = 3 Create 3x TextField() class Post(models.Model): STATUS_CHOICES = (('published','Published'), ('draft','Draft ')) FIELD_CHOICES = (('1','1 Title and body field'), ('2','2 Title and body fields'), ('3','3 Title and body fields'), ('4', '4 Title and body fields'), ('5', '5 Title and body fields')) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post') title = models.CharField(max_length=100) sub_title = models.TextField(max_length=50,default="") title_and_body_fields = models.IntegerField(choices=FIELD_CHOICES, default=1) **/// create number of title and body Textfields based on what was /// selected in title_and_body_fields** created = models.DateField() publish = models.DateTimeField(default=timezone.now) slug = models.SlugField(max_length=250, unique_for_date='created') status = models.CharField(max_length=250, choices=STATUS_CHOICES, default='draft') object = models.Manager() postManager = PostManager() class Meta(): ordering = ('publish',) def __strd__(self): return self.title def get_absolute_url(self): return reverse('my_blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) For example if FIELD_CHOICES = 3 create 3x TextFields() -
Django sign up view how to get the user from the user form to assign profile to the user
I have this sign up form where I am taking values from the user about his username and password and also his proile. I have separately created two forms UserForm and ProfileForm. When the user is signing up for his account how do I connect profile to the user. This is what I have forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, label='Email', error_messages={'exists': 'Oops'}) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(SignUpForm, self).save(commit=False) user.email = self.cleaned_data["email"] # user.status = self.cleaned_data["status"] if commit: user.save() return user class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['contact', 'whatsapp', 'gender', 'avatar'] models.py class Profile(models.Model): STATUS_CHOICES = ( (1, ("Permanent")), (2, ("Temporary")), (3, ("Contractor")), (4, ("Intern")) ) GENDER_CHOICES = ( (1, ("Male")), (2, ("Female")), (3, ("Not Specified")) ) PAY_CHOICES = ( (1, ("Fixed")), (2, ("Performance Based")), (3, ("Not Assigned")), ) user = models.OneToOneField(User, on_delete=models.CASCADE) emp_type = models.IntegerField(choices=STATUS_CHOICES, default=1) start_date = models.DateField(default=timezone.now) end_date = models.DateField(null=True, blank=True) user_active = models.BooleanField(default=True) contact = models.CharField(max_length=13, blank=True) whatsapp = models.CharField(max_length=13, blank=True) gender = models.IntegerField(choices=GENDER_CHOICES, default=3) pay_type = models.IntegerField(choices=PAY_CHOICES, default=3) pay = models.IntegerField(default=0) avatar = models.ImageField(upload_to='users/images', default='users/images/default.jpg') title = models.CharField(max_length=25, unique=False) #manager_username = models.ForeignKey(User, blank=True, null=True, to_field='username',related_name='manager_username', on_delete=models.DO_NOTHING) def __str__(self): return self.user.username … -
Error coming on the Local Server while logging in the Python and Django Application
I want my login.html page to hit first as a landing page in my Python and Django application. But an error is showing in urls.py file of the project on the server as soon as I am hitting the enter button after filling the username and password. Kindly help to solve the issue!! URLS.py File of the Project: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('tabs_app.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ] VIEWS.py file of the app in the project where index.html file is located: from django.shortcuts import render # Create your views here. def login(request): return render(request, 'login.html') URLS.py file of the app in the project where index.html file is located: from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login') ] VIEWS.py file of the app in which LOGIN code is written: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'invalid credentials') return redirect('login') … -
Heroku upload static folder not found
I was trying to reproduce the tutorial Django app and uploading it to Heroku server, but I can't resolve problems with static files. Here is a link to all files on github: https://github.com/Rufus90/poll.git When I try to run heroku run python manage.py collectstatic --noinput I get this error: Running python manage.py collectstatic --noinput on ⬢ hidden-plains-30510... up, run.1265 (Free) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 131, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/files/storage.py", line 315, in listdir for entry in os.scandir(path): FileNotFoundError: [Errno 2] No such file or directory: '/app/static' After completing the tutorial I have copied the whole repo, renamed it and changed the paths where I think it was needed. I was playing with my old project from … -
Caching table in django models
There is a remote database which is not always available and I need to store some of it's information in my app's model. I decided to use apscheduler to run a scheduled job which will try to connect to that database and update my model accordingly. The information is not changing very often so running a job, let's say, once a day would be enough. At the moment I decided to proceed like this: try to get new records from remote database get existing records from my local app's model compare these sets and define entities which are to be created, to be updated and to be deleted (based on specific_entity_id's value) perform bulk_create on those entities which are to be created perform bulk_update on those entities which are to be updated mark those entities which are to be deleted as to_be_deleted as there may be some foreign key constraints which I will handle later My model looks like this: class MyModel(models.Model): specific_entity_id = models.IntegerField() to_be_deleted = models.BooleanField() The table from remote database has some extra fields that I am not interested in. The number of records is not that great. I feel like there should be a better approach … -
How to display values from fields already chosen by user in UpdateView
So I've got a model and form: class CartItem(models.Model): user = models.ForeignKey('accounts.CustomUser', related_name='carts', on_delete=models.CASCADE, verbose_name='User') product = models.ForeignKey('pizza.Product', related_name='carts', on_delete=models.CASCADE, verbose_name=_('Product')) quantity = models.SmallIntegerField(verbose_name=_('Quantity')) def __str__(self): return f'{self.quantity} of {self.product}' class CartItemForm(forms.ModelForm): product_types = forms.ModelChoiceField(queryset=ProductType.objects.none(), required=False) product_sizes = forms.ModelChoiceField(queryset=Size.objects.none(), required=False) product_names = forms.ChoiceField(choices=[('', '---------')]) class Meta: model = CartItem fields = ['product_types', 'product_names', 'product_sizes', 'quantity'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) self.product_type = kwargs.pop('product_type', None) self.product_names_query = Product.objects.filter(type__name__contains=self.product_type).values_list( 'name', flat=True).distinct() self.product_names_choices = [('', '---------')] + [(name, name) for name in self.product_names_query] super().__init__(*args, **kwargs) def save(self, commit=True): product = Product.objects.get(name=self.cleaned_data.get('product_names'), type=self.cleaned_data.get( 'product_types'), size=self.cleaned_data.get('product_sizes')) user_product = CartItem.objects.create(user_id=self.request.user.id, `product=product, quantity=self.cleaned_data.get('quantity'))` My HTML form looks like this: > <form method="POST" action="{% url 'pizza_order' %}"> > {% csrf_token %} > <div> > <label for="id_product_types"><b>Choose pizza type:</b></label> > {{ form.product_types }} > </div> > <div> > <label for="id_product_names"><b>Choose amount of toppings:</b></label> > {{ form.product_names }} > </div> > <div id="toppings__checkboxes"> > <label for="id_toppings" id="toppings__label"></label><br> > {% for checkbox in form.toppings %} > <span class="toppings--checkbox">{{ checkbox.tag }} {{ checkbox.choice_label }}</span> > {% endfor %} > </div> > <div> > <label for="id_product_sizes"><b>Choose size:</b></label> > {{ form.product_sizes }} > </div> > <div> > <label for="id_quantity"><b>Quantity:</b></label> > {{ form.quantity }} > </div> > <div class="price"></div> > <div><input type="submit" … -
how to filter the objects in django? using OR and AND
salary_band = request.POST['salary_band'] decipline = request.POST['decipline'] role = request.POST['role'] find_role = Role.objects.filter(role = role) find_decipline = Decipline.objects.filter(name = decipline) find_sal_band = SalaryBand.objects.filter(sequencenter code heree_number = int(salary_band), role = find_role, decipline = find_decipline).exists() -
I Want To Save image in folder using django but i get this error
I Want To Save image in folder using django but i get this error: MultiValueDictKeyError at /lunchpk/signup/ i need to fix any help will be appreciated i also see more questions but i don't get correct answer so please answer my question don't add it to duplicate here's my views.py def signup(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = NewForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'Profile_Image' in request.FILES: profile.Profile_Image = request.FILES['profile_pics'] # profile.Dish_Image = request.FILES['Dish_pic'] profile.save() registered = True else: print(user_form.errors,profile_form.errors) else: user_form = UserForm() profile_form = NewForm() return render(request,'html/signup.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered}) Here is my model.py class UserInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) Profile_Image = models.ImageField(upload_to='profile_pics',null=True, blank=True) Dish_Image = models.ImageField(upload_to='Dish_pic',null=True, blank=True) Dish_Name = models.CharField(max_length=10,) def __str__(self): return self.user.username here is my forms.py from django import forms from django.contrib.auth.models import User from .models import * class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ('username','email','password') class NewForm(forms.ModelForm): class Meta: model = UserInfo fields = ('Profile_Image','Dish_Image','Dish_Name') -
Filter posts based on category
I'm new in django and generally in programming. And now I write my first project - that will be my personal blog, it's almost done except one feature: I have list of categories shown on the page in the right panel. 1) The question is how can I sort/filter my posts by these categories? I mean I want to click on one of these categories in the right panel and to see the posts where that category is mentioned (post may have several categories). I've tried a lot of combinations, which found on stackoverflow, but I didn't do that before so can't understand how to realize that feature in my project. models.py class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField('Content') author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.title views.py def filter_by_category(request): post_list = Post.objects.filter(categories=) context = { 'post_list': post_list } return render(request, 'post_by_category.html', context) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog, name='post-list'), path('search/', search, name='search'), path('blog/filter_by_category/', filter_by_category, name='filter_by_category'), path('subscribe/', … -
Django, forward form data using email, after submitting it to database
im new to django so i apologize in advance. I've successfully created a webform that submits everything successfully to a database and also successfully emails a designated adress upon form submission. now that everything is working I would like to add the content that is being submitted into that same email that is being sent out on submit. send_email seemingly only takes strings and render_to_string doesnt work for me on my form. is there an easy way to get the data being submitted into a readable format and pass it into the content of the email being sent? def snippet_detail(request): if request.method == 'POST': form = SnippetForm(request.POST) if form.is_valid(): form.save() send_mail('Form submitted', 'test', settings.EMAIL_HOST_USER, ['email@email.com'], fail_silently = False) return render(request, 'submittedformsuccess.html') Everything here works I simply wanna replace 'test' with for example a copy of the template form.html that the user sees, but completely filled in -
how to send a query set throw the super method?
i'm trying to send the log attribute to the super get function and list all the logs although i want the filter works on BasicQUserSerializer the how can i do this ? this is my viewsets class CustomerLogView(generics.ListAPIView): permission_classes = (AllowAny,) queryset = QUser.objects.all() serializer_class = BasicQUserSerializer filter_backends = [OrderingFilter] pagination_class = AdvancedPagination def get(self, request, *args, **kwargs): account = get_object_or_404(Account, pk=kwargs['pk']) log =CustomerLogSerializer(LogEntry.objects.filter(account=account), many=True).data return super().get(request, *args, **kwargs,) this is my Serializer class CustomerLogSerializer(serializers.ModelSerializer): actor = BasicQUserSerializer() class Meta: model = LogEntry fields = ('id', 'actor', 'account', 'changes', 'remote_addr', 'additional_data','timestamp') -
How to test an api that accesses an external service?
I am creating an application that receives some parameters and sends an email using a company server, when I do the test using postman it works, but using the same parameters to perform a test happens an error and I can't debug, only 500 error appears, can i see the test django server log? urls.py urlpatterns = [ path('modules/email/send', views_email.email_send.as_view(), name='email_send'), ] views_email.py class email_send(APIView): permission_classes = (IsAuthenticated,) def post(self, request): # ver anexo e como carregar os componentes try: body = json.loads(request.body.decode('utf-8')) fromaddr = body.get("from") to = body.get("to") cc = body.get("cc") subject = body.get("subject") level = body.get("level") level_color = body.get("level_color") alert_name = body.get("alert_name") body_html = body.get('body_html') #Arquivos html index_file = body.get("index_file") header_file = body.get("header_file") footer_file = body.get("footer_file") # body_file = body.get("body_file") message = MIMEMultipart("alternative") message["Subject"] = subject message["From"] = fromaddr message["To"] = to message["CC"] = cc .... part1 = MIMEText(text, "plain") part2 = MIMEText(html_string, "html") message.attach(part1) message.attach(part2) server = smtplib.SMTP('srvsmtp1.santander.com.br', 25) response = server.sendmail(fromaddr, toaddr, message.as_string()) if response == {}: response = 200 else: pass return Response(response, content_type="text/plain", status=status.HTTP_200_OK) except Exception as e: return Response(str(e), content_type="text/plain", status=status.HTTP_400_BAD_REQUEST) test_urls.py from rest_framework.test import RequestsClient from rest_framework.authtoken.models import Token import requests client = RequestsClient() token = Token.objects.get(user__username='admin') class EmailSendTest(TestCase): def test_email_send(self): headers … -
Django: Ajax Foreign Key's Add with popup
I use Django == 2.2.3 Postgres lasted version And chrome for browser However, I use this tutorial Ok ! I'm trying to reproduce some functionality of the Django administration interface in my own frontend application. So I have models that I create using a modal. Except that for linked models I invoke a popup if the linked model does not exist and I create it in the popup. The models are created normally and saved in the database. The main problem is that when the popup closes the new item created is not selected, let alone in the list of objects available in my selection Examle with image: Firstly i pushed link When i get the modal i click on add button I get first popup Inside my popup i push another + button to add element if not exist After Submitting inside another popup my select is not update: Example views: def coverage_popup_cru(request, insurance_id, coverage_id=None): """ This view is used to create and update coverage :param request: current request object :param insurance_id: Insurance primary key :param coverage_id: coverage primary key or None if create new :return: HttResponse... """ update = False instance = None get_insurance = get_object_or_404(InsuranceModel, pk=insurance_id) if … -
Where does the base_fields dictionary in django ManagementForm class come from?
I'm trying to improve my understanding of using forms in django and looking at the docs I'm confused of where the base_fields dictionary comes from in ManagementForm class?Hope someone can help me understand. Initially I thought its passed in by some other method but I cant seem to find which one. class ManagementForm(Form): """ Keep track of how many form instances are displayed on the page. If adding new forms via JavaScript, you should increment the count field of this form as well. """ def __init__(self, *args, **kwargs): self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput) self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput) Source code: https://docs.djangoproject.com/en/2.2/_modules/django/forms/formsets/#BaseFormSet -
use image in html from database using django
when i try display image from my database to html it's won't to show but all rest data are display ! so what is the error ? my code model : class Homepage(models.Model): name = models.CharField(max_length=50,default="") app_contect = models.CharField(max_length=240,default="") page_url = models.URLField(max_length=250,default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) def __str__(self): return self.name views.py : def home_page(request): app = Homepage.objects.all() page = request.GET.get('the_home_page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: appnum = paginator.page(page) except PageNotAnInteger: appnum = paginator.page(1) except EmptyPage: appnum = paginator.page(paginator.num_pages) return render(request,'html_file/enterface.html', { 'appnum': appnum }) Html file : {% for home_page in appnum %} <label id="label_main_app"> <img id="img_main_app_first_screen" src="{{ home_page.app_image }}" alt="no image found !" height="160" width="165" > {{ home_page.name }} <br><br> <p id="p_size_first_page"> {{ home_page.app_contect}} <br> <br> <a href=" {{ home_page.page_url }} " type="button" class="btn btn-primary"><big> See More & Download </big> </a> </p> </label> {% endfor %} any help please ? -
Start two http servers in Django
I have working application on port 8080(Django 1.6). It binds to external network interface. I would like to add one more http listener inside my Django app. E.G. one more http server on port 8000, and bind it to internal network interface only. Is it possible in Django? -
HTML CSS Design: Bootstrap UI-KIT with bootstrap-sidebar
I'm trying to Design a simple Django Web App I've written by myself. But I absolutely don't know how to design it like a want. HTML and CSS are like Word if you try to put in a simple image and that'll destroy your whole layout and design of the Word File. I'm Using this HTML Template: https://colorlib.com/wp/template/tools-ui-kit/ DEMO: https://colorlib.com/preview/theme/tools/ And I'm using this Sidebar: https://bootstrapious.com/p/bootstrap-sidebar#further-improvements I've painted a Screenshot so you could see what I want to archive and the current behavior: The <script> Parts and the <link> Parts that includes all the Scripts and CSS Files is included in the base_generic.html that is part of every other html file. This is my CSS File: .sidebar-nav { margin-top: 20px; padding: 0; list-style: none; } table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #DDDDDD; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #DDDDDD; } #sidebarCollapse { width: 40px; height: 40px; background: #f5f5f5; } #sidebarCollapse span { width: 80%; height: 2px; margin: 0 auto; display: block; background: #555; transition: all 0.8s cubic-bezier(0.810, -0.330, 0.345, 1.375); } #sidebarCollapse span:first-of-type { /* rotate first one */ transform: rotate(45deg) translate(2px, 2px); } #sidebarCollapse span:nth-of-type(2) { /* second one is … -
which implementation is better for endpoints?
i'm developing an api server with drf. one of our abilities must be finalizing the purchase. for this, there are some actions to be done. for example calculating final price considering some parameters effective on available discount,creating new row for some tables and finally send sms to the customer. all above can be done at one endpoint named finalize_purchase(for example). i think it's not good choice because of REST api concept but easy for client app to use. but another way is separating each section of process and let client app to use them. for example first client have to call an endpoint to calculating discount and final price, then calling an endpoint to sending sms to the customer.this is based on REST principles and CRUD.but it's not easy for client to calling multiple endpoints just for one action. so which way is correct according to the REST api principles? -
Django-cors-headers not working on live server
I'm working with djangorestframework and everything works fine on the local test and live server, But when I put the configuration for cors management using django-cors-headers package the applications works on test server fine but on the live server(Apache2) it doesn't work and throws the following Exception: mod_wsgi (pid=25506): Target WSGI script '/var/www/python3-projects/www.mywebsite.com/api/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=25506): Exception occurred processing WSGI script '/var/www/python3-projects/www.mywebsite.com/api/wsgi.py'. Traceback (most recent call last): File "/var/www/python3-projects/www.mywebsite.com/api/wsgi.py", line 16, in application = get_wsgi_application() File "/var/www/python3-projects/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/python3-projects/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/python3-projects/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant Here is my configuration for django-cors-headers: INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_WHITELIST = [ 'http://localhost', 'http://www.mywebsite.com', ] -
Run power-shell script from Django project
I have a Django application deployed in IIS server, this application runs some power-shell scripts. My power-shell scripts are stored in a deployment server. i can run all the power-shell scripts from my Django application when i am connected to the server using the remote computer, (the server is an RDP). But when i am disconnected from the server, my Django application can't run the power-shell scripts. this is the code than i am using in my view while running the script : Invoke-Command -ComputerName comptuer "-ScriptBlock { myscript.ps1 -SITE $args[0]} -
Using a single Microsoft authentication in frontend with Angular and in backend with Django REST API
I have recently made a working Django app which uses resources from MS Graph, where users authenticate in the same fashion as this tutorial's. I was then required to separate frontend, using Angular, and convert my Django app into a REST framework. I managed to set up frontend authentication in Angular as taught here. My question is: how can I use the token that was acquired in frontend to authenticate app's requests to my Django REST API, in order that the backend can also use it for its own queries to MS Graph API? Thank you guys in advance. -
Displaying Apliction error while deploying website app using django to heroku
I created a movie review website using Python-Django I tried to make it live using Heroku but while opening there it is Showing Application Error in Heroku. My app runs fine locally. Steps I followed to Install Heroku $sudo snap install --classic Heroku $heroku login And then run the following $pipenv lock $touch Procfile Add the following line in wsgi file : " web:gunicorn pages_project.wsgi --log-file -" $pipenv install gunicorn==19.9.0 Changes in the settings.py project/settings.py ALLOWED_HOSTS = ['*'] $heroku create $heroku git:remote -a xxx-yyy-26076 $heroku config:set DISABLE_COLLECTSTATIC=1 $git push heroku master $heroku ps:scale web=1 $heroku open Here is my code on Github. Here is my Website link--> https://fast-island-20902.herokuapp.com/