Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass multiple variables or context dictionary to context processors in Django?
I have a view called shopcart() which has multiple variables. Here's the code: def shopcart(request): category = Category.objects.all() current_user = request.user # Access User Session information shopcart = ShopCart.objects.filter(user_id=current_user.id) total=0 tax = 0 grand_total = 0 for i in shopcart: total += i.variant.price * i.quantity url = request.build_absolute_uri() domain = urlparse(url).netloc biz_id = Business.objects.get(domain_name=domain) get_tax = Tax.objects.get(business__business_id=biz_id.business_id) tax_percent = get_tax.tax_percentage tax = round((tax_percent * total)/100, 2) grand_total = round(total + tax, 2) context={'shopcart': shopcart, 'category':category, 'total': total, 'tax_percent': tax_percent, 'tax': tax, 'grand_total': grand_total, } return render(request,'shop/cart.html', context) Currently, it is sending context dictionary to only one template i.e 'shop/cart.html'. But, I want to access all the variables of this context in all the templates. I know the context processors are used to make the variables available in all templates, but not sure how to properly do it in my situation. Can anybody help me. Thanks. -
I am running into an error with an npm command in react. "ERROR in main Module not found: Error: Can't resolve ..."
I have been following a django-react tutorial and ran into a problem with the command npm run dev. I thought it was a problem with the webpack file but maybe not. [error message][1] [webpack file][2] [package.json][3] [file structure and app.js][4] [index.js][5] This is the error that I am receiving: [1]: https://i.stack.imgur.com/vCK8g.png (django_venv) C:\Users\bostm\Documents\CodingProjects\React-Django \music_controller\frontend>npm run dev > frontend@1.0.0 dev > webpack --mode development --watch [webpack-cli] Compilation starting... [webpack-cli] Compilation finished asset main.js 0 bytes [compared for emit] [minimized] (name: main) ERROR in main Module not found: Error: Can't resolve './src/index.js' in 'C:\Users\bostm \Documents\CodingProjects\React-Django\music_controller\frontend' webpack 5.10.2 compiled with 1 error in 136 ms [webpack-cli] watching files for updates... This is the webpack file. I assumed the problem was here because the error message said that it couldn't resolve "./src/index.js" in the path to the frontend directory, which is the name of the webapp folder that src/index is in. I tried using a solution from another post by using path.resolve(__dirname, /path/). It did not work so this is what I had originally. [2] const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: … -
Django input forms not showing up in my template
My problem is that when I go to my add.html page the input forms for title and textarea do not show up. For context, this is for an online course where I have to design a "wiki". This section of code is for adding an entry (a title and body content) Here is my code: views.py def create(request): if request.method == "POST": form = Form(request.POST) if form.is_valid(): title = form.cleaned_data["title"] textarea = form.cleaned_data["textarea"] entries = util.list_entries() if title in entries: return render(request, "encyclopedia/error.html") else: util.save_entry(title, textarea) page = util.get_entry(title) page_converted = markdowner.convert(page) context = dict(body=page_converted, title=title) return render(request, "encyclopedia/entry.html", context) else: return render(request, "encyclopedia/create.html", { "post": Form() }) add.html {% extends "encyclopedia/layout.html" %} {% block body %} <h1> Add Post </h1> <form action="{% url 'create' %}" method="post"> {% csrf_token %} <h6 class="post-title">Title: {{ post.title }}</h6> {{ post.textarea }} <input type="submit" value="add entry"> </form> <a href="{% url 'index' %}">View Entries</a> {% endblock %} -
django: I accidentally deleted the manage.py file. how to recover it?
I accidentally deleted the manage.py file with vim nerdtree. apparently, there isn't a way to recover it I I don't know what the hell to do. can I somehow create a new one or restore it? -
Is possible group nested objects from the same queryset?
I have a Viewset that looks like this: class EstadisticasEquipoViewSet(viewsets.ModelViewSet): """ Trae estadísticas totales de todos los equipos de una zona en una respectiva liga. """ serializer_class = EstadisticaEquiposSerializer def get_queryset(self): queryset = Estadistica_Equipo_Partido.objects.filter(id_partido__id_zona=self.request.query_params.get('id_zona')).values('id_equipo').annotate( ... tot_puntos=Sum('puntos'), prom_puntos=Avg('puntos'), prom_q1=Avg('q1'), prom_q2=Avg('q2'), prom_q3=Avg('q3'), prom_q4=Avg('q4'), tot_tiros_campo_convertidos=Sum('tiros_campo_convertidos'), prom_tiros_campo_convertidos=Avg('tiros_campo_convertidos'), ... ).annotate( ... prom_pts_poss=F('tot_puntos') / F('tot_poss'), prom_eficiencia_tiro_campo=(F('tot_tiros_campo_convertidos') + 0.5 * F('tot_tiros_3_convertidos')) / F('tot_tiros_campo_intentados') * 100, prom_true_shooting=(F('tot_puntos') / (2*(F('tot_tiros_campo_intentados') + 0.44*F('tot_tiros_tl_intentados')))) * 100, prom_eficiencia_ofensiva=(F('tot_puntos') / F('tot_poss')) * 100, prom_eficiencia_defensiva=Avg('eficiencia_defensiva'), ... ) return queryset How can I group annotate fields in this groups: promedios -> all fields that starts with prom totales -> all fields that starts with tot Actually i've this serializer: class EstadisticaEquiposSerializer(serializers.ModelSerializer): ... tot_puntos = serializers.IntegerField() prom_puntos = serializers.FloatField() tot_tiros_campo_convertidos = serializers.IntegerField() prom_tiros_campo_convertidos = serializers.FloatField() tot_tiros_campo_intentados = serializers.IntegerField() prom_tiros_campo_intentados = serializers.FloatField() porc_tiros_campo = serializers.FloatField() ... class Meta: model = Estadistica_Equipo_Partido fields = (... 'tot_puntos', 'prom_puntos', 'tot_tiros_campo_convertidos', 'prom_tiros_campo_convertidos', 'tot_tiros_campo_intentados', 'prom_tiros_campo_intentados', 'porc_tiros_campo', ... ) -
Django two same signal types
I don't understand how 2 signals executed together relate to each other. For example consider the following: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' # Overriding save method-image resizing def save(self, **kwargs): super().save(kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) # save() of parent class #Signals when a user is registered his profile is automatically updated @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile(user=instance) #could do Profile.objects.create(user=instance) instead to replace the 2 lines instance.profile.save() #reverse query I understand the following: create_profile: is my receiver function. It will do something when .save() method takes place, in our case will create a Profile instance and save it. sender: is the Model that is actually signalling this to take place. So in our case, if we want a signal to take place when the save method is executed on User model then the sender would be the User. post_save is the signal Regarding my question now. I have seen the above function broken … -
408 Request Timeout Using Apache + mod_wsgi + Python Django in Windows
I have a Django app which is deployed in local network using Apache + mod_wsgi under Windows. When I run python manage.py runserver, everything works fine. But when I start the Apache Service, I cannot access the app. The only response I get from the access.log is the error code 408. Below is my httpd.conf: LoadFile "c:/users/felix/appdata/local/programs/python/python37/python37.dll" LoadModule wsgi_module "c:/users/felix/appdata/local/programs/python/python37/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd" WSGIPythonHome "c:/users/felix/appdata/local/programs/python/python37" ServerName localhost WSGIScriptAlias / "D:/dev/test_server/django/django/wsgi_windows.py" Listen 8000 <VirtualHost *:8000> WSGIPassAuthorization On ErrorLog "logs/django.error.log" CustomLog "logs/django.access.log" combined Alias /static "D:/dev/test_server/staticfiles" <Directory "D:/dev/test_server/staticfiles"> Require all granted </Directory> <Directory "D:/dev/test_server/django/django"> <Files wsgi_windows.py> Require all granted </Files> </Directory> <Directory /> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> </VirtualHost> And below is the wsgi_windows.py file: # Activate the virtualenv activate_this = 'D:/dev/test_server/.venv/Scripts/activate_this.py' exec(open(activate_this).read(), dict(__file__=activate_this)) import os # noqa import sys # noqa import site # noqa # Add the site-packages of the chosen virtualenv to work with site.addsitedir('D:/dev/test_server/.venv/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('D:/dev/test_server/django') sys.path.append('D:/dev/test_server/django/django') os.environ['DJANGO_SETTINGS_MODULE'] = 'django.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django.settings") from django.core.wsgi import get_wsgi_application # noqa application = get_wsgi_application() I'd appreciate any ideas or hints on the issue. -
Django key error "request" when using inlineformset
I created an Class Based(CreateView) with in inlineformset. I need to pass the request.user to the form to enable a filter finction on one of the form fields. I however get a Key Error: request on the line: self.request = kwargs.pop('request') in the def init(self, *args, **kwargs): of the form. Assistance will be appreciated. Tips on my programming is also welcome. models.py: class ttransactions(models.Model): transaction_type = models.CharField(max_length=10, choices=tx_choices) description = models.CharField(max_length=50, null=False, blank=False, default='Description') transaction_date = models.DateField(default=datetime.today, db_index=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT, db_index=True) def __str__(self): return self.description class ttransaction_lines(models.Model): transaction = models.ForeignKey(ttransactions, on_delete=models.CASCADE, db_index=True) sequence = models.IntegerField() transaction_type = models.CharField(max_length=6, choices=debit_credit) ledger_account = models.ForeignKey(tledger_account, on_delete=models.PROTECT, db_index=True) amount = models.DecimalField(max_digits=14, decimal_places=2, default=0.0) quantity = models.IntegerField(blank=True, null=True) posted = models.BooleanField(default=True) forms.py: class TransactionLinesForm(forms.ModelForm): class Meta: model = ttransaction_lines fields = ['transaction_type', 'ledger_account', 'amount'] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(TransactionLinesForm, self).__init__(*args, **kwargs) user = self.request.user current_company = user.current_company self.fields['ledger_account'].queryset = tledger_account.objects.filter( company=current_company) TransactionLineFormset = inlineformset_factory(ttransactions, ttransaction_lines, # fields=['transaction_type', 'ledger_account', 'amount'] , form=TransactionLinesForm, can_order=True, can_delete=True) views.py: class JournalCreateView(LoginRequiredMixin, CreateView): template_name = 'accounting/journal.html' model = ttransactions transaction_lines_form = TransactionLinesForm form_class = TransactionLinesForm success_url = '/accounting/transaction_list' def get_form_kwargs(self): kwargs = super(JournalCreateView, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def get(self, request, *args, **kwargs): self.object = … -
django 3.1 user not staying logged in
So, I have a django 3.1 project and a Foo app that is going to have a user login, but I am running into the problem where users will not retain a logged in status after any additional requests. the code is similar to that below, but pretend that all relevant imports are made that are otherwise absent. views.py from django.shortcuts import render from django.contrib import auth from django.http import HttpResponseRedirect def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) if request.user.is_authenticated: return HttpResponseRedirect(reverse("Foo:stays_loggedin_check")) return render(request, template_name="Foo/loginfailed.html") return render(request, template_name="Foo/login.html") def stays_loggedin_check(request): if request.user.is_authenticated: return render(request, template_name="Foo/staysloggedin.html") return render(request, template_name="Foo/weirdly_doesnt_stay_logged_in_despite_documentaion.html") urls.py from django.urls import path from . import views app_name = "Foo" urlpatterns = [ path("login", views.login, name="login"), path("shouldnt_need_to_do_this", views.stays_loggedin_check, name="stays_loggedin_check"), ] When one fills out the login form at Foo/login.html incorrectly it, as expected, renders the page Foo/loginfailed.html. but when filled out correctly this form returns Foo/weirdly_doesnt_stay_logged_in_despite_documentaion.html. Is there a way to model behavior to be in line with django documentation where this will return Foo/staysloggedin.html instead? -
Django Class Base Views - muti model query
I am trying to create a class-based view that needs to query two models and render a joined context. Can someone please suggest how to achieve it in CBV? Example: Models: class model1(models.Model): number= models.CharField(max_length=16, null=True) location= models.CharField(max_length=64, null=True) status = models.CharField(max_length=64, null=True) class model2(models.Model): macaddress = models.CharField(max_length=64) unitnumber= models.CharField(max_length=64) device_number= models.ForeignKey(model1, default=1) How to create a class base view that will return a context which I can render to display all the 5 different fields of the two tables, mapped by 'number' filed indeed. -
How to disable a particular link after used once?
Here Admin invites the user by the email, firstname, lastname and username. After user saved with (is_active=False), a link will be send to the user email address. After clicking the link user will be redirected to a view where the user can set a new password for them. What I want is, the url which will be used to set a new password should not be valid once a user sets a new password. Right now when the user sets a new password through a url, user can use the same url to reset the password again. I want to invalid this url once a user sets a new password. OR what another approach will be better in this case while inviting a new user ? urls path('set/<uidb64>/<new_token>/password/', views.set_user_password, name='set_user_password'), path('confirm/user/<uidb64>/<token>/', views.activate_account, name="activate_user"), views class AddUser(View): template = 'user/add_user.html' form = AddUserForm def get(self, request): return render(request, self.template, {'form': self.form()}) def post(self, request): form = self.form(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() # sending email subject = "New User Invitation" context = { 'user': user, 'domain': get_current_site(request).domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user=user), } message = render_to_string('user/user_invitation_email.html', context) send_email.delay(subject, message, settings.EMAIL_HOST_USER, user.email) return redirect('dashboard:users_list') return render(request, self.template, {'form': form}) … -
Django override the error message that Django shows for UniqueConstraint error?
I want to customize Meta class constraints default message. Here is my model that I have been working out. class BusRoute(BaseModel): route = models.ForeignKey(Route, on_delete=models.PROTECT) shift = models.ForeignKey( Shift, null=True, on_delete=models.PROTECT ) journey_length = models.TimeField(null=True) class Meta: default_permissions = () verbose_name = 'Bus Route' verbose_name_plural = 'Bus Routes' constraints = [ models.UniqueConstraint( fields=['route', 'shift'], name='unique_bus_company_route' ) ] The default constraint error message is as following Bus Route with this Shift already exists. Is there any way out I can customize this constraint message to something like, Bus Route and shift already in use please validate again -
Why my serializer field does not show up?
Right now i have no problem with showing the output of the fields.But somehow i can't see the output of postlikes_set in json output. I don't get any error or something,i just can't see it. I don't know why. Does anybody know the issue? Here are my codes. Model class LikePostModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, unique=True, on_delete=models.CASCADE,related_name='postlikes',null=True) article = models.ForeignKey(Article, on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) Serializer class LikePostViewSerializer(serializers.ModelSerializer): class Meta: model = LikePostModel fields = ('id',"author","article") class ArticleViewSerializer(serializers.ModelSerializer): images_set = ArticleImageViewSerializer(source='images',required=False,many=True) comments_set = CommentViewSerializer(source='comments',required=False,many=True) postlikes_set = LikePostViewSerializer(source='postlikes',required=False,many=True) class Meta: model = Article fields = ('id','caption','images_set','comments_set','postlikes_set') def create(self, validated_data): return Article.objects.create(**validated_data) Output [ { "id": "092e929f-c845-403d-8373-84c745140c11", "caption": "caption", "images_set": [], "comments_set": [] } ] -
Django - Grouping data and showing the foreignkey's name in template
I am triying to create a pie chart(chart.js). My goal is grouping departments and displaying how many people work by departments in piechart. Models.py class Personel(models.Model): name = models.CharField(max_length=30) surName = models.CharField(max_length=20) department = models.ForeignKey(DepartmentList, on_delete=models.SET_DEFAULT, default=0, related_name="PersonelDepartman") def __str__(self): return f"{self.name},{self.surName}" class Meta: db_table = "personel" verbose_name_plural = "Ar-Ge Personeller" class DepartmentList(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: db_table = "DepartmentList" verbose_name_plural = "Departman Listesi" Views.py def index(request): personel_dep = Personel.objects.values('department').annotate(Count('department')) context = { "personel_dep" : personel_dep, } return render(request, 'core/index.html',context) personel_dep returns=><QuerySet [{'department': 1, 'department__count': 5}, {'department': 2, 'department__count': 5}, {'department': 3, 'department__count': 3}, {'department': 4, 'department__count': 3}, {'department': 5, 'department__count': 3}, {'department': 6, 'department__count': 4}, {'department': 7, 'department__count': 1}]> It is okay for me and all i need is in here. But I coulnd't figure out how i can display department's name in my template(also in chart label) Template {% for dep in personel_dep %}<p>{{ dep.department }}</p>{% endfor %} What am i missing? In these case is there any way to display departmant name or easy way to display name of departments in chart label? -
Django background tasks wait for result
I am trying to run a some machine learning computation task in the background due to heroku's 30 seconds timeout. I was trying to implement django-background-tasks. here's my code: def process_data(request): symbol = request.GET.get('symbol') data = test1.now(symbol) print(data) return JsonResponse(data, safe=False) @background(schedule=0) def test1(symbol): symbol = symbol+'ksksk' #long running machine learning stuff return symbol I displaying a loading screen while i wait for the computations to be completed and then return the data using jsonresponse. But when i print the data it show of type instead of the data i need: <class 'background_task.models.Task'> how do i get the data which i have computed in the background to the original view so that i can display the output? -
Django - I want to sort a previous query and not the entire model
I have two view functions: home_view - filters the database and renders the output in list.html display_view - sorts the page by date or price My PROBLEM: display_view sorts all the model and not only the output of home_view. Maybe I have to change the display_view: obj = Model.objects.all() ---> obj = home_view.obj How can I do this? def display_view(request): obj = Model.objects.all() myFilter = SortFilter(request.GET, queryset=obj) obj = myFilter.qs context = { 'objects': obj, 'myFilter': myFilter } return render(request, "list.html", context) def home_view(request): obj = Model.objects.all() myFilter = SortFilter(request.GET, queryset=obj) obj = myFilter.qs context = { 'objects': obj, 'myFilter': myFilter } return render(request, "home.html", context) -
How to toggle a wishlist button with an Ajax function in Django
So I have run into a bug that is just driving me crazy. When you open my webpage, a list of jobs are provided which have a small heart shaped wishlist icon next to them. Normally, if the job is part of your wishlist it should appear as a red icon, which if you click would have a sweetalert popup that says the job is removed from your wishlist. And if the job is not part of your wishlist it would be displayed in blue, which if you click would have a pop up that says the job has been added to your wishlist. All this works, except for when you have just loaded the page for the first time, and one of the listed jobs is NOT part of your wishlist, and displayed in blue. If you click this blue icon, instead of saying "added to wishlist" and turning red, it says "removed from wishlist" and stays blue, even though its not part of the wishlist. Clicking the button AGAIN, will then do the correct action, saying "added to wishlist" and flipping the color, so the error only occurs the first time. Something wrong with .data('wl') being set for … -
How to pass the CSRF Token in iFrame of Django?
I have made a site with django. I wish people can iframe my form and fill it to check the results. I have already tried by writing the following code in settings.py X_FRAME_OPTIONS = 'ALLOW-FROM example.com' CSRF_TRUSTED_ORIGINS = ['example.com'] CSRF_COOKIE_SAMESITE = None But it won't work. Shows the following error. How can I solve this issue. Moreover, if I want to allow all user how to write Xframe options. I am new to Django. I have tried with this It shows iframe but when submit form it is showing this kind of error. -
Handling ManyToMany Signals: Updating Individual Objects
I want to update user profiles by sending a signal once a specific user has been added onto an external m2m field. This is my setup. account-app class Deliverer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='deliverer') busy = models.BooleanField(default=False) orders-app: models.py class Order(models.Model): deliverer = models.ManyToManyField(Deliverer, related_name='Deliverer') deliveringstatus = models.BooleanField(default=False) order/views.py def assign_deliverer(request, user_id): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) del = get_object_or_404(Deliverer, user_id=user_id) order.deliverer.add(del) order.save() order/signals.py @receiver(m2m_changed, sender=Order.deliverer.through) def m2m_changes_deliverer(sender, instance, **kwargs): if kwargs['action'] == 'post_add': instance.deliveringstatus = True instance.save() Once a deliverer has been assigned an order (multiple deliverers can work on the same order) I want an additional seignal changing his/her profile's busy-status to TRUE. Failed: What I've tried: account-app/signals.py @receiver(post_save, sender=Order) def deliverer_added(sender, instance, **kwargs): obj, _ = Deliverer.objects.get(user=instance.deliverer) obj.status = True obj.save() ERROR: Field 'id' expected a number 1. Any insight on how to do this? -
How to distinguish different paths in Django which has similar path pattern? [closed]
I have recently started working with the Python Django framework. I have set up urls.py file that contains all my application URLs ```from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("encyclopedia/search", views.search_entries, name="search_entry"), path("encyclopedia/<str:title>", views.get_entry, name="entry"), path("encyclopedia/<str:action>", views.add_new, name="add_new"), ]``` How do identify the last 2 paths (encyclopedia/str:title) and (encyclopedia/str:action) uniquely? -
Annotate user of last revision in django-reversion
I keep track of the revisions of one of my django-models like so: @reversion.register() class MyModel(models.Model): In my views, I have a ListView for this model: class MyModelListView(ListView): model = MyModel Now: In the list/table of objects I want in one column displayed who made the last revision... i.e. the username of the last revision of the object... So my idea is something like this: def get_queryset(self): object_list = MyModel.objects.annotate(user_lastversion=reversion.reverse()[0].revision.user.get_username) But of course it is not working, since reversion has no attribute reverse. And I don't know how to merge something like Version.objects.get_for_object(MyModel.objects.get(slug=slug)).reverse()[0].revision.user.get_username into "annotate". Any help would be appreciated! -
How to download the uploaded file in s3 bucket without storing the temporary folder Python?
I have uploaded some of the files to the S3 bucket In private mode. I want to download the file based on the key. It should look like when I click the link to download it downloads directly without storing anywhere in the machine. Thanks in advance! -
DoesNotExist at /delete/64 list matching query does not exist.django
i'm creating todo list its fine working but when i double click so it shows me an error here is the screenshot here is my views.py code https://www.onlinegdb.com/edit/SJjz-d1aD -
DJANGO: Exception has occurred: AttributeError type object 'Client' has no attribute 'objects'
this is driving me crazy, it was working 2 days ago! I have a model called client on authentication/models: import datetime from django.contrib.auth.models import User from django.db import models from logs.mixins import LogsMixin class Client(LogsMixin, models.Model): """Model definition for Client.""" id = models.CharField("ID del cliente", primary_key=True, null=False, default="", max_length=50) company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) cif = models.CharField("CIF", null=False, default="", max_length=50) platforms = models.ManyToManyField('consumptions.Platform', verbose_name=("Plataformas")) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) When I try to get Clients with my funcion "get_client_data" like this: # -*- encoding: utf-8 -*- import datetime import json import sys from operator import itemgetter from authentication.models import Client from consumptions.models import Platform from ..models import MF, Call, Consumption, Course, Message, Provider from .sap import * def get_client_data(request): """ Con esta función pediremos los datos del cliente a SAP y devolveremos una respuesta """ if request.is_ajax(): response = {} try: request_body = request.body.decode('utf-8') url = json.loads(request_body) if Platform.objects.filter(url=url).exists(): client = Client.objects.filter(platforms__url=url).first() # FAILS HERE I receive the next error: Exception has occurred: AttributeError type object 'Client' has no attribute 'objects' What am I doing wrong? -
Django static files not loading on heroku server showing "Refused to apply style from '<URL>' because its MIME type"
Hi my django project working fine on local server but heroku couldn't find my static files i have installed whitenoise and also run collectstatic but still show this error "Refused to apply style from '' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." # MIME TYPE import mimetypes mimetypes.add_type("text/css", ".css", True) # Application definition INSTALLED_APPS = [ 'pages', 'listings', 'realtors', 'accounts', 'contacts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'btrc.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'btrc.wsgi.application' import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES ['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'btrc/static') ] # Media folder setting MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = …