Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Block evaluation of template tags but not variables
I am using Django's template engine to evaluate user-supplied template strings. I would like to allow the users to use the variable mapping functionality, but not the tags or filters. For example: from django.template import Context, Template user_template_string = "V1: {{ var1 }}. V2: {{ var2|truncatechars:5 }}. {% if var3 %} yes {% else %} no {% endif %}" template = Template(user_template_string) context = {'var1': 'One', 'var2': '123456789', 'var3': True} output = template.render(context=Context(context)) # Desired output: # "V1: One. V2: 123456789. {% if var3 %} yes {% else %} no {% endif %}" Is there a way to configure the template engine to render variables but ignore tags and filters? Or is my best bet to sanitize the user input and try to strip out all tags and filters that they may include? -
Putting a django application on production using IIS Server is raising an error
I am trying to put on production a Django web app using IIS Server but I am getting this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "SGC.wsgi.application" could not be imported: Traceback (most recent call last): File "c:\programdata\anaconda3\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = __import__(module_name, fromlist=[name_list[0][0]]) File ".\SGC\wsgi.py", line 16, in <module> application = get_wsgi_application() File "c:\programdata\anaconda3\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "c:\programdata\anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\programdata\anaconda3\lib\site-packages\django\apps\registry.py", line 92, in populate app_config = AppConfig.create(entry) File "c:\programdata\anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\programdata\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'ckeditor' StdOut: StdErr: In my application everything about creditor is installed. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hr.apps.HrConfig', 'account', 'courriers', 'rolepermissions', 'crispy_forms', 'admin_tools', 'cart.apps.CartConfig', 'enregistrement', 'ckeditor', 'debug_toolbar', ] Here is my web.config file: <system.webServer> <handlers> <add name="SCG SERVER" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\programdata\anaconda3\python.exe|c:\programdata\anaconda3\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="PYTHONPATH" value="F:\SGC" /> <add key="WSGI_HANDLER" value="SGC.wsgi.application" /> … -
How to add a variable through 'annotate' that is responsible for the presence of the current user in the list of values of one of the model fields
I have these models: class ProfilePost(models.Model): author = models.ForeignKey(Profile, on_delete=models.CASCADE) post_text = models.TextField(max_length=10000) publication_date = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(Profile, related_name='like') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) profile_picture = models.ImageField(default='/pictures/default.png', upload_to='pictures/', blank=True) city = models.CharField(max_length=63, blank=True) phone = models.CharField(max_length=15, blank=True) def get(self, request, user_id, *args, **kwargs): user = get_object_or_404(User, id=user_id) if request.GET and request.GET['request_type'] == 'get_extra_posts': posts2 = ProfilePost.objects.filter(author=user.profile).order_by('-publication_date') posts_with_users_likes = list(request.user.profile.like.all().values_list('id', flat=True)) print(posts_with_users_likes) # [21, 11, 10, 8, 6, 1] posts2 = posts2.annotate( like_count=Count('like', distinct=True), comment_count=Count('postcomment', distinct=True), is_liked_by_user=Value(len(Q(id__in=posts_with_users_likes)), output_field=BooleanField()) ) posts2 = posts2.values('id', 'post_text', 'publication_date', 'is_liked_by_user', 'like_count', 'comment_count') print(posts2) return JsonResponse(data={'posts': posts2}) In my views.py I want to add some extra fields to the ProfilePost Queryset, but I am having problems with the is_liked_by_user field, which should be True if the current user has liked this post and False otherwise. The line print(posts2) outputs <QuerySet [{'id': 12, 'post_text': '6', 'publication_date': datetime.datetime(2020, 10, 1, 18, 2, 29, 635769, tzinfo=<UTC>), 'like_count': 0, 'comment_count': 0, 'is_liked_by_user': True}, {'id': 11, 'post_text': '5', 'publication_date': datetime.datetime(2020, 10, 1, 18, 2, 21, 401305, tzinfo=<UTC>), 'like_count': 1, 'comment_count': 0, 'is_liked_by_user': True}, {'id': 10, 'post_text': '4', 'publication_date': datetime.datetime(2020, 10, 1, 18, 0, 49, 402443, tzinfo=<UTC>), 'like_count': 1, 'comment_count': 1, 'is_liked_by_user': True}, {'id': 9, 'post_text': '3', 'publication_date': datetime.datetime(2020, 10, … -
Facebook Share Button from Django App add <meta/>
I'm working on Django 2.0.13 and I'm trying to add button to share on facebook on my news.html template but when I click on share I don't see the image or the content of the shared new. Thanks for your help. {% for new in news %} <div class="row" id="{{ new.id }}" style="border-bottom:2px solid #000000; padding-top:20px; padding- bottom:20px"> {% if new.photo %} <div class="col-md-3"> <img src="{{ new.photo.url }}" alt="photo de {{new.photo.title}}"/> </div> <div class="col-md-9"> {% else %} <div class="col-md-12"> {% endif %} <div id="texte_middle" class="page"> <h3>{{ new.title }}</h3><br> <h4>{{ new.date_created}}</h4> <p>{{ new.content|safe }}</p> {% if new.share_button_active %} {% block extra_head_tags %} <meta property="og:title" content= "{% if new %} {{new.title}} {% else %} News {% endif %}" /> <meta property="og:image" content="{{new.photo.url}}" /> <meta property="og:description" content={{new.content|safe}} /> <!-- Sharingbutton Facebook --> <a class="resp-sharing-button__link" href="https://facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}%23{{ new.id }}" target="_blank" rel="noopener" aria-label="" > <div class="resp-sharing-button resp-sharing-button--facebook resp-sharing-button--small"><div aria- hidden="true" class="resp-sharing-button__icon resp-sharing-button__icon--solidcircle"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 0C5.38 0 0 5.38 0 12s5.38 12 12 12 12-5.38 12-12S18.62 0 12 0zm3.6 11.5h-2.1v7h-3v-7h-2v-2h2V8.34c0-1.1.35-2.82 2.65- 2.82h2.35v2.3h-1.4c-.25 0-.6.13-.6.66V9.5h2.34l-.24 2z"/></svg> </div> </div> </a> {% endblock %} {% endif %} -
How to filter the amount of options which the user can choose depending on the previous selected option (DJANGO)
I have been trying for a while to implement a filter system in which it changes the options that the user can select depending on the previous option chosen in my DJANGO application. The process is like that :[The user will select a school][then depending the school that the user has chosen just the courses this school has will be displayed] [then after selecting the course the only options the user will have are the ones that are related to School -> Course - > Classes - > Semester then all the books with the exactly matching metadata will be displayed. Does someone can guide me or give some ideas on how I can implement that ? I have tried many to many and one to many relationships already but I was not successful :/ Also for real time changes will I have to implement AJAX with the application for that ? Thank you for your time :) Here is a image to show how the application will look like: https://i.stack.imgur.com/xympT.png -
DoesNotExist at /blog/postComment Post matching query does not exist
I am trying to print the comments below the blog but after clicking the submit button the above error shows up. I just want a success message to be displayed on the top of the web page, for which I have written the line: messages.success(request, 'your comment has been added'), but the error shows up! models.py: from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.TextField() author = models.CharField(max_length=50) slug = models.SlugField(max_length=200) timeStamp = models.DateTimeField(blank=True) def __str__(self): return self.title + " by " + self.author class BlogComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField(default=now) urls.py: from django.urls import path, include from blog import views urlpatterns = [ path('postComment', views.postComment, name='postComment'), path('', views.blogHome, name='home'), path('<str:slug>', views.blogPost, name='blogpost'), ] view.py: from django.shortcuts import render, HttpResponse, redirect from blog.models import Post, BlogComment def blogHome(request): allpost = Post.objects.all() context = {'allposts': allpost} return render(request, 'blog/blogHome.html', context) def blogPost(request, slug): post = Post.objects.filter(slug=slug).first() comments = BlogComment.objects.filter(post=post) context = {'post': post, 'comments': comments} return render(request, 'blog/blogPost.html', context) def postComment(request): if request.method == 'POST': … -
Heroku not updating static files for Django webapp
I noticed that recently my static files on my Django web app are not being updated on my website despite being successfully pushed to Heroku master, and working fine locally. Now I have tried several steps: I first got my git status and it says Everything up to date. My DNS Host is CloudFare so I have done Purge Cache and still nothing. I have also triied heroku repo:purge_cache -a appname to delete my cache and then ran an empty commit and still nothing. I have deleted my browser cache several times and still, my static files are not being updated despite me running python manage.py collectstatic and heroku run python manage.py collectstatc and committed, yet nothing. Now is there anything that I have missed? I do not know any other method to update my static files. -
xamarin froms parse JSON from django rest framework
I can successfully register with my xamarin forms app in django website and if username or email already exist i receive http response from django rest framework in this format : { "username": [ "account with this username already exists." ], "email": [ "account with this email already exists." ] } i want to show these errors in display alert without username and email. only text of error ( for example: account with this username already exists or account with this email already exists) i've tried to parse it in a lot of ways but none of them worked. how can i achieve it? code in my app: HttpClient client = new HttpClient(); var values = new Dictionary<string, string> { { "username", EntryUsername.Text }, { "email", EntryEmail.Text }, { "password", EntryPassword1.Text }, { "password2", EntryPassword2.Text } }; var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("http://192.168.0.101:8000/api/account/register", content); var responseString = await response.Content.ReadAsStringAsync(); -
How to call user variables in Django ModelAdmin
I am new to Django and having trouble understanding how to call proper variables in a ModelAdmin. If I am on /admin/mt_app/my_model/ that I have information like the user's name OR I'm on /admin/auth/user/2/change/ that has all the user's information, how do I call those variables in the ModelAdmin View? I got it working selectively by plugging in my own user, but I can't figure out how to call the relevant user or model from the view. All I can find is how to call the current user, but again, I need the user of the that the page is regarding, not the active user. Ex: /admin/algorx/pt_data/41/change/ or /admin/auth/user/2/change/ What I have now is: Admin.py class pt_dataAdmin(admin.ModelAdmin): fieldsets = ( . . . ) # This gets passed into change_view as extra context def get_dynamic_info(self): user = User.objects.get(email='MYSUPERUSEREMAIL') return user . . . def change_view(self, request, object_id, form_url='', extra_context=None): . . . So what works is passing in my super user's email to select that user: user = User.objects.get(email='MYSUPERUSEREMAIL') return user But what I want to do is select the user of the current page being viewed. If I'm on the following URL how do I select that user's variable? … -
Django TestCase to validate a ModelForm over multiple Models
I have flexible data models representing network switches and their individual ports that look similar to below (with apologies for the name of the first; unfortunate but I could think of no better): class Model(models.Model): name = models.CharField(max_length=20, unique=True) port_count = models.IntegerField() ... class Switch(models.Model): model = models.ForeignKey(Model, on_delete=models.CASCADE) name = models.CharField(max_length=14, unique=True) ... class Port(models.Model): switch = models.ForeignKey(Switch, on_delete=models.CASCADE) number = models.IntegerField() ... Data entry is validated to ensure Port.number is within the range of 1 to Model.port_count. This was a trivial TestCase to author. Another important validation is for my ModelAdminForm.clean() to ensure that reducing Model.port_count would not make any existing Port records violate the new range. (Those ports would likely need to be deleted first.) Authoring this clean() method was also trivial, but authoring a TestCase for this validation has landed me in new territory without a map or guide. Since such a test requires a bit of initial DB population, I created a helper: def add_one(cls, **kwargs): _log.info(f'adding one {cls.__name__}') return cls.objects.create(**kwargs) I started by developing the TestCase to mimic an edit of Model.port_count that would not have any issues, to prove my transactional parts correct. Later, I would extend the code so that there would … -
How to select an instance of a model from a queryset django?
I am creating a project for hosting cricket tournaments. I have created 3 apps in it: home, tournament and team. After adding a tournament, when entering the tournament's detail view, I can add a team to the tournament. My Team model has a ForeignKey to my Tournament model, and my Tournament model has a ForeignKey to my User model(built-in django user model). When creating a team, I want to save the team for a particular tournament. I don't understand how to access the exact tournament and save the team for that tournament only. My tournament detail html: {% extends 'menu.html' %} {% block content %} <div class="row"> <div class="col-8"> <table class="table table-bordered table-hover"> <tr> <th scope="col">Match between</th> <th scope="col">Winner</th> </tr> {% for match in match_list %} <tr> <td> {{ match.team1.name }} vs {{ match.team2.name }} </td> <td> {% if match.winner %} {{ match.winner.name }} {% else %} TBD {% endif %} </td> </tr> {% endfor %} </table> </div> <div class="col-4"> {% if teamscount < tournament.no_of_teams %} <button class="btn btn-primary" onclick="window.location.href='{% url 'teams:addteam' %}'">Add Team</button> {% endif %} </div> </div> {% endblock content %} My urls.py file in tournament app: from django.urls import path, include from . import views app_name='tournaments' urlpatterns … -
serializer field with "allow_null" automatically sets value to null
I have the following serializer class NiceSerializer(serializers.Serializer): nice_field = serializers.CharField(required=False, allow_null=True) another_field = serializers.IntegerField(required=False) I need the nice_field to be nullable, that's why I put allow_null=True, however, sometimes I make a patch request that should only update the value of another_field, so the request does not contain the nice_field value. The problem is that the after validating the request data the NiceSerializer automatically set the value to None, which is a very inconvenient behaviour. How can I write a serializer where I can eventually ignore a field in the patch request? Thanks a lot -
How to pass values of a dropdown list from html to python using django
I am sure this is a simple syntax issue I am not able to resolve. I just started working in django to try to move away from tkinter for my python hobby project. List below are my views, template, and url files. All I want for my front end GUI is to have a user select a file path, a Area, and a type of output. I plan on pass off this values to python to do some logic with. from django.shortcuts import * from django.http import * # Create your views here. def home(request): return render(request, 'home.html') def page_objects(request): Area = request.GET["Area"] Output = request.GET["Output"] print(Area) print(Output) return render(request, 'home.html') <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h2>Please Select Your Document, and the Area</h2> <p>Move the mouse over the button to open the dropdown menu.</p> <p>Then hit submit!</p> <p> <label for="myfile">Select a file:</label> <input type="file" id="myfile" name="myfile"> </p> <form action="/views" method="post"> <select name="Area"> <option selected="selected" disabled>Objects on page:</option> <option value="P10">P10</option> <option value="P20">P20</option> <option value="P30">P30</option> <option value="P40">P40</option> <option value="P50">P50</option> </select> <select name="Output"> <option selected="selected" disabled>Objects on page:</option> <option value="List">List</option> <option value="Address">Address</option> </select> <input type="submit" value="Select"> </form> </body> </html> from django.urls import path from . import views urlpatterns … -
django-allauth-sendgrid password reset email not received
I have integrated sendgrid in my app as follows: SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "from@example.com" I run a test from manage.py shell as the below and I received the test email. from django.core.mail import send_mail send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com']) On my website, after clicking forget password and filling in a registered user email, the page directs to a page that says email sent. But I did not received any email. There is no debug info and I cannot figure out where it went wrong. I am on pythonanywhere is that makes a difference. -
django ajax login form login without page refresh
i followed a tutorial online that shows how to submit a form with ajax and i ended up with just submitting the form and a meesage gets rendered in the console that says it worked , but i want the prosses to work and the user signin or if there are errors , those errors appears without the need of page refresh i mean with the help of ajax. in my forms.py class SigninForm(forms.ModelForm): class Meta: model = User fields = ('email', 'password') widgets = { 'email': forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control','id':'signin_email'}), 'password': forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control','id':'signin_password'}), } def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] the email input has an id of "signin_form" and the password has an id of "signin_password" in my views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout as django_logout from django.http import JsonResponse from django.contrib import messages from .models import * from .forms import * def home(request): user = request.user signin_form = SigninForm() if request.is_ajax(): signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) data = { 'message':'it's working successfully' } return JsonResponse(data) context = {'signin_form': signin_form,'signup_form': signup_form} return render(request, 'main/home.html', context) in my … -
Django models.py (API result) - retrieve current post to add api result
I'm new to Django I got an issue. I don't know how to retrieve the current post inside of models.py. I've tried different way for that. 'QuerySet' object has no attribute 'aliments' or no error and no add to Post from ListAliments get_object_or_404(Post, id=kwargs['id']) here is my models.py class ListAliments(models.Model): name = models.CharField(max_length=40, unique=True) slug = models.SlugField(editable=False) status = models.IntegerField(choices=STATUS, default=1) def save(self, *args,**kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(ListAliments, self).save(*args, **kwargs) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=190) url_image = models.URLField(max_length=200, default=None) aliments = models.ManyToManyField('ListAliments',blank=True, related_name='listaliments_post') ... def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.title)) super(Post, self).save(*args, **kwargs) -> First save for Post which has not no ID ... if self.url_image: request = ... response = ... if response: names = [] for concept in response.outputs[0].data.concepts: current_aliments = ListAliments.objects.filter(name=concept.name) current_post = Post.objects.filter(url_image=self.url_image) #get_object_or_404(Post, id=kwargs['id']) if current_aliments.count()<1: create_aliments = self.aliments.create(name=concept.name) current_post.aliments.add(create_aliments) else: existed_aliments = ListAliments.objects.get(name=concept.name) current_post.aliments.add(existed_aliments) super().save(*args, **kwargs) -
How to convert bytes to a string of the same length in Python (1 character for each byte)?
I need a random string that I can write down to use for salt in a hash function. I can generate some random bytes and see them as hex: import os, binascii print(binascii.b2a_hex(os.urandom(32))) b'76449cd6134d64353122102fcb512d1eae1bd8437202b6e06e91a422ce9e386b' # 64 chars Great, but how do I convert these bytes directly to a string i.e. not necessarily printable, but exactly 32 characters? The hash function requires a string, not a "bytes" type with a maximum length of 32. I'm not sure how to do the encoding in Python, but I guess I need something similar to the way an old 8-bit computer or a C program would turn a byte into a character (ASCII or other). This is for the salt input of Django's make_password function. -
New users are not able to create an account and Login and Register urls are redirection to same page Django
I am trying to build a simple authentication system using Django. Both Login and Register urls on 'accounts' are redirecting to the same Login page. After I login as an admin, I'm redirected to register page. In the register page, I'm not able to register new accounts. Please tell me what I'm missing. urls.py-login from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ] urls.py-accounts from django.urls import path from . import views from django.contrib.auth.views import LoginView, LogoutView urlpatterns = [ path('', views.indexView, name = "home"), path('dashboard/', views.dashboardView, name = "dashboard"), path('login/', LoginView.as_view(), name = "login_url"), path('register/',views.registerView, name = "register_url"), path('logout/', LogoutView.as_view(next_page='dashboard'), name = "logout"), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required # Create your views here. def indexView(request): return render(request, 'index.html') def dashboardView(request): return render(request, 'dashboard.html') @login_required def registerView(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login_url') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form':form}) index.html <!DOCTYPE html> <html> <head> <title>Petrol Pump Management System</title> </head> <body> {% block content %} <h1>User Authentication</h1> {% if user.is_authenticated %} <a href="{% url 'logout' %}">Logout</a> {% else %} <a href="{% url 'login_url' %}">Login</a> <a href="{% … -
No revision info error when running manage.py in Django
I am currently working on a Django project and have run into the follow error whenever I run any of my manage.py commands: Revision invalid: Got "no revision info! Check GIT_DIR=/Users/brockherion/dev." The issue seems to have come out of nowhere as I was able to add projects to my Django app without it. I can still run all the manage.py commands, but everyone of them throw this error. I have tried a couple of things, including: Removing PIP packages (I though django-markdownx was the cause, but it still throws the error without it) Removing my local git repo and creating a new one Checking out a new GIT branch Creating a new Django project (Works for a few commands then starts throwing it again) Merging all my branches so they are up to date I can still run my Django app. This just more of an annoyance than anything else. Again, it ONLY happens when I run manage.py, so I'm not sure if it's a GIT or Django issue. -
How to set a default field in a serializer to be the same as another field in the same serializer?
I have a serializer like this class SomeSerializer(serializers.Serializer): id = serializers.UUIDField(required=False, default=uuid.uuid4) anotherId = serializers.UUIDField(required=False, default = ????) and i want to set field 'anotherId' same as 'id' by default. This is what I expect s = SomeSerializer(data={}). data = s.data data.id # return '56e34c58-be7d-4c7c-992a-43080faf5614' data.anotherId # return '56e34c58-be7d-4c7c-992a-43080faf5614' (as id) I tried to do it like here but it didn't work class SomeSerializer(serializers.Serializer): id = serializers.UUIDField(required=False, default=uuid.uuid4) anotherId = serializers.UUIDField(required=False, default = id.get_default()) How can this be done? -
Why do I get the following error attempting to install memcached in my django app?
I'm trying to add memcached to a django app . So I installed it using the command sudo apt get install memcached When I Attempt to check the install using memcached -vv I get the error can't run as root without the -u switch I'm not sure what this error means. I need to understand before I attempt to research solutions. -
How to recieve many to many field value in model viewsets and model serializer in django?
I have a simeple app with two models Post and Categories. A post will have three fields title, body and assigned categories which should be pre created. A user will create the categories first then create the post with the categories put in the assigned categories field. I am sending the values like this--> { "id": 5, "title": "title 1", "body": "body", "categories_assigned": [ { "id": 1, "name": "technlogy" } ] } but the more I try putting the dictionary in many to many field. I ony recieve the the values as a ordered dict in a array. [OrderedDict([('name', 'technlogy')])] I know i can put it in a for loop and subscript it using i["name"]...but it only gives me the name property. I want the unique id to add in that many to many field in case there are lot of category objects having the name = technology my serializers.py file--> class CategorySerilizer(serializers.ModelSerializer): class Meta: model = models.Category fields = ['id', 'name'] class PostSerializer(serializers.ModelSerializer): categories_assigned = CategorySerilizer(many = True) class Meta: model = models.Post fields = ['id', 'title', 'body', 'categories_assigned'] def create(self, validated_data): post = models.Post.objects.create(title = validated_data["title"], body = validated_data["body"]) print(validated_data["categories_assigned"]) for i in validated_data["categories_assigned"]: print(i["name"]) // 'technlogy' return … -
Django, URL dispatcher not working when using angle brackets to capture a value
core/settings.py INSTALLED_APPS = [ ... 'api.apps.ApiConfig', ... ] core/urls.py (app URL configuration) urlpatterns = [ path('api', include("api.urls")), ] api/urls.py urlpatterns = [ path("", views.index, name="API Overview"), path("establishment/<str:username>", views.get_id_establishment_auth, name="task-establishment"), ] api/views.py @api_view(['GET']) def get_id_establishment_auth(request, username): print(username) return HttpResponse('Success'); The above code will result a 404 page Page not found if i type http://127.0.0.1:8000/api/establishment/mark when mark is a path converter i cant get what is the problem but looks like the path converter is not working (str:username). -
(django) .update() not working inside class model
I have the following code but the .update() in remove_user_invite() isn't working, and no errors are being thrown. Does anyone know what's wrong or how I can fix this? Many Thanks! models.py class StaffProfile(Profile): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, db_index=True, related_name="staff_profiles", on_delete=models.SET_NULL) objects = CustomStaffProfileManager() def remove_user_invite(self): invites = StaffUserInvite.objects.filter(staff_profile=self, used_at=None, expires_at__gt=timezone.now()) invites.update(expires_at=timezone.now()) -
Client-side and server-side rendering of HTML page in a Django single page app
this question could be a duplicate but I have a specific use case. The app is a single page Django app. The user can choose from several options in a drop-down box. Depending on the choice, a few input boxes will need to be rendered. As an example, if the user chooses to order a pizza, the options in another drop-down menu should be related to the toppings whereas an order for drinks should provide options related to the type or brands. The resulting number of input boxes could be 5 with one option or 10 with a different option. I can think of rendering the page using JS or by using Python in the back-end. Because this app will be a commercial one, I do not need SEO as users need to log into the app first. I also want to minimize the amount of code that a competitor can 're-use' from my work. Will client-side rendering open up security problems? If not, is client-side the better way to go?