Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django urls without a trailing slash show Page not found
in django urls without a trailing slash in the end i get this result "Page not found 404" the same project and the same code in one pc i get different result. this code is when i get the page without slash: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), ] and this the same code but i should to add slash from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), ] what i am waiting in the frontend its my views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def about(request): return HttpResponse('about page') i am waiting for your help guys -
Django Pass URL Parameter To Decorator
trying to redirect user to a page if they're not staff members. how do i pass a url parameter to a django decorator? # categories.urls.py from django.urls import path from categories.views import CategoryInfoView, CategoryDetailView app_name = 'categories' urlpatterns = [ path('<slug:handle>', CategoryDetailView.as_view(), name = 'category'), path('<slug:handle>/info/', CategoryInfoView.as_view(), name = 'category_info'), ] # categories.view.py class CategoryInfoView(LoginRequiredMixin, DetailView): model = Category template_name = 'categories/info.html' context_object_name = 'category' @redirect_if_not_staff(redirect_to = reverse_lazy('categories:category')) # <-- how do i pass the url parameter here?! def get(self, request, *args, **kwargs): return super().get(self, request, *args, **kwargs) def get_object(self): return get_object_or_404(Category, handle = self.kwargs.get('handle')) # decorator.py def redirect_if_not_staff(*setting_args, **setting_kwargs): """ A decorator to redirect users if they are not staff Can be used as: @decorator(with, arguments, and = kwargs) or @decorator """ no_args = False redirect_to = setting_kwargs.get('redirect_to', reverse_lazy('index')) if len(setting_args) == 1 and not setting_kwargs and callable(setting_args[0]): func = setting_args[0] no_args = True def decorator(func): @wraps(func) def redirect_function(self, request, *args, **kwargs): if not request.user.is_staff: return HttpResponseRedirect(redirect_to) return func(self, request, *args, **kwargs) return redirect_function if no_args: return decorator(func) else: return decorator how do i get localhost:8000/categories/sample/info/ to redirect to localhost:8000/categories/sample/ if the user is not a staff using decorators currently getting this error NoReverseMatch at /categories/agriculture/info/ Reverse for 'category' … -
Programmatically generate Django models for legacy databases
I'm trying to find out if there is a way to programmatically generate Django models for legacy databases. So given a list of legacy tables, create a model for each one. Here is an example of what I mean class Person_001(models.Model): id = models.IntegerField(primary_key=True) huge_dataset = models.CharField(max_length=70) class Meta: managed = False db_table = 'person_001' So for example, create this model for person_001, person_002 etc... I realize there may be a more efficient way of storing this data and I am opened to suggestions, but the data has been stored this way because huge_dataset is, well, huge. -
Django - if checkbox is selected, execute function
hey guys I'm trying to implement a feature in the user system where if you click the "is_staff" option another options pops up saying to enter your staff_id number. Is this possible? if so how can I implement it - or do I need to take a completely different approach. thanks! So something like this code from accounts>models.py from datetime import date import email import imp from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Email address is required') if not username: raise ValueError('Username is required') user = self.model( email=self.normalize_email(email), username = username, ) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password = password, username = username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using = self.db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) #staff_number = models.CharField(max_length=10, unique=True) is_superuser = models.BooleanField(default=False) #note for self - these fields are required USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] objects = MyAccountManager() def __str__(self): return self.email def … -
Checkbox checked, javascript in Django template
I am just trying to display hiddens items in django template when checkbox is checked, but in my console i am getting 1:194 Uncaught TypeError: Cannot read properties of null (reading 'checked') at inventoryFunction (1:194:22) at HTMLInputElement.onclick (1:107:73) the items are hidden in a table and when i check a category i am hoping to get them displayed here is the template : <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in categories%} <input type="checkbox" id="{{category.id}}" onclick="inventoryFunction()"> <label for="{{category.id}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'> {% for category in items%} <div class='{{category.id}}' style="display:none"> <div>{{category}}</div> <table class='runninghours-table'> <tr> <th>Item name</th> <th>part number</th> <th>R.O.B</th> </tr> <tbody> {%for item in category.items.all%} <tr> <td>{{item.name}}</td> <td>{{item.part_number}}</td> <td>{{item.ROB}}</td> </tr> {%endfor%} </tobdy> </table> </div> {%endfor%} </div> </div> the JavaScript : <script> function inventoryFunction() { var checkBox = document.getElementById("{{category.id}}"); var item = document.getElementsByClassName("{{category.id}}"); if (checkBox.checked == true) { item.style.display = "block"; } else { item.style.display = "none"; } } </script> -
Real time bidirectional data sync client-server
I am trying to achieve real time data sync on my android application to django server with support to offline capabilities. What protocols or specifications to achieve that. Just like how Firebase works but with Android and Django having PostgreSQL as DB -
"unexpected keyword argument 'version'" when trying to deploy a Django app on Heroku
2022-02-06T22:55:19.786956+00:00 app[web.1]: Error: __init__() got an unexpected keyword argument 'version' 2022-02-06T22:55:19.959506+00:00 heroku[web.1]: Process exited with status 1 2022-02-06T22:55:20.021043+00:00 heroku[web.1]: State changed from starting to crashed 2022-02-06T22:55:20.033987+00:00 heroku[web.1]: State changed from crashed to starting 2022-02-06T22:55:22.000000+00:00 app[api]: Build succeeded 2022-02-06T22:55:27.937148+00:00 heroku[web.1]: Starting process with command `gunicorn bona_blog.wsgi:application --log-file -` 2022-02-06T22:55:30.108106+00:00 app[web.1]: 2022-02-06T22:55:30.108127+00:00 app[web.1]: Error: __init__() got an unexpected keyword argument 'version' 2022-02-06T22:55:30.316169+00:00 heroku[web.1]: Process exited with status 1 2022-02-06T22:55:30.440121+00:00 heroku[web.1]: State changed from starting to crashed 2022-02-06T22:56:11.005567+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=fceoapp.herokuapp.com request_id=45757802-6d06-4d6e-80d3-90feafdeb023 fwd="105.112.52.76" dyno= connect= service= status=503 bytes= protocol=https 2022-02-06T22:56:10.341541+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fceoapp.herokuapp.com request_id=c030a659-ad28-4088-8b87-58d94731a394 fwd="105.112.52.76" dyno= connect= service= status=503 bytes= protocol=https -
Django: update a model with the current user when an non-model form field is changed
I'm building a page that allows users to edit Task and related Activity records (one task can have many activities), all on the same page. I want to allow the user to "adopt" one or more activities by ticking a box, and have their user record linked to each activity via a ForeignKey. Here are extracts from my code... models.py from django.contrib.auth.models import User class Task(models.Model): category = models.CharField(max_length=300) description = models.CharField(max_length=300) class Activity(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) title = models.CharField(max_length=150) notes = models.TextField(blank=True) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) The activity "owner" is linked to a User from the Django standard user model. I added an extra field in the form definition for the adopt field - I don't want to add it to the model as I don't need to save it once it's done it's job. forms.py class ActivityForm(forms.ModelForm): adopt = forms.BooleanField(required=False) class Meta: model = Activity fields = '__all__' views.py def manage_task(request, pk): task = Task.objects.get(pk = pk) TaskInlineFormSet = inlineformset_factory(Task, Activity, form = ActivityForm) if request.method == "POST": form = TaskForm(request.POST, instance = task) formset = TaskInlineFormSet(request.POST, instance = task) if form.has_changed() and form.is_valid(): form.save() if formset.has_changed() and formset.is_valid(): ## ? DO SOMETHING HERE ? … -
Django rest framework Detail not found while deleting
i have a a problem deleting an object via API. So i have 2 models, Answer and Vote vote is connected to Answer via foreignKey like this class Vote(models.Model): class AnswerScore(models.IntegerChoices): add = 1 subtract = -1 score = models.IntegerField(choices=AnswerScore.choices) answer = models.ForeignKey('Answer', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('answer', 'user',) Now i have an API endpoint for creating a Vote for user on a particular answer path('answers/<int:pk>/vote', VoteCreate.as_view()), Looks like this: class VoteSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) answer = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Vote fields = '__all__' class VoteCreate(ParentKeyAPIView, generics.CreateAPIView): model = Vote parent_model_field = 'answer_id' serializer_class = VoteSerializer def perform_create_kwargs(self, **kwargs): return super().perform_create_kwargs(user=self.request.user, answer_id=self.kwargs['pk'], **kwargs) And i also want to delete the same vote using url like this path('answers/<int:pk>/voteDelete', VoteDelete.as_view()), Because i know that only 1 user(request.user) can have 1 Vote per answer. So i tried doing it similarly to creating class VoteDelete(generics.DestroyAPIView): serializer_class = VoteDeleteSerializer def get_queryset(self): queryset = Vote.objects.get(user=self.request.user, answer_id=self.kwargs['pk']) return queryset Im using the same serializer just like above* I get an error: Not Found: /api/v1/answers/55/voteDelete There is no any traceback, i have checked in fact that in database the Vote with answer_id 55 exists and i can delete them via … -
Why shutil dont copy django image
Good day! I try to copy image from one Django model instance to another, with file cloning. I know that I can make it easier state.image = self.image, but I need physical copy of file with new name. My source: original = os.path.join(settings.MEDIA_ROOT, self.image.name) target = os.path.join(settings.MEDIA_ROOT, self.image.path.split('.')[1] + '_' + str(state.pk) + '.png') shutil.copyfile(original, target) content = urllib.urlretrieve(target) state.image.save(self.image.path.split('/')[-1], File(open(content[0])), save=True) state.save() My output: celery_1 | File "/app/state/models/bills/change_coat.py", line 79, in do_bill celery_1 | shutil.copyfile(original, target) celery_1 | File "/usr/local/lib/python3.9/shutil.py", line 264, in copyfile celery_1 | with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst: celery_1 | FileNotFoundError: [Errno 2] No such file or directory: '/app/media/img/state_avatars/file.jpg' Please tell me what am I doing wrong -
dependent select script for django
Help with js. I have two selects that earn them with nested list dictionaries. I don’t know how to write a script so that when choosing a brand it would be possible to select only the selected brand, after choosing send a request with the brand and model of the car <form action="" method="post" id="dynamic_selects"> <div class="row"> <select class="form-select" aria-label="Default select example" id="marka"> <option value="0">Select auto</option> {% for car in marka_sorted %} <option value={{ car }}>{{ car }}</option> {% endfor %} </select> </div> <div class="row"> <select class="form-select" aria-label="Default select example" id="model" disabled> <option value="0">Select model</option> {% for marka, model in marka_sorted.items %} {% for model_select in model %} <option value={{ model_select }} class={{ marka }}>{{ model_select }}</option> {% endfor %} {% endfor %} </select> -
SMTPAuthenticationError in Weblate (which uses Django)
I checked quite a few stackoverflow questions about this and none doesn't seem to be the exact case as me and didn't really work for me so posting this question. So I'm trying to setup weblate using docker which wants me to set weblate email host user, password etc. to send mails to users when using the site, my current docker-compose.override.yml looks like this: version: '3' services: weblate: ports: - 1111:8080 environment: WEBLATE_EMAIL_HOST: smtp.mymailserver.com WEBLATE_EMAIL_PORT: 465 WEBLATE_EMAIL_HOST_USER: translate@domain.com WEBLATE_EMAIL_HOST_PASSWORD: password WEBLATE_SERVER_EMAIL: translate@domain.com WEBLATE_DEFAULT_FROM_EMAIL: translate@domain.com WEBLATE_SITE_DOMAIN: translate.mydomain.com WEBLATE_ADMIN_PASSWORD: mypass WEBLATE_ADMIN_EMAIL: myemail@domain.com I checked this with gmail app in mobile with the same outgoing server configuration and it worked perfectly fine there (I was able to send mails from it) but whenever I try it with weblate, I'm seeing this error: SMTPAuthenticationError: (535, b'Authentication credentials invalid') This is the whole error I get in the logs -
How to upload profile image corresponding to the user?
models.py from django.db import models from django.forms import fields, ModelForm from .models import UploadImage from django import forms class UploadImageForm(ModelForm): class Meta: # To specify the model to be used to create form model = UploadImage # It includes all the fields of model fields = ['picture'] forms.py from django.db import models from django import forms from django.contrib.auth.models import User # Create your models here. class UploadImage(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.ImageField(default='default.jpg', upload_to='profile_pics') views.py from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.models import User from django.contrib import messages from Profile.models import UploadImage from Profile.forms import UploadImageForm def profile(request): if request.method == 'POST': form = UploadImageForm(request.POST, request.FILES, instance=request.user.profile) if form.is_valid(): form.save() return HttpResponse('uploaded') else: form = UploadImageForm(instance=request.user.profile) username = request.user.username first_name = request.user.first_name last_name = request.user.last_name email = request.user.email userinfo = { 'username': username, 'first_name': first_name, 'last_name': last_name, 'email': email, 'form': form, } return render(request, 'profile.html', userinfo) I wanted a image to be uploaded by a users of their profile. I have created a Model for uploading picture and images were getting uploaded but the other fields which recognizes that this uploaded picture of this user are empty in the database also after changing some … -
Django comment form not submitting data [ERROR: function' object has no attribute 'objects]
I have a comment form on a post page for submitting user comment. I keep getting this error: 'function' object has no attribute 'objects' And the trace-back is highlighting this in my views: comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id) Most answers on SO refer to identical model & function names but that is not my case. This is my model: class Comment(models.Model): opinion = models.CharField(max_length=2200, verbose_name='Comment', null=False) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.comment class Meta: verbose_name_plural = 'Comments' My view @login_required(login_url='Login') def AddComment(request, id): post = Post.objects.filter(id=id) user = User.objects.get(username=request.user) if request.method == "POST": usercomment = request.POST['comment'] comment_obj = Comment.objects.create(opinion = usercomment, author = user.id, post = post.id) comment_obj.save() messages.success(request, '✅ Your Comment Was Created Successfully!') return redirect('Home') else: messages.error(request, "⚠️ Your Comment Wasn't Created!") return redirect('Home') And my form: <form method="POST" action="{% url 'AddComment' post.id %}"> {% csrf_token %} <div class="d-flex flex-row add-comment-section mt-4 mb-4"> <img class="img-fluid img-responsive rounded-circle mr-2" src="{{ user.profile.profile_image.url }}" width="38"> <textarea class="form-control mr-3" rows="1" name="comment" placeholder="Your Comment" required></textarea> <button class="btn btn-primary btn-lg" type="submit">Comment</button> </div> </form> And lastly my URL: urlpatterns = [ path('post/<int:id>/comment', views.AddComment, name="AddComment"), ] -
Options for running on user demand asynchronous / background tasks in Django?
My Django app generates a complex report that can take upto 5 minutes to create. Therefore it runs once a night using a scheduled management command. That's been ok, except I now want the user to be able to select the date range for the report, which means the report needs to be created while the user waits. What are my options for running the tast in the background? So far I've found these: Celery - might work but is complex django-background-tasks looks like the right tool for the job but hasn't been updated for years, last supported Django is 2.2 The report/background task could be generated by AWS Lambda, basically in a microservice, which Django can call, Lambda can execute the background task then call the Django app with output once finished. This is what I did last time but not sure it would work now as I'd need to send the microservice 10mb of data to process. Use subprocess.popen which someone here said worked for them but other reports say it doesn't work from Django. -
Moving logic from Django views to models
This is my model: class Car(models.Model): make = models.CharField(max_length=30) model = models.CharField(max_length=30) rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], default=0, blank=True) avg_rating = models.FloatField(default=0, blank=True) rates_number = models.IntegerField(default=0, blank=True) def __str__(self): return self.make + ' ' + self.model What's the best way to move the logic from the following perform_create function (in views.py) to my models? class CarRate(generics.CreateAPIView): serializer_class = CarRatingSerializer queryset = Car.objects.all() def perform_create(self, serializer): pk = serializer.validated_data['car_id'] rating = serializer.validated_data['rating'] queryset = Car.objects.all() car_queryset = get_object_or_404(queryset, pk=pk) if car_queryset.rates_number == 0: car_queryset.avg_rating = rating else: car_queryset.avg_rating = (car_queryset.avg_rating + rating)/2 car_queryset.avg_rating = round(car_queryset.avg_rating, 1) car_queryset.rates_number = car_queryset.rates_number + 1 car_queryset.save() -
How to get last number from url in djnago
http://127.0.0.1:8000/orders/order_complete/2022020762/ This is my link the last number 2022020762 I want to get this in a function how to get this? -
How to bulk update using CSV file in Django Rest Framework
class PackageRateListPrice(core_models.TimestampedModel): package = models.ForeignKey( PackageLabPrice, related_name="package_ratelist_price", on_delete=models.CASCADE ) offer_price = models.FloatField(null=True, blank=True, default=None) addon_price = models.FloatField(null=True, blank=True, default=None) is_active = models.BooleanField(default=True) My View: class BulkUpdatePackageRateListPriceUpdateFromFile(APIView): permission_classes = [IsAuthenticated, ] def put(self, request, pk, *args, **kwargs): upload_file = request.FILES.get('package_ratelist_file') file = upload_file.read().decode('utf-8') reader = csv.DictReader(io.StringIO(file)) data = [line for line in reader] for item in data: package_id = item['PackageID'] offer_price = item['OfferPrice'] addon_price = item['AddOnPrice'] is_active = item['IsActive'] models.PackageRateListPrice(package_id = package_id, offer_price = offer_price,addon_price = addon_price, is_active = is_active).save() return Response({"status": True}, status=status.HTTP_200_OK) In this i am trying to bulk update from a csv file. So first i need to check that package_id(first_field) exists or not if it exists then it will update for that id. Any help will be really appreciated. Thank you !! -
kubernetes django deployment with gunicorn
I am trying to deploy an empty image of alang/django using kubernetes on my minikube cluster. This is my manifest file for deployment. apiVersion: apps/v1 kind: Deployment metadata: name: django labels: app: django spec: replicas: 2 selector: matchLabels: pod: django template: metadata: labels: pod: django spec: restartPolicy: "Always" containers: - name: django image: alang/django ports: - containerPort: 8000 env: - name: POSTGRES_USER valueFrom: configMapKeyRef: name: postgresql-db-configmap key: pg-username - name: POSTGRES_PASSWORD valueFrom: secretKeyRef: name: postgresql-db-secret key: pg-db-password - name: POSTGRES_HOST value: postgres-service - name: REDIS_HOST value: redis-service - name: GUNICORN_CMD_ARGS value: "--bind 0.0.0.0:8000" but i am facing issues with deployment , i think with gunicorn, getting this back: TypeError: the 'package' argument is required to perform a relative import for '.wsgi' Any way please to deploy it correctly? -
how to resolve uwsgi installation error on mac
i have the stack trace when i try to pip install uwsgi and i think its related to the mac os or my m1 chip > Collecting uWSGI Using cached uwsgi-2.0.20.tar.gz (804 kB) Building wheels for collected packages: uWSGI Building wheel for uWSGI (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/eliorcohen/placer-django-server/env556/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-install-UZMqSB/uwsgi/setup.py'"'"'; __file__='"'"'/private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-install-UZMqSB/uwsgi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-wheel-iPa0EY cwd: /private/var/folders/fv/r82y8wns2rsgbxjl0k12zxvc0000gn/T/pip-install-UZMqSB/uwsgi/ Complete output (154 lines): /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'descriptions' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib copying uwsgidecorators.py -> build/lib installing to build/bdist.macosx-12.0-x86_64/wheel running install using profile: buildconf/default.ini detected include path: ['/Library/Developer/CommandLineTools/usr/lib/clang/13.0.0/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include', '/Library/Developer/CommandLineTools/usr/include', '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks'] Patching "bin_name" to properly install_scripts dir detected CPU cores: 10 configured CFLAGS: -O2 -I. -Wall -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -fno-strict-aliasing -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DUWSGI_HAS_IFADDRS -DUWSGI_ZLIB -mmacosx-version-min=10.5 -DUWSGI_LOCK_USE_OSX_SPINLOCK -DUWSGI_EVENT_USE_KQUEUE -DUWSGI_EVENT_TIMER_USE_KQUEUE -DUWSGI_EVENT_FILEMONITOR_USE_KQUEUE -DUWSGI_UUID -DUWSGI_VERSION="\"2.0.20\"" -DUWSGI_VERSION_BASE="2" -DUWSGI_VERSION_MAJOR="0" -DUWSGI_VERSION_MINOR="20" -DUWSGI_VERSION_REVISION="0" -DUWSGI_VERSION_CUSTOM="\"\"" -DUWSGI_YAML -DUWSGI_XML -DUWSGI_XML_EXPAT -DUWSGI_PLUGIN_DIR="\".\"" -DUWSGI_DECLARE_EMBEDDED_PLUGINS="UDEP(python);UDEP(gevent);UDEP(ping);UDEP(cache);UDEP(nagios);UDEP(rrdtool);UDEP(carbon);UDEP(rpc);UDEP(corerouter);UDEP(fastrouter);UDEP(http);UDEP(signal);UDEP(syslog);UDEP(rsyslog);UDEP(logsocket);UDEP(router_uwsgi);UDEP(router_redirect);UDEP(router_basicauth);UDEP(zergpool);UDEP(redislog);UDEP(mongodblog);UDEP(router_rewrite);UDEP(router_http);UDEP(logfile);UDEP(router_cache);UDEP(rawrouter);UDEP(router_static);UDEP(sslrouter);UDEP(spooler);UDEP(cheaper_busyness);UDEP(symcall);UDEP(transformation_tofile);UDEP(transformation_gzip);UDEP(transformation_chunked);UDEP(transformation_offload);UDEP(router_memcached);UDEP(router_redis);UDEP(router_hash);UDEP(router_expires);UDEP(router_metrics);UDEP(transformation_template);UDEP(stats_pusher_socket);" -DUWSGI_LOAD_EMBEDDED_PLUGINS="ULEP(python);ULEP(gevent);ULEP(ping);ULEP(cache);ULEP(nagios);ULEP(rrdtool);ULEP(carbon);ULEP(rpc);ULEP(corerouter);ULEP(fastrouter);ULEP(http);ULEP(signal);ULEP(syslog);ULEP(rsyslog);ULEP(logsocket);ULEP(router_uwsgi);ULEP(router_redirect);ULEP(router_basicauth);ULEP(zergpool);ULEP(redislog);ULEP(mongodblog);ULEP(router_rewrite);ULEP(router_http);ULEP(logfile);ULEP(router_cache);ULEP(rawrouter);ULEP(router_static);ULEP(sslrouter);ULEP(spooler);ULEP(cheaper_busyness);ULEP(symcall);ULEP(transformation_tofile);ULEP(transformation_gzip);ULEP(transformation_chunked);ULEP(transformation_offload);ULEP(router_memcached);ULEP(router_redis);ULEP(router_hash);ULEP(router_expires);ULEP(router_metrics);ULEP(transformation_template);ULEP(stats_pusher_socket);" *** uWSGI compiling server core *** [thread 0][clang] core/utils.o [thread 2][clang] core/protocol.o [thread 1][clang] core/socket.o [thread 4][clang] core/logging.o [thread 7][clang] core/master.o [thread 6][clang] core/master_utils.o [thread 8][clang] core/emperor.o [thread 5][clang] core/notify.o [thread 3][clang] core/mule.o [thread 9][clang] core/subscription.o [thread 0][clang] core/stats.o [thread 2][clang] core/sendfile.o [thread … -
how fix cycle in django?
I have problem with cycle in djano(Maybe I dont understand this).I have cycle in template and it must to output value from database,but Idk how I can create cycle,which may output value from (id = 1),because this cycle output value (id = 0) again and again. vds.html {% for item in allobjects %} <div class="container-fluid"> <div class="body2"> <li class="title">{{item.title}}</li> <li class="listram">{{item.ram}}<small>ГБ(озу)</small></li> <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img> <li class="cpu">{{item.cpu}} vCore</li> <img class="cpu1"width="51px" height="50px" src="/static/main/images/cpu.png" ></img> <li class="hdd">{{item.hdd}}<small> ГБ(ssd)</small></li> <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img> <li class="os">Установка любой ос</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/> <li class="os">Виртуализация KVM</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/> <form action="https://billing.king-host.ru"> <button type="submit" name="buy">Купить</button> </form> <li class= "prise">{{item.name}}₽/месяц</li> </div> </div> <div class="container-fluid"> <div class="body3"> <li class="title">{{item.title}}</li> <li class="listram"><small>ГБ(озу)</small></li> <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img> <li class="cpu">2 vCore</li> <img class="cpu1"width="51px" height="50px" src="/static/main/images/cpu.png" ></img> <li class="hdd">40<small> ГБ(ssd)</small></li> <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img> <li class="os">Установка любой ос</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/> <li class="os">Виртуализация KVM</li> <img class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/> <form action="https://billing.king-host.ru"> <button type="submit" name="buy">Купить</button> </form> <li class= "prise">600 ₽/месяц</li> </div> </div> {% endfor %} models.py class VDSTARIFS( models.Model): id = models.CharField(max_length=40, primary_key= True,serialize=True) name = models.CharField(max_length=20, verbose_name = 'Цены') choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.') title … -
Field 'id' expected a number but got <User: ben>
I created a population script for a django website however, after running the script and making migrations, I logged in to the django admin page for my site to access the objects created using the script and could not do it for my Business model. It works fine for my other models. I get this error when I try to access the registered Businesses in my database from the Django admin page. It does not seem to trace back to any of my code but rather to a template in the admin folder of my python environment. Here's the error message: error message Here are my models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="profile_images", blank=True, default="profile_images/default.png") description = models.TextField(max_length=1024, default="") # boolean flag for identifying business owners is_business_owner = models.BooleanField(default=False) def __str__(self): return self.user.username class Business(models.Model): owner_fk = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=128) address = models.CharField(max_length=128) img = models.ImageField(upload_to="business_images", blank=True) slug = models.SlugField(unique=True) class Meta: verbose_name_plural = 'Businesses' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Business, self).save(*args, **kwargs) def __str__(self): return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}" Here is how I created the objects through the population script: def add_user(username, firstname, lastname, password, profile_pic, description, is_business_owner): new_user = User.objects.get_or_create(username=username, password=password, … -
Stuck deploying django to herkou posgress pip lock error
I am trying to deploy a Django app to herokou. I am getting a piplock that is out of date. -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in Pipfile.lock -----> Installing python-3.8.12 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing dependencies with Pipenv 2020.11.15 Your Pipfile.lock (a6086c) is out of date. Expected: (6ce893). [DeployException]: File "/tmp/build_df99f796/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/click/decorators.py", line 73, in new_func [DeployException]: return ctx.invoke(f, obj, *args, **kwargs) [DeployException]: File "/tmp/build_df99f796/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/click/core.py", line 610, in invoke [DeployException]: return callback(*args, **kwargs) [DeployException]: File "/tmp/build_df99f796/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/click/decorators.py", line 21, in new_func [DeployException]: return f(get_current_context(), *args, **kwargs) [DeployException]: File "/app/.heroku/python/lib/python3.8/site-packages/pipenv/cli/command.py", line 233, in install [DeployException]: retcode = do_install( [DeployException]: File "/app/.heroku/python/lib/python3.8/site-packages/pipenv/core.py", line 2052, in do_install [DeployException]: do_init( [DeployException]: File "/app/.heroku/python/lib/python3.8/site-packages/pipenv/core.py", line 1251, in do_init [DeployException]: raise exceptions.DeployException ERROR:: Aborting deploy ! Push rejected, failed to compile Python app. ! Push failed When I try and update the pip lock in the pipenv I am getting. pipenv lock Locking [dev-packages] dependencies… Locking [packages] dependencies… Building requirements... Resolving dependencies... ✘ Locking Failed! ERROR:pip.subprocessor:Command errored out with exit status 1: command: /Users/matthewsmith/.local/share/virtualenvs/devlog-XABMBIas/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/bq/46k05k255snbkf2x3fkzv0380000gn/T/pip-resolver-jdku7f8q/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/bq/46k05k255snbkf2x3fkzv0380000gn/T/pip-resolver-jdku7f8q/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' … -
sorting search result in django rest framework
I have written a search api for my website in django rest framework. when you search a name (e.g. "jumanji") there might be more than one result for the search for many reasons. what I want is for the result to be ordered by the "rating" field or "releaseDate" field of the Film model. here are my codes. # models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) duration = models.PositiveIntegerField() typeOf = models.IntegerField(validators=[MaxValueValidator(3), MinValueValidator(1),]) rating = models.FloatField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) releaseDate = models.DateTimeField(null=True) # serializers.py class FilmSerializer(serializers.ModelSerializer): class Meta: model = Film fields = [ "filmID", "title", "price", "duration", "typeOf", "numberOfFilminoRatings", "filminoRating", "rating", "releaseDate", "detailsEn", "salePercentage", "saleExpiration", "posterURL", "posterDirectory", ] # views.py '''Override get_search_fields method of SearchFilter''' class DynamicSearch(filters.SearchFilter,): def get_search_fields(self,view, request): return request.GET.getlist('search_fields',[]) '''Override page_size_query_param attribute of PageNumberPagination''' class CustomizePagination(PageNumberPagination): page_size_query_param = 'limit' """Pagination Handler""" class PaginationHanlerMixin(object): @property def paginator(self): if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator =None else : self._paginator = self.pagination_class() else : pass return self._paginator def paginate_queryset(self,queryset): if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self,data): if self.paginator is None: raise "Paginator is None" return self.paginator.get_paginated_response(data) class SearchFilm(APIView,PaginationHanlerMixin): authentication_classes = () permission_classes = (AllowAny,) def __init__(self,): APIView.__init__(self) self.search_class=DynamicSearch self.pagination_class=CustomizePagination def filter_queryset(self,queryset): … -
How to reuse an existing python Enum in Django for chocies?
Django has its own Enumeration types like model.TextChoices. However, if you already use traditional python Enum objects in your codebase, it would be nice to reuse them for fields definition without redefining all the values. Is there an elegant straightforward way to do this without too much boilerplate? What I tried: building a models.TextChoices class from the Enum seems impossible without manually declaring the values building the choices parameter from the Enum instead of dealing with models.TextChoices but then things like obj.field == ENUM.XXX won't work because Enums don't do value comparisons like models.TextChoices does among other things. Any elegant way to do this? form enum import Enum class YEAR_IN_SCHOOL(Enum): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' class MyModel(models.Model): year_in_school = django_model_field_choices_using_enum(YEAR_IN_SCHOOL) So that: Comparaison with the ENUM works my_model.year_in_school == YEAR_IN_SCHOOL.FRESHMAN Saving using the Enum works my_model.year_in_school = YEAR_IN_SCHOOL.FRESHMAN my_model.save()