Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send a specific Mailgun email template from django application?
I am implementing mailgun with a django application and thinking about the logic. Firstly, I thought about creating templates in mailgun and when the cronjob takes place - it gets the recipient list and downloads the related template and off it sends. However, two issues arose along the way. First of all, when downloading the template with a function provided by mailgun, def get_template(template_name): return requests.get( "https://api.mailgun.net/v3/mydomain/templates/{0}".format(template_name), auth=("api", "mykey")) instead of the actual html (which is needed for the send_mail function it returns <Response [200]>. Nevertheless, if a template will contain eg images or other attachments, it would create unnecessary traffic due to the downloading. So now I am thinking about somehow specifying the template and other required attrs and sending it to mailgun which would send the email. However I cannot find a function or any solution (I'm looking for example here) that would allow me to specify the template eg ... data={'recipients': 'some list', 'template': 'template001', ... I would much appreciate any thoughts on this or any suggestion or hint. -
How can I call collectstatic routine inside a django app?
My Django app works with css/html themes and I can upload new themes from the user interface, that is, a regular user can upload a new theme without asking for a IT guy. I usually call a os.run('python manage.py collectstatic') but I would like to know if it is possible to do it in a more elegant or pythonic way. -
Handle List of objects passed to django template in jQuery for Ajax call
I have my views.py function as below: def method(request): objects = Model1.objects.all() return render(request, 'manager/link.html', {'objects': object}) In my template, link.html I have the below code: <script> $('#nav').on('click', function (event) { $('#stock_holdings').text('Loading...'); var stocks = ({{ stocks|get_list|safe }}); $.ajax({ type: "GET", url: '{% url 'broker:load_data' %}', data: { 'stocks': stocks, }, dataType: 'json', success: function (data) { $('#stock_holdings').text(data['stocks_details']); } }); }) ; </script> where get_list is a custom tag to convert the queryset into a list of objects: @register.filter def get_list(queryset): return list(queryset) However I get the below error when the code is run and I see its due to this in the browser debug window: Error: Uncaught SyntaxError: Unexpected token '<' Line causing the error: var stocks = ([<broker: stock1>, <broker: stock2>]); It looks like the '<' in the list of objects is causing the error. Could someone please help on how to handle this? -
Why doesn't Django load my javascript file correctly?
I am new to Django and I'm trying to implement drag and drop file uploading using dropzone.js. I was follow this tutorial to start of with. Dropzone is working fine and the file is being uploaded and stored correctly, my issues comes with the customization of the dropzone instance. I created a second javascript file to create my custom dropzone like the tutorial showed and included it into the django template. But for some reason this does not change anything, with or without customization javascript file, the dropzone looks exactly the same. The javascript file: Dropzone.autoDiscovery = false; const dropzone = new Dropzone("#drop", { dictDefaultMessage = "Upload your PDF here", clickable: false, url: "/upload", maxFiles: 1, acceptedFiles: ".pdf", }); The django template file I'm trying to include the script into: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PDF2Notes</title> </head> <body> <form method="POST" action="/upload" class="dropzone dz" id="drop"> {% csrf_token %} <div class="fallback"> <input name="file" type="file"> </div> </form> <!--default stylesheet--> <link rel="stylesheet" type="text/css" href="{% static 'converter/style.css' %}"> <script type="text/javascript" src="{% static 'converter/main.js' %}"></script> <!--dropzone js & css--> <link rel="stylesheet" tpye="text/css" href="{% static 'converter/dropzone/dist/dropzone.css' %}"> <script type="text/javascript" src="{% static 'converter/dropzone/dist/dropzone.js' %}"></script> </body> </html> My static file directory is setup correctly, … -
Django deployment with Docker on EB failed and 502 badgateway
Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY ./config/requirements.txt . RUN pip install -r requirements.txt COPY . . docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0:8000 ports: - '8000:8000' depends_on: - db - redis db: image: postgres environment: - POSTGRES_USER=postgres_test - POSTGRES_PASSWORD=postgres_test_pw redis: image: redis ports: - '6379:6379' and in vscode terminal eb init -> choose docker , Docker running on 64bit Amazon Linux 2 eb create -> application balancer type and when "eb open" i got 502 badgateway what should i do -
Django & PostgreSQL is making Server response very slow
When we are doing changes in the code of CSS or python Django, sometimes the changes are reflecting after 15-20 min. but when we restart the web server the changes reflect. so is there any setting in Django to store or release Cache Memory or Virtual Memory that is making the code changes response slower? -
Django channels + celery: Handler is called on exception, fails to be called for a second time
I have an api endpoint that triggers a celery task, when it's done, it writes a result into a AsyncWebSocketConsumer group (Only one user will be on it). This goes well on all successful tasks, but if a task fails due to an exception, it will send a failure event the first time and it will be sent via the websocket (As expected), but it will fail to do it a second time. class ConversionConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope["user"] self.awaiting_for_conversion = None if self.user.is_anonymous: await self.close() return await self.accept() async def disconnect(self, close_code): if self.awaiting_for_conversion: await self.channel_layer.group_discard( self.awaiting_for_conversion, self.channel_name ) async def receive(self, text_data): try: action = json.loads(text_data) # the user has to send a message asking for the conversion he wants to receive information on if action['type'] == 'await_for_conversion': self.awaiting_for_conversion = action['payload']['uid'] await self.channel_layer.group_add( self.awaiting_for_conversion, self.channel_name ) except: pass async def conversion_succeded(self, event): uid = event['uid'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'status': 'SUCCESS', 'type': 'conversion_has_finish', 'uid': uid })) async def conversion_failed(self, event): # This will be called the first time an exception is raised and caused the task to fail, but not if another task is called and fails the same way uid = event['uid'] … -
Working on Django forms, I will like to use input field as variable for a regular expression function? not working as I have it
passing input of form search = form.cleaned_data["search"] return get_search(request,search, list1) *using input form as variable def get_search(request,search, list): # convert list to string for re entries = str1.join(list) # using pattern to match items in my string?? re pattern = re.compile(r'{}.*.format(search)', re.IGNORECASE) matches = pattern.finditer(entries) # ** passing variables to a new template but it is not working!! return render(request, "encyclopedia/search.html", { "matches": matches }) -
Remove empty spaces in assertDictEqual to pass Flake8
I'm fixing code to normalize in PEP8 by Flake8. One of the problems is long lines that I need skip lines to accomplish Flake8. This is my return that I skip line using : expected_return = { "error": { "message": None, "type": "You are logged as admin. This endpoint requires\ a customer or an anonymous user.", "detail": None, } } Using from django.test import TestCase with Django, my assertion is: self.assertDictEqual(self.deserialize(response.content), expected_return) My test don't pass because the assert reads with spaces: AssertionError: {u'error': {u'message': None, u'type': u'You are logged as admin. This endpoint [truncated]... != {u'error': {u'message': None, u'type': u'You are logged as admin. This endpoint [truncated]... {u'error': {u'detail': None, u'message': None, - u'type': u'You are logged as admin. This endpoint requires a customer or an anonymous user.'}} + u'type': u'You are logged as admin. This endpoint requires a customer or an anonymous user.'}} I tried to use self.assertMultiLineEqual too, but other errors appers. What solutions usually you use to skip lines, in accordance to PEP8 and do not receiving with this error with unittest? Best regards. -
Get user's last login time in Django using LDAP Authentication
I tried user.last_login in order to get the last login time for LDAP user. But i'm receiving null value although user has done login several times. It works for Django users like admin. Is there any way around this? -
Is it possible translate URL's with Rosetta?
Is it possible to translate the URLs with Rosetta? Example: Spanish: domain.com/es/contacto English: domain.com/en/contact Check that Contact has the translation in the Spanish URL. Many thanks Alfredo -
Django Forms Invalid but no Errors
Maybe it might be an oversight but I do not know the point where I am getting it wrong. My form is rendered correctly but it keeps failing without errors. forms.py from crispy_forms.helper import FormHelper from django import forms from django.utils.translation import ugettext as _ class BeneficiaryForm(forms.Form): """Add Beneficiary template form""" # Form fields account_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), empty_label=_('Select account currency')) bank_account_type = forms.CharField(max_length=50, required=False) email = forms.CharField(max_length=150, required=False, help_text=_("We'll notify them when a transfer is made")) name = forms.CharField(max_length=50, required=False) swift_code = forms.CharField(max_length=11, required=False, widget=forms.TextInput(attrs={'placeholder': 'MSBCCNBJ001'})) iban = forms.CharField(max_length=34) def __init__(self, *args, **kwargs): super(BeneficiaryForm, self).__init__() self.helper = FormHelper() self.helper.form_show_labels = False views.py def beneficiaries(request): """View function for viewing Beneficiaries and adding a Beneficiary instance""" if request.method == 'POST': form = BeneficiaryForm(request.POST) if form.is_valid(): print("Form is valid") print(request.POST['bank_account_type']) print(request.POST['email']) print(request.POST['name']) print(request.POST['iban']) print(request.POST['swift_code']) print("Form is invalid") print(form.errors) form = BeneficiaryForm() context = { 'form': form } return render(request, 'dashboard/beneficiaries.html', context) and in my rendered form. I have this block to show errors and nothing shows up -
django.db.utils.IntegrityError: NOT NULL constraint failed fom Postman
I am trying to create a simple model with foreign keys using Django rest framework. This are the models: class Route(models.Model): place_origin = models.ForeignKey( Place, null=False, on_delete=models.DO_NOTHING) class Place(models.Model): name = models.CharField(max_length=50, null=False) This are the serializers for each model: class PlaceSerializer(serializers.ModelSerializer): class Meta: model = Place fields = ["id", "name"] class RouteSerializer(serializers.ModelSerializer): place_origin = PlaceSerializer(many=False, read_only=True) class Meta: model = Route fields = ["id", "place_origin"] This RouteSerializer has the place_origin property in order to show the place details(all the fields from it) when I am looking at the route detail. What I mean is for routes I want to display: [ { "id": 1, "place_origin": { "id": 1, "name": "New york" } }, { "id": 2, "place_origin": { "id": 2, "name": "Boston" } } ] And not just: [ { "id": 1, "place_origin": 1 }, { "id": 2, "place_origin": 2 } ] This is the view: @api_view(['POST']) def routes_new_route_view(request): """ Create a new route """ if request.method == "POST": data = JSONParser().parse(request) place_origin = Place.objects.get(id=data["place_origin"]) data["place_origin"] = PlaceSerializer(place_origin) data["place_origin"] = data["place_origin"].data serializer = RouteSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) else: return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I want to send the request from postman this way: { "place_origin": 3 } But … -
Reverse for 'create_chat' with arguments '('',)' not found. 1 pattern(s) tried: ['create_chat/(?P<id>[0-9]+)/$']
I am building chat app and I am using Django Version 3.8.1. I am stuck on Error. This view is for Chat with friend private. views.py def create_chat(request,id): from_user = get_object_or_404(User,id=id) user1 = request.user user2 = from_user chat_box = ChatBox(user_1=user1,user_2=user2) chat_box.save() urls.py path('create_chat/<int:id>/',views.create_chat,name='create_chat'), profile.html <a href="{% url 'create_chat' from_user.id %}">Chat</a> The Problem When i open profile.html in browser this error is occured named :- Reverse for 'create_chat' with arguments '('',)' not found. 1 pattern(s) tried: ['create_chat/(?P<id>[0-9]+)/$'] I will really appreciate your Help. Thank You In Advance. -
Do I need to lock a SQL update query with an "is null" check?
I have an API endpoint that can be called multiple times (in theory), even though it should be only called once. The API endpoint basically just performs an update operation that looks like this: MyModel.objects.filter( pk=kwargs["pk"], accessed_at__isnull=True, ).update(accessed_at=now()) I'm wondering what happens if this API endpoint gets called by another user in parallel. Is this vulnerable to a race condition or is it safe because I'm doing the isnull check before which should prevent that this field gets updated after setting it once? This is more like a SQL related question because I'm not sure how Postgres handles these situations. Or should I explicitly lock the row to prevent parallel updates with select_for_update? -
Language selection of third party packages, Django
I am dealing with this problem for 2 days approximately. Let me tell you what I did and why I did then asking my question. I have a project that I want to support multilanguage but right now it should support only one language, I will add other languages over time. So my settings.py has these: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'project.apps.ProjectConfig', ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'project/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.i18n' ], }, }, ] LANGUAGE_CODE = 'tr' LANGUAGES = [ ('tr', 'Türkçe') ] LOCALE_PATHS = [ BASE_DIR / 'project/locale', ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I translated my forms.py and models.py files only for now. and ran makemessages: python manage.py makemessages -l tr --ignore=venv/* (I ignored venv packages) python manage.py compilemessages --ignore=venv/* after all of these, my website was correctly translated to my desired language (which is the only language now) also Django admin page is "tr" now because the project language is set to "tr". Form errors are "tr" too. BUT. I am using the third-party phonenumber_field … -
Use context var to access attribute in django template
I'm actually building a template to render several models in the same table format. I use a class based listviews to access the model. I've also overwritten the context to give the fields needed for each type of model : views.py class ProductListView(ListView): template_name = 'myApp/table.html' model = Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['fields'] = ['name', 'product_type', 'cost', 'margin'] return context In the template, I'd like to loop through the given fields, by doing : {% for element in object_list %} <tr> {% for field in fields %} <td>{{ element.field }}</td> {% endfor %} </tr> {% endfor %} But it does not display anything. I've read in the documentation (https://docs.djangoproject.com/en/3.1/ref/templates/language/) that : Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context. and I understand what I'm doing wrong but I can't figure out how to display this field. I can't just explicitely write the field names in the template because I want this template to be able to handle differents models. Is there any way to loop through the given fields ? -
Serializer with other Serializer as attribute not parsing incoming request data
In Django Rest Framework I have this serializer: class RecipeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, many=False) id = serializers.ReadOnlyField() ingredients_list = IngredientCompositionSerializer(read_only=False, many=True) def create(self, validated_data): validated_data['user'] = self.context['request'].user return super().create(validated_data) class Meta: model = Recipe fields = ['user', 'id', 'name', 'description', 'ingredients_list', 'created', 'modified'] In his ViewSet, when I try to create a new Recipe, I got an error for ingredients_list field saying that it's a required field (true), but I'm sending its value as Json in the request. This is how request.data is reaching the create function in the ViewSet of RecipeSerializer. I'm using Postman: <QueryDict: { 'name': ['a new recipe test'], 'description': ['the description'], 'ingredients_list': [ '{"id": 4, "quantity": 350}, {"id": 3, "quantity": 500}' ] }> Also tried with sending ingredients_list between [] but the error is the same. Here is IngredientCompositionSerializer, which represents ingredients_list in RecipeSerializer: class IngredientCompositionSerializer(serializers.HyperlinkedModelSerializer): id = serializers.PrimaryKeyRelatedField(source='ingredient.id', queryset=Ingredient.objects.all()) name = serializers.ReadOnlyField(source='ingredient.name') class Meta: model = IngredientComposition fields = ['id', 'name', 'quantity'] # quanitity is just a Django's DecimalField When I check serializer.data in RecipeViewSet.create() function, it only has name and description. What am I doing wrong? Thanks! -
Database entry not created by clicking on the accept friend request button
I am writing the view for accepting the friend request, I dont know what is happening, i am fetching jason data to the view but i doesn't working . i have tried all of the solutions that are on this website but they doesn't work for me here is my Javascript <script > function acceptFriendRequest(friend_request_id, uiUpdateFunction){ var url = "{% url 'friend:friend-request-accept' friend_request_id=53252623623632623 %}".replace("53252623623632623", friend_request_id) $.ajax({ type: 'GET', dataType: "json", url: url, timeout: 5000, success: function(data) { console.log("SUCCESS", data) if(data['response'] == "Friend request accepted."){ // ui is updated } else if(data['response'] != null){ alert(data['response']) } }, error: function(data) { console.error("ERROR... this is the error from accept", data) alert("Something went wrong") }, complete: function(data){ uiUpdateFunction() } }); } Here is my view def accept_friend_request(request, *args, **kwargs): user = request.user payload = {} if request.method == "GET" and user.is_authenticated: friend_request_id = kwargs.get("friend_request_id") # print(f"friend request id {friend_request_id}") if friend_request_id: friend_request = FriendRequest.objects.get(pk=friend_request_id) # print(f"friend request object {friend_request}") # confirm that is the correct request if friend_request.receiver == user: if friend_request: # found the request. Now accept it friend_request.accept() payload['response'] = "Friend request accepted." else: payload['response'] = "Something went wrong." else: payload['response'] = "That is not your request to accept." else: payload['response'] = … -
ForeignKey Constraint failed
I have followed Coreys blog app, and I have integrated a comments function. I now appear to have an issue when trying to delete a comment WITH a comment attached. after reading about a million posts on stackoverflow, most people refer to the USER on_delete, but mine already appears to be on CASCADE. Odd issue. a post without a comment can be deleted by the user the issue is a post with a comment can't be deleted (foreignkey constraint issue) error: POST Request URL: http://127.0.0.1:8000/post/31/delete/ Django Version: 3.1.4 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed I should be able to create a post, have multiple users comment on said post. Then if the user of the post wishes to delete the post all comments should be deleted(obviously- cascade has been added) at the moment the only way i can get around this, is to delete a users comments and then delete the post. models.py (post function) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(choices=cat_new_choice, max_length=200,default='Onboarding') likes = models.ManyToManyField(User, related_name='blog_posts', blank=True) #user who created this post, then the user gets deleted - what happens to the post? this will … -
Is it possible to list files in a dir with Azure storages
I'm using Django and django-storages[azure] as backend. But i can't to find out to list dir the files instead I have to use snippets like this: block_blob_service.list_blobs(container_name='media', prefix=folderPath)] this is not working: listdir(absoluteFolderPath) In storages/backend/azure_storage.py I found this part: def listdir(self, path=''): """ Return directories and files for a given path. Leave the path empty to list the root. Order of dirs and files is undefined. """ files = [] dirs = set() for name in self.list_all(path): n = name[len(path):] if '/' in n: dirs.add(n.split('/', 1)[0]) else: files.append(n) return list(dirs), files But how can I use it? regards Christopher. -
Django React Serving Together Page not found (404)
I develop an application using Django and React. I want to serving Django and React together. I create an build in react. I use it in Django. This is urls.py ; urlpatterns = [ url(r'^$', views.index), ] and views.py; def index(request): return render(request, "build/index.html") When I run development server there is no any error but when ı want to go url directly ; http://www.x.com:8000/accounts I got page not found (404) error. -
The view urlshort.views.page_redirect didn't return an HttpResponse object. It returned None instead
I'm making a url shortener with django. I have a form that has a long_url attribute. I'm trying to get the long_url and add it to a redirect view with a HttpResponseRedirect. # Form from .models import ShortURL from django import forms class CreateNewShortURL(forms.ModelForm): class Meta: model=ShortURL fields = {'long_url'} widgets = { 'long_url': forms.URLInput(attrs={'class': 'form-control'}) } # View def page_redirect(request, url): if request.method == 'GET': form = CreateNewShortURL(request.GET) if form.is_valid(): original_website = form.cleaned_data['long_url'] return HttpResponseRedirect(original_website) When I go to the link, it gives me The view urlshort.views.page_redirect didn't return an HttpResponse object. It returned None instead. Does anyone know why this is happening? -
AuthFailed at /social-auth/complete/linkedin-oauth2/
I am a bit confuse while LinkedIn r_basicprofile is not authorized for my application after completing the necessary process. I have check some related question on SO but it appears that solutions are not working for me maybe because of the different changes on LinkedIn social oauth. Authentication failed: Scope &quot;r_basicprofile&quot; is not authorized for your application My backend settings, frontend and API are correct, but I don't know why it is not working. 'social_core.backends.linkedin.LinkedinOAuth2', SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'correct' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'correct' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email-address', 'formatted-name', 'public-profile-url', 'picture-url'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('formattedName', 'name'), ('emailAddress', 'email_address'), ('pictureUrl', 'picture_url'), ('publicProfileUrl', 'profile_url'), ] frontend <li class="linkedin"><a href="{% url "social:begin" "linkedin-oauth2" %}">Login with LinkedIn</a></li> urls.py path('social-auth/', include('social_django.urls', namespace='social')), -
UnboundLocalError: local variable '_' referenced before assignment
Seems that django/python is not recognizing that I want to use this library: from django.utils.translation import gettext as _ If I do: {"id": user.pk, "status": _("Password changed")} He gives an error: UnboundLocalError: local variable '_' referenced before assignment He thinks that I want to reference to a local variable, while I just wanted to use the translation function. In other parts of my application, the translation does work perfect. How is this possible? Thank you