Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to replace LocaleRegexURLResolver from django 1.11
I am currently upgrading Django from 1.11 to 2.0 (to 2.2 in the long run). But recently I bumped into a problem which a can't solve for quiet some time. LocaleRegexURLResolver has been removed in 2.0 without any warning and the whole code has been refactored. Sadly we were using LocaleRegexURLResolver and I am not sure how to replicate it's functionality in the current version of Django. Any ideas? class SiteLocaleRegexURLResolver(LocaleRegexURLResolver): """ Overrides LocaleRegexURLResolver to use specified default language by site instead of global default language """ def __init__( self, urlconf_name, site, default_kwargs=None, app_name=None, namespace=None, prefix_default_language=True ): super(LocaleRegexURLResolver, self).__init__( None, urlconf_name, default_kwargs, app_name, namespace, ) self.prefix_default_language = prefix_default_language self.default_language = site.language_code @property def regex(self): language_code = get_language() or self.default_language if language_code not in self._regex_dict: if language_code == self.default_language and not self.prefix_default_language: regex_string = '' else: regex_string = '^%s/' % language_code self._regex_dict[language_code] = re.compile(regex_string, re.UNICODE) return self._regex_dict[language_code] Basically it changes the default language. In UK, site /docs/ would be in english and /fr/docs/ in french. In FR on the other hand, /docs/ would be in french and /uk/docs/ in english -
Django in line advertising
I want to put an ad in the article by dividing the article, like this bla bla bla bla bla bla bla bla bla bla ADS bla bla bla bla bla I searched but couldn't find anything. Do you have any suggestions? getting content with this code <p class="content"> {{ post.content|safe }} </p> -
Set Authorization Token in request header of GET route in django
I'm trying to access the below URL using HTTPResponseRedirect which is protected by Django_restframework_simplejwt. I would like to redirect to below URL after the signup success, for the email and mobile verification. http://base_url/acc_verification Assuming, I do have an access token, Now, How do I set the Authorization token in the request header to load the above page. Authorization: Token Python - 3.6.8 Django - 2.2.3 djangorestframework_simplejwt - Latest -
How to return images from restfulapi in django
i wanted to retrieve images in django from db. But as path of image will be stored in db i am not able to fetch the image from the retrieved path.is there any way to solve this in django -
How to return the processed form data to the template without saving it to the database?
I am making an English grammar checker. I have two models Sentence and Error. The user will input a sentence in the form and the errors (if any) will be generated and attached to the sentence programatically. Now I have two types of users: free and paid. I don't want to save the results to the database for the free accounts. How can I display the results in the template without saving them to the database? # noting gets displayed in the template with this code ... if request.method == 'POST': form = SentenceForm(request.POST) if form.is_valid(): cd = form.cleaned_data form.save(commit=False) sent_str = cd['sent'] s = Sentence(sent=sent_str, sent_correct=sent_str) s.author = user # s.save(commit=False) --- This line throws an error if user.is_basic or user.is_standard or user.is_premium: s.save() sent = nlp(sent_str) sents = [] subjs = [t for t in sent if t.dep_ in subj_ls] two_subj = False if len(subjs) >= 2: two_subj = True if not subjs: has_imp_patt = imp_patt(sent) if has_imp_patt: pass else: print('Line 60') msg = '<span style="color:#be0000">Subject\\verb not found</span>' m = Message(msg=msg, sent=s) if user.is_basic or user.is_standard or user.is_premium: m.save() form = SentenceForm() return render(request, 'home.html', {'sentences': sentences, 'form': form}) ... -
app.yaml configuration for websocket django app
WebSocket works in the development server but not in the Google cloud. the official docs provide WebSocket example in flask. did not get in django? think the cause of the error is "entrypoint:" variable in app.yaml? app.yaml # [START runtime] runtime: python env: flex entrypoint: gunicorn -b :$PORT myproject.wsgi:application beta_settings: cloud_sql_instances: project-id:region:instance-name runtime_config: python_version: 3 # [END runtime] settings.py ASGI_APPLICATION = "myproject.routing.application" # channels CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { # "hosts": [("localhost", 6379)], "hosts": [("redis-ip", port)] }, "ROUTING": "myproject.routing.application", }, } routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from app.consumers import NoseyConsumer application = ProtocolTypeRouter({ "websocket": URLRouter([ path("path/", NoseyConsumer), ]) }) in google cloud it rise an error "failed: Error during WebSocket handshake: Unexpected response code: 404". -
In Django REST Framework, how to initialize a field value for a createAPIView based on the GET query parameter?
I know how to get the query parameter in View or Serializer by: request.GET.get(query_param_key). I also know we can use it to do sorts of things like filtering the query set for a ListView, but, I just couldn't figure out how it can be used to initialise a field in a CreateView, or any legit place to just keep or hold this information so that it could be used later when POSTing to set the default value for a field. For example, if the url of the page to create a "product" is: http://localhost:8000/myapp/create_product/?item_id=1 The serializer of the "product" has a foreign field "item", which would like to be initialised with item's id = 1 when the above creation page is called with this parameter. Obviously, there isn't any place other than this query parameter that has the information "item_id=1", so either needs a way to initialise the "item" field, or there is a suitable place to hold this information to use it when POSTing. But I don't know how this can be achieved. The html template for the "create_product" page is a very basic one using render_form: {% extends "base_generic.html" %} {% load rest_framework %} {% block content %} … -
Django urls giving me different direction
I am working on Django project where I am implementing the in-build authentication framework. I created urls directly to in-build views. I am supposed to visit the following url http://127.0.0.1:8000/account/login/ which redirects me to the following urls and supposed to choose 'LoginView' and it's corresponding template urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('', views.dashboard, name='dashboard'), ] Here is the template code {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. please try again. </p> {% else %} <p>Please, use the following form to log-in: </p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{form.as_p}} {% csrf_token %} <input type="hidden" name="next" value="{{next}}"> <p><input type="submit" value="Log-in"></p> </form> </div> {% endblock %} when I submitted the credentials I am getting the following error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ Using the URLconf defined in xxxxxxxxxx.urls, Django tried these URL patterns, in this order: admin/ account/ The current path, accounts/profile/, didn't match any of these. Please help me with this. -
Queryset which returns only objects with a foreign key assigned.Django
I'm trying to find a simple way to return objects which have a foreign key assigned to each other. For example, I have such models.py file: class Parent(models.Model): name = models.CharField(max_length=100) class Children(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) name = models.CharField(max_length=10) For my parent I create objects family1, family2, family3. And for my children I create the object John and Stefani which is related with a foreign key from family1. How easiest to create queryset which returns only family1(only once, even though it has many related objects) Any help will be appreciated. Sorry for my bad English. If the question is not understood, I will write additional explanations. -
reroute invalid urls back to home in django
Using localhost:8000/admin/ and localhost:8000/ work fine But I want to ignore other meaningless links like localhost:8000/adm and make them route back to localhost:8000/ permanently.. from django.urls import path from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView from API import views from API.views.Home import HomeView urlpatterns = [ path('grappelli/', include('grappelli.urls')), # grappelli URLS url(r'^admin/', admin.site.urls), url(r'^v1/', include('API.urls')), url(r'',HomeView.as_view(),name='HomeView'), ] any idea ? can this be simply achieved by regex? more examples... of what I want to achieve localhost:8000/anything -> localhost:8000/ localhost:8000/anything/ -> localhost:8000/ localhost:8000/admin/anything -> localhost:8000/admin/ localhost:8000/admin/anything/ -> localhost:8000/admin/ in short, I want to get rid of excess url parts... so they don't even show in the browser, a 5xx redirect. it would be easily done in nginx, but wanted to know if this is easily done in django directly. -
how to connect remotly pyodbc to sql server
i have an sql server that i need to have a remote connection between it and pyodbc. i tried to test the connection locally and i works once i tried to use it on remote server it crashs and display the error below. where i have the below settings. connection = pyodbc.connect('Driver={SQL Server};' 'Server=AB-INT-SQL\MSSQLSERVER;' 'Database=testDB;' 'trusted_connection=yes;') but once i tried to connect it display the below error : Operational error :[odbc sql server dirver] invalid connection string attribute (0) -
DRF nested serializer not able to updated nested data
I'm using Django 2.x and Django REST Framework. I have a nested serializer set. class ListFieldSerializer(serializers.ModelSerializer): class Meta: model = ListField fields = [ 'id', 'name', 'field_type' ] class LeadListSerializer(serializers.ModelSerializer): list_fields = ListFieldSerializer(many=True, source='list_field') class Meta: model = LeadList fields = [ 'id', 'lead_id', 'name', 'list_fields', ] @transaction.atomic def create(self, validated_data): list_fields = validated_data.pop('list_field', None) lead_list = self.Meta.model.objects.create(**validated_data) if list_fields: # Create fields for field in list_fields: ListField.objects.create( lead_list=lead_list, **field ) return lead_list @transaction.atomic def update(self, instance, validated_data): list_fields = validated_data.pop('list_field', None) if list_fields: list_fields_dict = dict((i.id, i) for i in instance.list_field.all()) for field in list_fields: if 'id' in field: # If exists id, remove from the dict and update field_item = list_fields_dict.pop(field['id']) field_item.name = field.get('name', field_item.name) field_item.field_type = field.get('field_type', field_item.field_type) field_item.is_required = field.get('is_required', field_item.is_required) field_item.order = field.get('order', field_item.order) field_item.save() else: # Create a new object ListField.objects.create(lead_list=instance, **field) return super().update(instance, validated_data) This is working fine for POST request. But when I send PATCH request with the following data, the id field is not retrieved in the serializer update() method and instead of update, it is creating a new instance for the fields. { "name":"New name", "list_fields": [ { "id": 8, "name": "Email" } ] } -
Add calculated data to a serializer
I have a serializer in my django rest framework: Serializers.py class rfqserializer(serializers.ModelSerializer): class Meta: model = Quiz fields = "__all__" Views.py class rfqview(viewsets.ModelViewSet): serializer_class = rfqserializer queryset = Quiz.objects.filter(Q(status="Hold") | Q(status="Active")) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) print("request.user", request.user) queryset = queryset.filter(owner_id=request.user) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) #Can I update this in the serializer ? ** for i in queryset: bid_queryset = TakenQuiz.objects.filter(quiz_id=i.id).count() print("t type",bid_queryset) ** return Response(serializer.data) I want to send the count of attribute of another model with this serilaizer. Can I do this ? -
Execute "select_for_update" with Django ORM in loop.run_in_executor
Env: python - 3.6.4 django - 2.1.7 DB - mysql Sample: from django.db import transaction async def some_method(): with transaction.atomic(): obj = await loop.run_in_executor( None, lambda: models.ModelName.objects.select_for_update().get(id=obj_id) ) # do other stuff Following error is thrown: raise TransactionManagementError('select_for_update cannot be used outside of a transaction.') django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction. Similar code could be ran without error: async def some_method(): with transaction.atomic(): obj = models.ModelName.objects.select_for_update().get(id=obj_id) # do other stuff And any other query without select_for_update() could be done in loop.run_in_executor e.g. obj.save() Context: As an experiment I try to "migrate" Django application to aiohttp with keeping Django ORM. (please do not ask "why" - it's as experiment) Questions: Is it possible to call select_for_update() in run_in_executor or in other method? if I call obj.save() and obj2.save() in loop.run_in_executor is it indeed ran in same transaction like: async def some_method(): with transaction.atomic(): await loop.run_in_executor( None, obj.save ) await loop.run_in_executor( None, obj2.save ) Purpose: let's assume that call to DB takes 2 seconds (just assume, reason could be: connection or non-optimized DB, whatever) - I need to call DB without blocking.(I know that there are several "async" ORM libraries for Mysql, but I try to keep Django ORM) -
How to detect redirection in Django view
I have a view that returns a redirection. return redirect(reverse('my-view-name')) Is it a way to detect redirection inside a view method? I've searched in request object attributes but couldn't find any one that indicates redirection. -
Where does Django-Channels store user's channel names?
I am trying to add a user to a django channels group but I do not know the user's channel name. Only their database id/username. I have been reading through channels' documentation but was not able to discover where these channel names are stored. Normally, from within a channel's communicator, I can add the user of the communicator to a group with: class OrderConsumer(AsyncJsonWebsocketConsumer): def __init__(self, scope): ... async def connect(self): ... async def add_user_to_group(self, group_name): await self.channel_layer.group_add( group=group_name, channel=self.channel_name ) Is it possible to access another user's "self.channel_name" via the database? or otherwise? If so how? I am using an InMemoryChannelLayer for my tests: TEST_CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } but a redis database (with the help of channels-redis) in my live deployment. Will this make a difference? -
Django: building a tree from existing model
I have already a list of products, which follow a hierarchy (with their unique product ID): 0000 ; 1000 ; 1100 ; 1110 ; 2000 ; 2100 ; 2110 I want to display these products under a tree. I have installed django-mptt, done the tutorial and read the doc but I have no idea how to implement it to my situation. Should I use mptt to build the tree or should I create the tree directly in a template? -
How to create your own hash sha3 in django?
I can not add my hash(sha3_512) using hashlib in django. My password is hashing 2 times:by me and by django automatically. def hashing(password): password = hashlib.sha3_512(password.encode('utf-8')).hexdigest() return password I want to disable django hashing and use only my function. -
Django - needs to have a value for field "id" before this many-to-many relationship can be used
I have two serializers class CheckItemSerializer(serializers.ModelSerializer): class Meta: model = CheckItem fields = ( 'item_name', 'amount', ) class PaymentActionSerializer(serializers.ModelSerializer): items = CheckItemSerializer(many=True, required=False) class Meta: model = PaymentAction fields = [ 'booking_number', 'date', 'guest_name', 'isRefund', 'lcode', 'payment_type', 'positions', 'total', 'items', 'id' ] def create(self, validated_data): action = PaymentAction.objects.create(**validated_data) action.save() if validated_data.get('items', None) is not None: items = validated_data.pop('items') if items is not None: for item in items: item_name = item['item_name'] amount = item['amount'] new_item = CheckItem.objects.create( item_name=item_name, amount=amount ) new_item.save() action.items.add(new_item) action.save() return action and json {"lcode": 123, "total": 1, "isRefund": false, "booking_number": "333", "guest_name": "me", "positions": "1 night", "date": "2019-07-22 00:00", "payment_type": "nal", "items": [ { "item_name": "glazka", "amount": "100" }, { "item_name": "glazka2", "amount": "150" } ] } and I get error "<PaymentAction: PaymentAction object>" needs to have a value for field "id" before this many-to-many relationship can be used. What am I doing wrong ? -
How to show Balance in html page for each user using django? [duplicate]
This question already has an answer here: How to show the payment which is assigned to user in html page of django? 1 answer I have a very simple question and this is also a duplicate but people who answered didn't understand. I am struggling to show the balance of each user in html page. Whenever a person login, his/her balance should be shown in browser.The result I am getting is just Your Balance is. After that nothing is showing. But people who answered they sum up the balance and I want to show each user his/her own balance which I have stored in database. How to do it? models.py class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=1) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py @login_required def balance(request): total_amount = Balance.objects.all() for field in total_amount: field.amount context = { 'total_amount': total_amount } return render(request, 'users/balance.html') Html page <h2>Your Balance is: {{total_amount.amount}}</h2> -
ChoiceAdmin inline not displaying (Django official tutorial part 7)
I'm doing the Django official tutorial and after editing the admin.py file to add and edit choices for poll questions my code is not working as expected. No error messages were displayed. Tried restarting the test server, clearing the DB (sqlite3) and deleting site data in the browser. Contents of admin.py: from django.contrib import admin from .models import Choice from .models import Question class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] admin.site.register(Question, QuestionAdmin) My "Add Question" page: https://imgur.com/m1a49gB Expected result: https://docs.djangoproject.com/en/2.2/intro/tutorial07/#adding-related-objects -
Django formtools with custom template
I have the following custom wizard <div class="container"> <div id="smartwizard"> <ul> <li><a href="#step-1">Engagement Setup<br /><small>Basic info</small></a></li> <li><a href="#step-2">File Upload<br /><small>Upload files</small></a></li> <li><a href="#step-3">Business Rules<br /><small>rules</small></a></li> <li><a href="#step-4">Documentation<br /><small>documentation</small></a></li> </ul> <div> <div id="step-1" class=""> <div id="form-step-0" role="form" data-toggle="validator"> <div class="form-group"> <label for="text">Code <span class="tx-danger">*</span></label> <input type="text" class="form-control" name="code" id="code" placeholder="Write your code" required> <div class="help-block with-errors"></div> </div> </div> <hr /> </div> .... </div> </div> <br /> </div> I have setup the django form as such class PageOne(forms.Form): ibs_code = forms.CharField(max_length=100) engagement_name = forms.CharField(max_length=100) engagement_manager = forms.CharField(max_length=100) engagement_partner = forms.CharField(max_length=100) solution = forms.CharField(label='What solution would you like to use?', widget=forms.Select(choices=FRUIT_CHOICES)) And of course the views.. class TestWizard(SessionWizardView): file_storage = FileSystemStorage( location=os.path.join(settings.MEDIA_ROOT, 'temp_uploads')) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_done = False def get_template_names(self): if self.is_done: # return [self.templates['done']] return [TEMPLATES['done']] else: return [TEMPLATES[self.steps.current]] ..... ...... Now I want to use the custom template with the form. Meaning, I want to generate the form fields the way the html/style looks with form-group and such. How can I achieve this? I tried the documentation but they weren't any sources for custom templating -
Showing key error at the backend of django when i am receiving data
I want to record audio and send that audio blob to django backend to do some processing.I am using recorder.js for the recording part but it is showing key error while retrieving that blob i am using xmlhttprequest to send that blob but it is not working Javascript Code: var upload = document.createElement('a'); upload.href="show/"; upload.innerHTML = "Upload"; upload.addEventListener("click", function(event){ var xhr=new XMLHttpRequest(); xhr.onload=function(e) { if(this.readyState === 4) { console.log("Server returned: ",e.target.responseText); } }; var fd=new FormData(); var csrftoken = Cookies.get('csrftoken'); fd.append("audio_data",blob, filename); xhr.open("POST","/show/",true); xhr.setRequestHeader("X-CSRFToken", csrftoken); xhr.send(fd); }) urls.py : urlpatterns = [ path('admin/', admin.site.urls), path('',views.getmain), path('show/',views.solve) ] views.py" def solve(request): print("post post") file = request.FILES['audio_data'] print(file.size) return render(request,'display.html') -
Post method in django
I had a tutorial in django with forms and I tried to do exactly what is taught , but I found that either my form in not sending the post method or django can't realize that the request sent is a POST request here is my file named "register.html": {% extends "blog/base.html" %} {% block content %} <div class="content-section"> <form role="form" method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %}</code> and here the django side views.py: <code>from django.shortcuts import render , redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register (request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html' , {'form': form})</code> the result is when I click submit , the POST method is not working , I tried to pass a get request and it worked , so the problem only appears when I try to send the POST request , so where is problem … -
Django: separation of settings for development at production with asgi server
In the process of separating the settings, I encountered a problem on the production server. I implemented a structure with a new folder settings and added 3 files to it: base.py, production.py, development.py. I also changed the manage.py file to run the required configuration on the local machine by adding the following line: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lifeline.settings.development") On production, I use the daphne server to work with channels. The project has an asgi.py file with import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lifeline.settings.production") django.setup() application = get_default_application() Everything works fine on the local machine. The problem is that in production I get 502 errors and in asgi logs I see that the problem is in importing and the sixth line of code with the value django.setup() File "./lifeline/asgi.py", line 6, in <module> django.setup() File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/Env/lifeline/lib/python3.6/site-packages/django/conf/__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty