Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django_simple_jwt for sending the token as soon as user signs up?
Hi All I have a code from https://medium.com/@dakota.lillie/django-react-jwt-authentication-5015ee00ef9a which uses django rest_framework_jwt for responding Token with the user sign up importing libraries from rest_framework import routers, serializers, viewsets from django.contrib.auth.models import User, Group **from rest_framework_jwt.settings import api_settings from rest_framework_simplejwt.serializers import TokenObtainPairSerializer** Serializer:- class UserSerializerWithToken(serializers.ModelSerializer,TokenObtainPairSerializer): email = serializers.EmailField(required=True) username = serializers.CharField() password = serializers.CharField(style = {'input_type':'password'}, min_length=8, write_only=True) token = serializers.SerializerMethodField(source ="get_token") def get_token(self, obj): **jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER** payload = jwt_payload_handler(obj) token = super(obj).get_token(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'email','username', 'password') and the views :- """ class UserList(APIView): """ Create a new user. It's called 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. """ permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = UserSerializerWithToken(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now I want to convert all the serializer setting from rest_framework_jwt to rest_framework_simplejwt as the former is not being actively maintained. I am having issues in what to replace in jwt_payload_handler, jwt_encode_handler and payload for rest_framework_simplejwt. -
Django view self.request.GET.get() inside of get() function returns None
I have a search field inside my html code and I want to get that value in order to get the corresponding values from the table, but I keep getting None and I'm not sure why. Here is the html code <form autocomplete="off" action="" method="GET"> <div class="autocomplete"> <input id="myInput" type="text" name="Item" placeholder="Search..."> </div> <input type="submit" value="Search"> </form> <div class="chart-container"> <canvas id="myChart"></canvas> <script type="text/javascript"> var endpoint = 'api/chart/data/' var dataset = [] var labels = [] $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels dataset = data.dataset var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: dataset }] }, options: { responsive:true, layout: { padding: { left: 50, right: 50 } } } }) }, error: function(error_data){ console.log("error") console.log(error_data) } }) </script> </div> My views homepage() function prints out correctly what's put into the search field, but doing self.request.GET.get('Item') prints out None? class chartData(APIView): def homepage(request): print('Inside of testing class') itemName = request.GET.get('Item') print('homepage() var itemName = ', itemName) return render(request,'home/home.html') def get(self, request): itemName = self.request.GET.get('Item') print(itemName) self.dataLabels = [] self.dataset = [] self.itemData = DataInfo.objects.filter(item_name … -
Ajax to submit a like button leading to Page 404 Error
I am trying to use Ajax to submit a like button, I believe everything is in order but I keep getting PAge 404 error after submitting the like button, I am not sure what is the reason. Need help to identify the error. Here is the view class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked return context def LikeView(request, pk): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) like = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) like = False else: post.likes.add(request.user) like = True context["total_likes"] = total_likes context["liked"] = liked if request.is_ajax: html = render_to_string('like_section.html', context, request=request) return JsonResponse({'form': html}) Here is the url path('like/<int:pk>', LikeView, name='like_post'), here is the template <form class="mt-0" action="{% url 'score:like_post' post.pk %}" method='POST'> {% csrf_token %} <strong> Likes : {{total_likes}} </strong> {% if user.is_authenticated %} {% if liked %} <button id='like' type='submit' name='post_id' class= "btn btn-danger btn-sm" value="{{post.id}}"> Unlike </button> {% else %} <button id='like' type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button> {% endif %} {% else %} <p><small><a href="{% url 'login' %}"> Login</a> … -
Deploy Django api rest in heroku using docker
I'm trying to access to my Api rest that I released in Heroku with docker and see that Dynos is running the gunicorn command that I put in the Dockerfile. The Dockerfile that I used is: FROM ubuntu:18.04 RUN apt update RUN apt install -y python3 python3-pip RUN mkdir /opt/app ENV PYTHONUNBUFFERED 1 ENV LANG C.UTF-8 ENV DEBIAN_FRONTEND=noninteractive COPY Ski4All/ /opt/app/ COPY requirements.txt /opt/app/ RUN pip3 install -r /opt/app/requirements.txt ENV PORT=8000 CMD exec gunicorn Ski4All.wsgi:application — bind 0.0.0.0:$PORT When I release I go into the container via heroku run bash -a "name app" and executing ps aux I don't see the api running. But if execute the command of my Dockerfile when I'm in the container. Any idea? -
Django assigning multiple models to single model
I am wanting to create a way to add the players of a team into my admin panel. Then I want to load in a years worth of events for the team. Then when creating a list, I want to select each persons name and then multiselect all the events they are going to and assign it to my event roster. class Person(models.Model): name = Charfield(max_length=100) class Event(models.Model): name - Charfield(max_length=100) ....more fields.... class List(models.Model): upcoming_events_list = ??? In my head it would look like this.. Mary Ann: Event1 Event2 Event3 John Pilgrim: Event4 Event9 Rusty Spoon: Event13 Event99 Event2 Event4 etc... I will eventually want to be able to create multiple event rosters. So I could have a Home Roster, Away Roster, Playoff Roster, etc. Where I can reuse the players names and events on each of these rosters. Then when I want to filter through the list for a certain name how would I be able to do that? I am new to the admin page and Django in general but it would be nice to login and select 'Names' and add all the players. Then go to 'Events' and add all the event details. Then go to … -
Confusion of codes in the django views part
class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=category_choices, max_length=2) label = models.CharField(choices=label_choices, max_length=1) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,null=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("product",slug=slug) Though it doesnt gives me error but i am confuse of the following codecan any on explain me that how this add-to-cart views work ? can anyone explain me in step wise? i understand the models but i m confused with views part. what concept is used in the following code for adding item to the cart? -
Trying to create attributes from a functions return statement
I think I'm lacking understanding of scope. In my "Store" model I have a function to take the address field and turn it into latitude and longitude. I want to take the two values I return and use them to create latitude and longitude attributes for my "Store" model. My goal is to use them in my template like {{store.latitude}} and {{store.longitude}} class Store(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=255) def get_coords(self): geolocator = Nominatim() location = geolocator.geocode(self.address) latitude = location.latitude longitude = location.longitude return latitude, longitude latitude = ... longitude = ... class Meta: verbose_name_plural = "Store" def __str__(self): return self.name -
Django: How can I assign a variable ForeignKey to data collected in forms?
My goal is to be able to add "weight" values to my existing lists. The weights correspond to an exercise by ForeignKey which in turn the exercise relates to a specific workout. I've created a form that adds the weight value but I can not figure out how to set the ForeignKey to the related exercise. Here is my code and I will explain further after it: models.py from django.db import models from django.utils import timezone class Workout(models.Model): workout_name = models.CharField(max_length=100) def __str__(self): return self.workout_name @property def exercise(self): return self.workout.all() class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='workout') exercise_name = models.CharField(max_length=100) def __str__(self): return self.exercise_name @property def weight(self): return self.exercise.all() class Weight(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='exercise') weight = models.DecimalField(decimal_places=0, max_digits=10000) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.weight}' forms.py from django import forms class WeightForm(forms.Form): weight = forms.DecimalField(decimal_places=0, max_digits=10000) views.py def workout(request, workout_id): workout_main = Workout.objects.get(id=workout_id) exercise = Exercise.objects.filter(workout__workout_name=workout_main).values_list('pk', flat=True) if request.method == 'POST': form = WeightForm(request.POST) if form.is_valid(): w = form.cleaned_data['weight'] new_weight = Weight(weight=w, exercise_id=exercise) new_weight.save() return redirect('workouts_workout', workout_id) form = WeightForm() context = { 'workout': workout_main, 'form': form, } return render(request, 'workouts/workout.html', context) Above in my views.py my attempt to solve my problem was with the creation of the … -
REST API, JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I have a django based website with user profiles system where users can add notes. I am trying to implement CRUD via REST Framework. I followed this tutorial: https://dev.to/nobleobioma/build-a-crud-django-rest-api-46kc I have modified the code. I have a model named Note, here is the model's code: class Note(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="notes") type = models.IntegerField(choices=NOTE_TYPE, default=0) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-created_on"] The view class is as following: @api_view(["POST"]) @permission_classes([IsAuthenticated]) @csrf_exempt def add_note(request): payload = json.loads(request.body) user = request.user.id note = Note.objects.create( type=payload["type"], content=payload["content"], author=user, ) serializer = NoteSerializer(note) return JsonResponse({'notes': serializer.data}, safe=False, status=status.HTTP_201_CREATED) When I run the server, all the other URLs work but the URL linked to this class gives me the following error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I have tried many solutions on similar error but nothing seems to help. -
Filtering set in template
I've got the following models. class FAQCategory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=50) def __str__(self): return self.title class FAQ(models.Model): category = models.ForeignKey(FAQCategory, on_delete=models.SET_NULL) question = models.CharField(max_length=100) answer = models.TextField(max_length=10000, null=True, blank=True) def __str__(self): return self.category Within my template, I'd like to be able to show a category title ONLY if there are FAQs that have that category (already satisfied with the code below) and at least one FAQ that has that category has a answer that is not equal to None or "" (not sure how to do this). So far, I have the following code: {% if category.faq_set.all|length > 0 %} {{category.title}} {% endif %} -
How to get data from form and show in dropdown in django
What I m trying to do: Upload a CSV file(Form #1) and show header of a CSV file in the dropdown (Form #2). and these forms are on the same page. What I have tried: for now I able to upload CSV file and display header in a webpage. index.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="file1">Upload Files</label> <div class="custom-file"> <input type="file" accept=".csv" id="file1" name="file" required="True" class="form-control custom-file-input"> <label class="custom-file-label" for="file1"></label> </div> </div> <div class="form-group d-flex justify-content-center"> <button type="submit" class="btn text-white w-50" value="Upload">Upload</button> </div> </form> views.py def read_csv(request): csv_file = request.FILES['file'] data = pd.read_csv(csv_file) i = list(data.head(0)) context = {'loaded_data': i} return render(request, "WebApp/index.html", context) -
Problem with setting up datetimepicker in Django
Im currently using Tempus Dominus for my datetime picker in django. In my models.py I have class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1' }) ) and in my template I have <h5>When would you like to pickup? *</h5> <div class="input-group date" id="datetimepicker1" data-target-input="nearest"> <input type="text"> {{ form.date }} <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <script> $(function () { $("#datetimepicker1").datetimepicker({ format: 'DD/MM/YYYY HH:mm', }); }); </script> </div> I want my end result to look like this However, when I try to add in {{ form.date }} instead of a input field, it would only show the calendar icon with no input field. I of course want the datetime info in the database but I've been scratching my head for the past couple hours trying to link them up, Im sure im missing something stupid. Thanks!! -
Django model field having multiple dictionary options
I am running into an issue and this is a replica in a smaller scale of what I am running into.. class Garage(models.Model): vehicles = models.CharField(max_length=255) What I want to store in my garage is multiple vehicles. And I want each vehicle to be a Make and Model. So I was thinking I could do something like this.. class Make(models.Model): make = models.CharField() class Model(models.Model): model = models.CharField() Then I can specify in my Garage class any amount of Make:Model objects and assign them to the vehicles field. So then essentially, vehicles would like like: {'Ford':'Mustang', 'Chevrolet':'Camaro', 'Dodge':'Charger'} -
Django formset, pass initial value and save to different model
I am trying to pull initial data from existing objects and save them as new object. The situation is like, user tries to submit their education information for review. If user has pre-saved education information, bring the initial values from the object and pre-fill the forms of the education. When user saves it, it does not change the original object, but makes new object. I tried to bring original value and save the formset as education_form = ResumeEducationFormSet(request.POST, instance=resume, prefix='education') but it shows the "inline value does not match the parent instance". I get why I am getting this error, but I can't find the way to just bring the initial values. I can do the (initial={}) thing but it is hard it there are multiple objects. How can I solve this problem? -
PRAW how to catch a "received 401 HTTP response"
I'm purposely trying to authenticate with wrong credentials to the reddit API using PRAW. I can see on my console that I'm getting "received 401 HTTP response" error. Traceback (most recent call last): File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/bob/Sites/django/myproj/src/blog/views.py", line 246, in syncMyPosts thisimage.remove_category = submission.removed_by_category File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/praw/models/reddit/base.py", line 33, in __getattr__ self._fetch() File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/praw/models/reddit/submission.py", line 591, in _fetch data = self._fetch_data() File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/praw/models/reddit/submission.py", line 588, in _fetch_data return self._reddit.request("GET", path, params) File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/praw/reddit.py", line 726, in request return self._core.request( File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/sessions.py", line 329, in request return self._request_with_retries( File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/sessions.py", line 227, in _request_with_retries response, saved_exception = self._make_request( File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request response = self._rate_limiter.call( File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/rate_limit.py", line 35, in call kwargs["headers"] = set_header_callback() File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/sessions.py", line 282, in _set_header_callback self._authorizer.refresh() File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/auth.py", line 349, in refresh self._request_token( File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/auth.py", line 149, in _request_token response = self._authenticator._post(url, **data) File "/Users/bob/Sites/django/myproj/lib/python3.8/site-packages/prawcore/auth.py", line 32, in _post raise ResponseException(response) prawcore.exceptions.ResponseException: received 401 HTTP response I would rather catch this error / exception and show a friendly message. Having a hard time understanding how to use … -
Python Cloud Programming
I'm new in python and trying to develop my projects. I've been using tkinter module to code my programs so far. As you may notice tkinter works in local machine and does not allowed you to use the data from another computer(at least I know that so far). Now I'm in need of developing my project as a website but I don't know which way to go. I'm planning to open a website and code my program in there as well as I need to save program user informations(user name, password, their data's) in my website cloud server. I've been searching django, tkinter and other GUI modules to decide my way to code but I couldn't find the best proper way. If you have any recommendations I really appreciate it. -
django: 502 bad gateway because of gunicorn
I keep running into 502 bad gateway error while trying to upload files from my django app. Nginx error log points me to gunicorn. I have set up asyncronous workers to deal with the problem but it does not work. I keep getting the error when uploading slightly big files. Here is my gunicorn error log: [2020-05-18 22:49:47 +0000] [2867] [INFO] Using worker: gevent [2020-05-18 22:49:47 +0000] [2870] [INFO] Booting worker with pid: 2870 [2020-05-18 22:49:47 +0000] [2879] [INFO] Booting worker with pid: 2879 [2020-05-18 22:49:47 +0000] [2891] [INFO] Booting worker with pid: 2891 [2020-05-18 22:49:47 +0000] [2892] [INFO] Booting worker with pid: 2892 [2020-05-18 22:49:47 +0000] [2894] [INFO] Booting worker with pid: 2894 [2020-05-18 22:58:28 +0000] [2867] [CRITICAL] WORKER TIMEOUT (pid:2892) [2020-05-18 22:59:48 +0000] [2925] [INFO] Booting worker with pid: 2925 [2020-05-18 23:10:14 +0000] [2867] [INFO] Handling signal: term and here is what my gunicorn config look like: gunicorn/config.py BASE_DIR = "/home/ubuntu/" sys.path.append(BASE_DIR) bind = '127.0.0.1:8000' backlog = 2048 import multiprocessing workers = 5 worker_class = 'gevent' worker_connections = 1000 timeout = 300 graceful_timeout = 300 keepalive = 300 and then gunicorn.conf [program:gunicorn] directory=/home/ubuntu/mysite command=/home/ubuntu/venv/bin/gunicorn --config /home/ubuntu/venv/lib/python3.6/site-packages/gunicorn/config.py --bind unix:/home/ubuntu/mysite/app.sock app.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn I am not … -
Django: Having the admin panel display different models when viewing another model
I am new to Django and I am working on problem I am facing. Right now my model (Property) looks like this in the admin panel. Right now I can assign this property to different devices and different platforms. What I want to do is assign this to different devices BASED ON different platforms. Which is resembled here: Currently my models.py looks like this: class Device(models.Model): name = models.CharField(max_length=255) class Meta: verbose_name = 'Device' verbose_name_plural = 'Devices' ordering = ['name'] def __str__(self): return self.name class Platform(models.Model): name = models.CharField(max_length=255) class Meta: verbose_name = 'Platform' verbose_name_plural = 'Platforms' ordering = ['name'] def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=255) applicable_devices = models.ManyToManyField(Device) applicable_platforms = models.ManyToManyField(Platform) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' ordering = ['name'] def __str__(self): return self.name def get_devices(self): return ", ".join([str(p) for p in self.applicable_devices.all()]) def get_platforms(self): return ", ".join([str(p) for p in self.applicable_platforms.all()]) get_devices.short_description = 'Devices' get_platforms.short_description = 'Platforms' class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) applicable_device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) applicable_platform = models.ForeignKey(Platform, null=True, on_delete=models.SET_NULL) applicable_events = models.ManyToManyField(Event) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' ordering = ['name'] def __str__(self): return self.name class Property(models.Model): name = models.CharField(max_length=255, unique=True) description = models.CharField(max_length=512, … -
Django Need to add two serializers data together in one response
I have a two models, Person and Video. Below viewset allows me all methods like POST, PATCH, DELETE, GET. class PersonViewSet(viewsets.ModelViewSet): queryset = apis_models.Person.objects.all() serializer_class = apis_serializers.PersonSerializer permission_classes = [HasPermPage] Video model is associated with person model as foreign key. So each person has few videos. Now what I need is when I do "/person/{id}/" I should get person details along with all videos details it associated with. Please let me know what change needs to be done to above ViewSet. -
Proper namespacing when using django-hosts
So I'm using django-hosts so as to have multiple domains for each app. But then I'm having an issue when trying to access the url index for each of the apps in my base.html I'm trying to have something like this in my base.html file <div> <ul> <li><a href="{% url 'home:index' %}">Home</a></li> <li><a href="{% url 'laundry:index' %}">Laundry</a></li> <li><a href="{% url 'tailor:index' %}">Tailor</a></li> </ul> </div> and this is my hosts.py file from django_hosts import patterns, host from django.conf import settings host_patterns = patterns( '', host(r'www', 'artisan.home_urls', name='www'), host(r'laundry', 'artisan.laundry_urls', name='laundry'), host(r'tailor', 'artisan.tailor_urls', name='tailor'), host(r'admin', settings.ROOT_URLCONF, name='admin') ) And I have 3 files, namely home_urls.py, laundry_urls.py, and tailor_urls.py and each of them have the same format as the one below # home_urls.py from django.urls import path, include app_name = 'home' urlpatterns = [ path('', include('home.urls')), ] # tailor_urls.py from django.urls import path, include app_name = 'tailor' urlpatterns = [ path('', include('tailor.urls')), ] # laundry_urls.py from django.urls import path, include app_name = 'laundry' urlpatterns = [ path('', include('laundry.urls')), ] But then, the problem is that only the namespacing for the home.urls is working. For the others, I keep getting a namespace error and I have no idea why. I was wondering if maybe … -
Using database data for labels and dataset with Django and Chartjs, getting error when referencing those values
I'm trying to use the values in my DB table for labels and timestamps, but I'm getting syntax errors with my code.. I was refereeing previous questions and they seemed to do what I'm doing, but I get " Property assignment expected.javascript " ... " ',' expected.javascript " ... " Declaration or statement expected.javascript " when I try to create the labels. Do I need $ajax? This is the code I have so far, I started off with the getting started code on the chartjs site <div class="chart-container"> <canvas id="myChart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <script type="text/javascript"> var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'line', // The data for our dataset data: { labels: [{% for d in data %} "{{ d.date }}", {% endfor %}], datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [0, 10, 5, 2, 20, 30, 45] }] }, // Configuration options go here options: { responsive:true, maintainAspectRatio: false } }); </script> </div> -
Django CropperJS CropperImageField doesn't save the cropped image
I developed an app in Django and in Admin Panel, when adding an Image to my Model, I need to crop it (but it's not a standard crop, so I need to do it manually, by drag and drop for every new image added). So I found CropperJS that fits perfectly. I pip installed CropperJS, I ran it and it works (the modal shows up and I can crop the image, I see the preview of the cropped image), but the problem is that when I press "Save", the picture just don't save. The CharField(name) saves. My code: class ImageTest(models.Model): image_field_crop = CropperImageField(upload_to='images/', default=None, null=True, blank=True) name = models.CharField(max_length=50, default=None, null=True, blank=True) -
Django set_wakeup_fd only works in main thread
I have uploaded my django web app to my windows server using WAMP apache web server. Everything works well and as expected, however occasionally when i try to load a page, i get thrown this error. I am using django version 3.0.6 and am using python version 3.8.3. I was originally using 3.8.2 but read somewhere if i upgrade python the error will subside. My windows server is running windows server 2008 rc2. Has anyone else encountered this error and/or know of a way to stop it? -
How to add multiple model objects on the same admin page Django
The idea is super simple. This is specific to my project, I want to add data to 2 objects of the same model on one Django admin page and have one save button. My class: class Data(models.Model): issuer = models.ForeignKey(Issuers, on_delete=models.CASCADE) issuer_field = models.ForeignKey(Fields, on_delete=models.CASCADE, null=True) data_year = models.PositiveSmallIntegerField() long_term_ar = models.IntegerField() section_1 = models.IntegerField() short_term_ar = models.IntegerField() short_term_investments = models.IntegerField() cash = models.IntegerField() To illustrate:I want to have 2 of those on the same page I am new to Django, and it will be super helpful if you will help me implement this idea -
Django admin able to upload images to S3 bucket but doesn't load on template
I was able to upload images to my s3 bucket via django admin however, the images do not load on the HTML page. I followed the documentation and checked some tutorials and other solutions but none worked so far. I tried adding the region name of my s3 bucket but this didnt worked either. I also tried making the bucket public but to no avail. This is my settings.py: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Upon inspecting element and viewing the image, I am greeted with this error: this lead me to the trying out making the bucket public and configuring utils.py (https://stackoverflow.com/a/53976351/9615990) which didnt work.