Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No Order matches the given query
I am learning Django from book called Django 3 by example. I am following steps given in the book. But I am getting following error: Page not found (404) No Order matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/payment/process/ Raised by: payment.views.payment_process Using the URLconf defined in FlixKart.urls, Django tried these URL patterns, in this order: admin/ cart/ orders/ payment/ process/ [name='process'] The current path, payment/process/, matched the last one. views.py of payments app: def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # mark the order as paid order.paid = True # store the unique transaction id order.braintree_id = result.transaction.id order.save() return redirect('payment:done') else: return redirect('payment:canceled') else: # generate token client_token = gateway.client_token.generate() return render(request, 'payment/process.html', {'order': order,'client_token': client_token}) url patterns from settings.py of Project: urlpatterns = [ path('admin/', admin.site.urls), path('cart/', include('cart.urls', namespace='cart')), path('orders/', include('orders.urls', namespace='orders')), path('payment/', include('payment.urls', namespace='payment')), path('', include('shop.urls', namespace='shop')), ] I have tried some solutions from stackoverflow but none worked for me. Please help me solve this error. Thank you. -
How to read file stored in my computer using django view function
I have developed and deployed a Django app and trying to update the database table using a locally stored CSV file. Everything is working fine on http://127.0.0.1:8000/ or localhost but when I am deploying the app on Cpanel, the view function stops working. Here is my code: def getrate(request): if request.user.is_authenticated: if request.method == "GET" : with open("C:/djangoapp/xyz.csv", "r", encoding='utf-8-sig',newline='') as temp_raw: temp_raw_reader = csv.reader(temp_raw) for line in temp_raw_reader: rt = Rates_Detail.objects.get(product_id = 111) if rt: rt.product_rate = line[2] rt.save() user = request.user pd = Rates_Detail.objects.values() productdetails = list(pd) return JsonResponse({'status':'Save', 'productdetails':productdetails}) else: return HttpResponseRedirect("/") -
Extending JSONField and custom default value handling
I am subclassing JSONField to handle default values a bit differently. Specifically, I pass choice options (from django-choices) and build a dictionary based on this. While it works, I understandably get warnings that my new default isn't callable. How could I fix it? class ChoiceOptionsField(JSONField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.default is NOT_PROVIDED: self.default = self.get_default() def _get_default(self): default = super()._get_default() if not default and self.choices: default = dict() for option_key, option_value in self.choices: if option_key not in self.exclude: default[option_key] = { 'display': option_value 'show': True } return default I have tried setting self.default = self.get_default but that causes issues when migrating, as self doesn't exist in this context. return lambda: default also doesn't work because it doesn't want anonymous functions. -
Redirect http to https in django
I have a django project working with HTTPS using django sslserver. I want http to be redirected to https. I tried adding SECURE_SSL_REDIRECT = True in settings.py which does not seem to have any effect. Thanks in advance -
How to use CKEDITOR_THUMBNAIL_SIZE = (500, 500) ckeditor django?
Could you please advise how to use this feature CKEDITOR_THUMBNAIL_SIZE = (500, 500) ? I have tried simply to add this to my settings file but it does not work. Here it does not say much about https://github.com/django-ckeditor/django-ckeditor With the pillow backend, you can change the thumbnail size with the CKEDITOR_THUMBNAIL_SIZE setting (formerly THUMBNAIL_SIZE). Default value: (75, 75) Basically, what i am trying to achieve is to make image size uploaded by users say not bigger than 500x500. -
How do add +1 to the PositiveIntegerField model field when adding each new Post?
I have a Posts model. And field Order = models.PositiveIntegerField has been created for arbitrary sorting. Objective: in the model, overriding the save method, do add the index +1 (from the last available index of Posts) to this field when adding each new Post. That is, each post must also have an Order-index, and if there are already 3 posts on the site, then when the fourth is added, its index 4 is added to the field, and so on. Help implement this logic. It seems simple, but I don't know how to approach it. I understand that in the model I need to do this: def save(self): ** logics ** super().save() -
Form values in django formtol
I have a django formtool with 2 steps. In the first step I select from a multiselect some values and I need to take this values for a next elaboration. According some tutorial (http://blog.hayleyanderson.us/2015/07/26/passing-information-between-django-form-wizard-steps/) I take first form values but for the multiselection it takes only the last value as you can see in the pic/print. This is my code. forms.py from django import forms from station.models import Station from django.forms import formset_factory from .models import Vdl from django.contrib.auth.models import User station_all = Station.objects.all().values('station_name', 'id_station') options = () i = 0 for st in station_all: #station_all: station = (st['id_station'], st['station_name']), if i == 0: options = options + station else: options = options + station i = i+1 class VdlSelectStationsForm(forms.Form): vdl_name = forms.CharField(label='nome virtual data logger', max_length=20, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'nome vdl'})) stations = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=options) class Meta: model = Station fields = ('station_name') class VdlSelectSensorsForm(forms.Form): sensor_list_for_station = forms.ModelMultipleChoiceField(queryset=Vdl.objects.all()) #filter(id_user = id_user)) VdlSelectSensorsFormSet = formset_factory(VdlSelectSensorsForm, extra=1) views.py from django.shortcuts import render from .forms import VdlSelectStationsForm, VdlSelectSensorsForm from formtools.wizard.views import SessionWizardView, CookieWizardView from django.forms import formset_factory from .forms import VdlSelectSensorsFormSet from django.contrib.auth.models import User VdlSelectSensorsFormSet = formset_factory(VdlSelectSensorsForm, formset=VdlSelectSensorsFormSet) class VdlWizard(SessionWizardView): template_name = "vdl.html" form_list = [VdlSelectStationsForm, VdlSelectSensorsForm] def get_curr_user(self, request): current_user … -
local variable 'params' referenced before assignment in django
Here's my view def ATFinfo(Request): # inputdata = Request.GET.get('inputdata') url = 'www.google.com' req = Request.GET print("hi",req) req_list = list(dict(req).values()) print("list",req_list) params_count = len(req_list) print('params_count', params_count) if params_count > 0: for i in range(params_count): params = params + req_list[i+1][0] + '=' + req_list[i+1][1] + '&' url = url + params print('paramfinal',params) return render(Request, 'hello/ATF_Dashboard.html') In this view i'm getting error local variable 'params' referenced before assignment in line params = params + req_list[i+1][0] + '=' + req_list[i+1][1] + '&' How to solve that issue? Also i'm not able to understand what is the problem here -
How to export a csv from a search result in Django
I have a search form using django-filters and I want to export out a .csv with the filtered result. Currently it is giving me a full page of data and I am not sure how to join the 2 views together to utilize the filtering. models.py class account(models.Model): Price = models.DecimalField('price', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) User = models.CharField('user', max_length=120, blank=True, null=True,) Account_Number = models.CharField('account Number', max_length=20, blank=True, null=True,) Date = models.DateField(default=now) views.py def stage(request): slist = account.objects.all() search_list = account.objects.all() search_filter = stageFilter(request.GET, queryset=search_list) return render(request, 'stage.html', {'slist': slist, 'search': search_filter}) def export_csv(request): employees = account.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="file.csv"' writer = csv.writer(response) writer.writerow (['User', 'Account Number', 'Price', 'Date']) for employee in employees: writer.writerow([employee.User,employee.Account_Number,employee.Price, employee.Date]) return response filters.py class stageFilter(django_filters.FilterSet): Date = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = account fields = ['User', 'Account_Number', 'Price', 'Date'] urls.py urlpatterns = [ path('stage/', views.stage, name='stage'), path('export_csv', views.export_csv, name='exportcsv') ] -
Django Rest framework: Relate 2 tables
Participants Model lass Participant(models.Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) first_name = CharField(max_length=255) last_name = CharField(max_length=255) current_employing_country = CharField(max_length=255) current_payroll_country = CharField(max_length=255) # locations = ManyToManyField(Location) Location Model class Location(models.Model): participant_id = ForeignKey(Participant, on_delete=CASCADE,related_name="locations") start_date = DateField() end_date = DateField() country = CharField(max_length=255) region = CharField(max_length=255) tax_policy = CharField(max_length=255, null=True) Serializers class ParticipantSerializer(serializers.ModelSerializer): class Meta: model = Participant fields = "__all__" class LoactionSerializer(serializers.ModelSerializer): # participant_id = serializers.PrimaryKeyRelatedField(queryset=Participant.objects.all()) class Meta: model = Location tax_policy = serializers.CharField(allow_blank=True, allow_null=True) fields = "__all__" Trying to get all participants with property locations that contain array of all the locations that relate to the participant id like Participant.objects.all().prefetch_related("locations") -
Get instance.id during annotation Django
cannot make it working I need to annotate with function and for that function I need to pass the instance id qs = cls.objects.filter(**filters).values(**values).annotate( **annotations, sheets_sum=counter('sheets'), sheets_color=counter('sheets', color=True), sheets_grayscale=culc_function(color=False, id = ???), Is there any way to do it? To get instance id during annotation -
Is exist on multiple table django?
I have five models, Model1 - Primary Model Model2 - One to One with mode1 Model3 - One to Many with mode1 Model4 - One to One with mode1 Model5 - One to Many with mode1 I need to check if any data exist on each of the table, I can do that by one query each but wanted to know if there is any elegant way of checking if record exist ? Above is for django -
Ckfinder for python/django
I'm having problem with thinking how to add ckfinder plugin into my ckeditor in my django project.I could not enough information on the internet. How can I integrate ckfinder into my ckeditor in django? This question was asked previously https://github.com/ckfinder/ckfinder/issues/378 Or should I use another edtor with django like Tinymce? -
how to send request with csrf token using django mock client
I wrote and API that leverages JWT Authentication. I tested the api using postman and I am able to get the csrf cookie and acces token after the user logs in and then I am able to use these tokens to consume the endpoints of the API. For testing I use pytest-django that creates a mock database. All works when I test user registration, user login and when I consume GET endpoints. For the POST I have to send in the headers (as in Postman) the csrf token and access_token, problem is I don't understand how to send those. For example in a GET test I am able to retrieve the access token like this def test_get_signal(): form_data = { "username": "testuser", "email": "email@email.com", "password": "mytestpassword", } CustomUser.objects.create_user(**form_data) response = APIclient.post("/login/", form_data) assert response.status_code == 200 response_content = json.loads(response.content) token = response_content["access_token"] APIclient.credentials(HTTP_AUTHORIZATION="Bearer " + token) response = APIclient.get( path="/api/v1/signals/", ) assert response.status_code == 200 but I do not know how to send the csrf token in the header for the post request. For this reason (as all works in postman) I implemented an agostic way of testing that requires a live server @pytest.mark.skip_in_ci @pytest.mark.skip(reason="This test needs localhost django server … -
Automatically get all fields from my sql db to django model?
right now I'm doing (manually adding the headlines of my db as fields): class NewTables07(models.Model): TestDate = models.CharField(max_length=200) Division = models.CharField(max_length=200) Library = models.CharField(max_length=200) ID = models.CharField(max_length=200) ################# MONOGRAMS ######################## ... class Meta: db_table = 'stat_cat1' I was wondering if there's a way to automatically get all the headlines of my SQL table to my models without having to enter them manually? -
I get an error while running requests_html render function in django enviroment
I highlighted that it happens in django enviroment,because when I run similar scripts with this function outside of django server it works fine. I'm trying to do something like this: from requests_html import HTMLSession session = HTMLSession() page = session.get('https://python.org/') page.html.render() but when I run this code through django server, I get something like this(actual error is very long, so I cut all irrelevant pieces) There is no current event loop in thread 'Thread-1'. ... File "/Users/mac/Desktop/sogo-sakata/papi/seoparser/schema.py", line 28, in titles result = analize(url) File "/Users/mac/Desktop/sogo-sakata/papi/seoparser/utilities.py", line 91, in analize page.html.render() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests_html.py", line 586, in render self.browser = self.session.browser # Automatically create a event loop and browser File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests_html.py", line 727, in browser self.loop = asyncio.get_event_loop() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/events.py", line 642, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' RuntimeError: There is no current event loop in thread 'Thread-1'. Stack (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 930, in _bootstrap self._bootstrap_inner() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 747, in __init__ self.handle() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 178, in handle … -
im trying to write a custom user model and when i try to migrate i keep getting this error :
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/migrations/loader.py", line 295, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency Occupier.0001_initial on database 'default'. -
ValueError: "<User: harry1>" needs to have a value for field "id" before this many-to-many relationship can be used in Django
I need help with Django web Framework I cannot solve this problem or I cannot identify the source of the problem. Please help me with this problem the main problem is written in the title. Here is my traceback for the error: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Documents\CodingFox\CodingFox_final\CodingFox\Users\views.py", line 37, in registeration_form form.save() File "D:\Documents\CodingFox\CodingFox_final\CodingFox\Users\forms.py", line 18, in save user = super().save(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\forms.py", line 131, in save user.save() File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 536, in __get__ return self.related_manager_cls(instance) File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py", line 851, in __init__ raise ValueError('"%r" needs to have a value for field "%s" before ' ValueError: "<User: harry1>" needs to have a value for field "id" before this many-to-many relationship can be used. Models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse import cv2 class Profile(models.Model): user =models.OneToOneField(User, on_delete=models.CASCADE) cover_img = models.ImageField(default='default.png',upload_to='cover_pics') image = models.ImageField(default='default.jpg',upload_to='profile_pics') # bio = models.TextField() def __str__(self): return f'{self.user.username} Profile' def save(self ,*args, **kwargs): super(Profile, self).save( *args, **kwargs) img = cv2.imread(self.image.path) output_size = cv2.resize(img,(300,300)) cv2.imwrite(self.image.path, output_size) Forms.py from django import forms from django.contrib.auth.models import User … -
Reverse for '' not found Django
Can't find the problem #my urls path("office", views.office, name="office") #my views def office(request): offices_list = Office.objects.all() context = {'offices_list': offices_list} return render(request, "auctions/office.html", context) #my html <li class="nav-item"> <a class="nav-link text-white " href="{% url 'office' %}">office</a> </li> Reverse for '' not found. '' is not a valid view function or pattern name. -
Toggle boolean fields from a Queryset using 'not F()'
I added a new action to toggle Users is_staff property. But I noticed that using the method below, can only toggle from True to False. The other way round doesn't seem to work(ie. from False to True). admin.py from django.db.models.expressions import F actions = ['toggle_staff'] def toggle_staff(self, request, queryset): queryset.update(is_staff= not F('is_staff')) Please, I need help here. -
How to get value from HTML user input in django view?
Hello everyone I have an HTML form as follows: https://jsfiddle.net/ritzlucky13/z627Lrm3/ and after clicking on post i am redirecting it to views.py. can any one tell me how to get the field values of all the fields of the form into views.py. here's the output i want the field value in key value pair like shown in above pic i.e. API=hello&Area=hello1 so on... i know we can do that using this if html: <div class="form-group col-md-2"> <label for="param">TAF Parameter</label> <input type="text" name="inputdata_API" class="form-control" id="inputapi_param" value="API" readonly> </div> and view: def register(request): api = request.GET.get['inputdata_API'] But in that case i have to write each and every input name in my view -
Django won't authenticate user
I just upgraded django, from 1.11 all the way to 3.2, and my custom authentication backend won't work now. settings.py: AUTHENTICATION_BACKENDS = ( 'apps.base.auth.PasswordlessAuthBackend', ... ) apps/base/auth.py: class PasswordlessAuthBackend(BaseBackend): def authenticate(self, username): try: return User.objects.get(username=username) except: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None views.py: def test_login(request): my_username = 'my_user' authorized_user = authenticate(username=my_username) print(authorized_user) u = User.objects.get(username=my_username) print(u.username) Output from views.py: None my_username I've tried everything and really can't get my head around this. I'm positive it's loading the PasswordlessAuthBackend class, since if I change its name I get an ImportError in settings.py. -
why can't hide slug field in django admin?
when i try to exclude 'slug' field in django admin form,i got this msg: "KeyError at /admin/post/post/add/ "Key 'slug' not found in 'PostForm'. Choices are: author, content, image, title." why? django code: model: models.py : from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Post(models.Model): title= models.CharField(max_length=50,null=False,blank=False) content= models.TextField(max_length=2000,null=False,blank=False) image= models.ImageField( upload_to="post-img/") created_at=models.DateTimeField(default=timezone.now) author=models.CharField(max_length=50,null=True,blank=True) slug=models.SlugField(max_length=30) class Meta: verbose_name =("Post") verbose_name_plural =("Posts") def __str__(self): return self.title def get_absolute_url(self): return reverse("PostDetail", kwargs={'slug': self.slug}) def headline(self): return self.content[:50]+'...' admin.py : from django.contrib import admin from .models import Post # Register your models here. class PostAdmin(admin.ModelAdmin): exclude=('created_at','slug',) # fieldsets=(({'fields':('title','content','image',)}),) list_display=['title','headline','author','created_at'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Post,PostAdmin) thank you ! -
how to serilize a json object in drf
I have two serializers like this : class UsersInfoSeriliazerByUsers(serializers.ModelSerializer): class Meta: model = FreeTime fields = '__all__' class SetTimeZoneSerializer(serializers.Serializer): TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones)) meeting_date = serializers.DateField(format="%d-%m-%Y", input_formats=['%d-%m-%Y', 'iso-8601']) time_zone_destination = serializers.ChoiceField(choices = TIMEZONES) time_table = UsersInfoSeriliazerByUsers(many=True,read_only=True) emails = serializers.ListField(child=serializers.EmailField()) in views.py i need to get filter queryset from freetime model and serilize the result query it again : def common(self,request): serializer = SetTimeZoneSerializer(data = request.data) if serializer.is_valid(): j={} j['meeting_date']=serializer.data['meeting_date'] j['time_zone_destination']=serializer.data['time_zone_destination'] j['time_table'] = UsersInfoSeriliazerByUsers(FreeTime.objects.all(), many=True).data json_string = json.dumps(j) serializer = SetTimeZoneSerializer(json_string, many=True) It creates json_string successfully and i printed it in terminal but i got this error : Internal Server Error: /api/time/common/ Traceback (most recent call last): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'str' object has no attribute 'meeting_date' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception … -
How to update self.request.user field in django rest framework?
I need to update the requested user field when I create the organization from OrganizationViewSet as below, class OrganizationViewSet(viewsets.ModelViewSet): queryset = Organization.objects.all() serializer_class = OrganizationSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): serializer.save(admin_user=self.request.user) data = serializer.data org_id = data['id'] self.request.user.update(organization=org_id) # Error is coming from this line The above code generates the following error, 'User' object has no attribute 'update' So my question is, how can I update the requested user organization? Any help?