Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using the URLconf defined in projectname.urls, Django tried these URL patterns, The current path, appname/tablename/add/, didn't match any of these
When I deploying a Django project, I find this error: The error after deploying project This error didn't appear in localhost and everything is fine in the localhost. I do many solutions in static and media files but still doesn't work. Hint: This error come only with tables that contain the image field. project/app/urls.py from django.urls import path from .views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', IndexView.as_view(), name='index'), path('aboutus/', AboutUsView.as_view(), name='aboutus'), path('blogs/<int:pk>', BlogsView.as_view(), name='blogs'), path('blogdetail/<int:pk>', BlogDetailView.as_view(), name='blogdetail'), path('blogdetail/', BlogDetailView.as_view(), name='comment'), path('blogsearch/', SearchBarView.as_view(), name='search'), path('contactus/', ContactUsView.as_view(), name='contactus'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Example of table that contain image field: enter code here class Blog(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images', default='images/defualt_blog.png', blank=True) short_content = models.TextField(max_length=200) content = RichTextField() category = models.ForeignKey('Category', on_delete=models.CASCADE) status = models.BooleanField(default=False) recipe = models.ForeignKey('Recipes', on_delete=models.SET_NULL, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_created'] verbose_name_plural = 'المدونة' def __str__(self): return self.title The files structures: Project/ --- db.sqlite --- manage.py --- app/ --- migration/ --- admin.py --- apps.py --- model.py --- urls.py --- views.py --- Projectname/ … -
Django - How to get parameters from PUT request?
I set the URL like this: path('voucher/<str:voucher>', views.update_voucher.as_view()) Here is my code: class update_voucher(generics.GenericAPIView): @swagger_auto_schema(......) @logging_code def put(request, voucher): voucher_id = voucher request_data = json.loads(request.body) My request: http://0.0.0.0:6001/voucher/125 Body: {"custimer_id": 123} When running it, I got this error: TypeError at /voucher/125 put() got multiple values for argument 'voucher' Request Method: PUT Request URL: http://0.0.0.0:6001/voucher/125 Django Version: 3.1.4 Exception Type: TypeError Exception Value: put() got multiple values for argument 'voucher' Exception Location: /code/leadtime/logger.py, line 9, in func_wrapper Python Executable: /usr/local/bin/python Python Version: 3.9.0 Python Path: ['/code', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/site-packages'] Server time: Sun, 31 Jan 2021 05:27:46 +0000 Since, I am the beginner, it would be nice if you can give me both solution and explanation. Thanks -
WagtailAdminPageForm and URL not saving in admin or passing to page
I have a quick script that parses a JSON response from an API and adds it to a WagtailAdminPageForm, like so: """Flexible page.""" from django.db import models import requests from django import forms from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.admin.forms import WagtailAdminPageForm def get_mp3_choices(): response = requests.get('https://api.somexamplepage.com') response.raise_for_status() jsonResponse = response.json() jsonResponse['results'][0]['audio'] mp3_list = [] return [ (key['audio'], key['title']) for key in jsonResponse['results'] ] class FlexPageForm(WagtailAdminPageForm): audioUrl = forms.ChoiceField(choices=get_mp3_choices) class Meta: label = 'Select Audio for Player' class FlexPage(Page): """Flexibile page class.""" template = "flex/flex_page.html" # @todo add streamfields # content = StreamField() base_form_class = FlexPageForm subtitle = models.CharField(max_length=100, null=True, blank=True) Flexbody = RichTextField(blank=True) bannerImage = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('Flexbody', classname="full"), ImageChooserPanel('bannerImage'), ] class Meta: # noqa verbose_name = "Flex Page" verbose_name_plural = "Flex Pages" The code works well and I'm able to see the returned list of MP3's within my admin panel. The problem, the selected MP3 is not being preserved when I save the page and, when I look in the sqlite table, I'm not seeing any record of the audioUrl. The following fields do show. page_ptr_id … -
why i'm getting this error 'dict' object has no attribute '_meta'
code in views.py file def settings(request): if not request.user.is_authenticated: return redirect('login') context = {} if request.POST: form = AccountUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: form = AccountUpdateForm( instance={ 'email': request.user.email, 'username': request.user.username, 'light_theme': request.user.light_theme } ) context['account_form'] = form return render(request, 'account/account.html', context) code in forms.py file variable light_theme is BollenFiled I made it to make it eye-friendly to night-time user and select light-theme if they want class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('username', 'email', 'light_theme') def clean_username(self): if self.is_valid(): email = self.cleaned_data['email'] try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExists: return email raise forms.ValidationError('email "%s" is already in use.' % email) def clean_email(self): if self.is_valid(): username = self.cleaned_data['username'] try: account = Account.objects.exclude(pk=self.instance.pk).get(username=username) except Account.DoesNotExists: return username raise forms.ValidationError('Username "%s" is already in use.' % username) code in account.html {% extends 'base.html' %} {% block content %} <h2 style="color:blue;">Account settings</h2> <form method="post"> {% for filed in account_form %} <p> {{ filed.label_tag }} {{ filed }} {% if filed.help_text %} <small style="color:blue;">{{ filed.help_text }}</small> {% endif %} </p> {% end for %} {% for filed in account_form %} {% for error in filed.error %} <p style="color:red;">{{ error }}</p> {% endfor %} {% endfor %} {% if account_form.non_filed_error %} <div style="color:red;"> … -
Render Django login form using django.contrib.auth.urls
I am following this document for implementing the authentication mechanism. Having trouble with rendering the form at begging using this code. It only renders when the form was first submitted, form object was created. How to render form from the auth.urls? #This is not working, it duplicates the base_generic.html, and form input fields are not rendered. {% if user.is_authenticated %} # {% else %} {% include 'registration/login.html'%} {% endif %} https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication {% extends "base_generic.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> {% endblock %} -
Django: Adding monthly goal for products model, and daily production
I'm sorry if my question seems weird, I'll try to explain: I'm building an app for my family's company, there are some products, and every month I need to set a goal for each product for each user. I also need each user to be able to submit how much they've sold of each product every day I'm confused about the approach I should use to relate all of these What I've done is created models for the Products, for the goals and for 'production' (how much they've sold that day) First, I put each product as field in the 'Production' model, but that wouldn't allow me to change anything using the admin panel So, how can use the Products models in the Production models as "fields". ex: class ProductsModel(models.Model):#This is the form each worker is supposed to fill every day, Worker is set accordingly to logged in user Worker = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) ProductsModel1 = models.FloatField()#How much they've sold of this product ProductsModel2 = models.FloatField()#How much they've sold of this product I'd like to do this for as many Products as there are And for the goals, this is what would be ideal: class GoalsModel(models.Model):#This is me or the … -
Which version of Django to start learning as a beginner in 2021?
I've decided to learn Django. But as a beginner, it seems overwhelming seeing the different versions of it. Which version should I choose to learn first so that I have a solid understanding actually how it works? 3.xx or 2.xx or 1.xx? How much different are these three versions of Django? -
vue+django+graphql:has been blocked by CORS policy
the question is 'has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.' I use Django+Graphql and I can get the data through postman。 enter image description here In order to solve the cross domain problem of Django, I have done the following work 1.install django-cors-headers pip install django-cors-headers 2.Add “corsheaders” to the list of installed apps in the settings.py file 3.Add “corsheaders.middleware.CorsMiddleware” to the middleware list in the settings.py file 4.Add CORS_ALLOW_METHODS and CORS_ALLOW_HEADERS But in the front end of Vue, cross domain problems are encountered enter image description here Here is my configuration django/setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '08ux)8987i4d#7^@4a-e3y601*rwhl)zdpl=5#te4f8#!eh(_5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # app 'company', # graphql 'graphene_django', # cors 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', … -
How to make element active in sidebar which is in django include tag through javascript?
I have made sidebar in sidebar.html and had include it in main.html as well as dashboard.html through django include tag to reduce data reduntancy-> {% include 'employee/sidebar.html' %} {% block content %} {% endblock %} Now how do I make different elements (in sidebar) active according to the different pages? Like for example, When I am on dashboard.html , dashboard should be active in sidebar. -
How does social-auth-app-django work with jinja2?
I'm using: python 3.7 Django 2.2.13 social-auth-app-django 3.1.0 I'm considering moving from django templates to jinja2. Most of it makes sense, but it's not clear how the social-auth part would work. In my settings for the DjangoTemplates backend, I've got: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', but the django docs say, "Using context processors with Jinja2 templates is discouraged." So, are these context managers not needed with jinja? -
How to create/update ManytoManyField-related Models
I have been trying lotta solutions (mostly depreciated) on multiple sites but can't manage to make it working in my script : I have two models Product and MyClient : class Product(models.Model): tdpcode = models.IntegerField(null=True) name = models.CharField(max_length=50, null=False) prange = models.CharField( max_length=8, choices=PRODUIT_RANGE, default='TDP') desc = models.TextField(blank=True) unitweight = models.IntegerField(null=True) pcperctn = models.IntegerField(null=True) img = models.ImageField(null=True, blank=True, upload_to="images/") pc = models.FloatField(null=True) palletization = models.ForeignKey( Palletization, default=DEFAULT_PALLETIZATION_ID, on_delete=models.CASCADE, null=True) countryban = models.ManyToManyField(Country, blank=True) status = models.CharField( max_length=10, choices=PRODUIT_STATUS, default='active') date = models.DateField(auto_now_add=True) updatedate = models.DateField(auto_now=True) def __str__(self): return self.name and class MyClient(models.Model): class Meta: ordering = ['clientname'] clientname = models.CharField(max_length=50, null=False) channel = models.CharField( max_length=18, choices=CLIENT_TYPE, default='Distributor') logoimg = models.ImageField(null=True, blank=True, upload_to="client/") incoterm = models.CharField( max_length=3, choices=INCOTERM, default='EXW') country = models.ForeignKey( Country, default=DEFAULT_COUNTRY_ID, on_delete=models.CASCADE, null=True) clientbuy = models.ManyToManyField( Product, blank=True, related_name='myclient') date = models.DateField(auto_now_add=True) updatedate = models.DateField(auto_now=True) When I create/update a new client : I can select the products from MultipleSelectField, on submit, it is working fine. However, I would like to do the same when I create/update a new item, I would like to be able to tick which client will potentially buy it among my full list of client MyClient.objects.all() Please help to indicate where is my issue? … -
Django generic view fields for reverse relationship
I may just be having issues reading the documentation but I can't figure out if this is impossible or I just don't know how to make it work. I'm trying to use a generic UpdateView, and include a reverse relationship in fields to show all of the cars a user has. View: class User_Detail_View(LoginRequiredMixin, UpdateView): model = User template_name = "User/User_Detail.html' fields = ['email', 'cars_set'] User.models: class Cars(models.Model): User = models.ForeignKey('User', on_delete=models.Set_NULL, null=True) Car_Name = models.CharField(max_length=256, unique=True) class User(models.Model): email = models.EmailField(_('email_ address'), unique=True) I'm getting a django.core.exceptions.FieldError: Unknown field(s) (cars_set) specified for User. I can access this reverse relationship via user.cars_set.all() in the shell, so I know the relationship works. I can also show normal fields on the page if I remove the offending reverse field. Any ideas if this is possible or not? Being able to use the generic view would be quite handy. -
Django Model Constraints
I have the following models from django.db import models class league(models.Model): name = models.CharField(max_length=64) def __str__(self): return f"{self.name}" class player(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) age = models.IntegerField() position = models.CharField(max_length=1) nteam = models.CharField(max_length=128) def __str__(self): return f"{self.id} {self.name} {self.age} {self.position} {self.nteam}" class team(models.Model): name = models.CharField(max_length=64) league = models.ForeignKey(league, null=True, blank=True, on_delete=models.CASCADE, related_name="teams") roster = models.ManyToManyField(player, blank=True, related_name="rosters") def __str__(self): return f"{self.name} {self.league}" My goal would be to have many different leagues, each league containing multiple teams. I want a player only to be added to one team in a league. Right now I created a league, add several teams, then added players to each team. As of now I can take a player and add to all the teams in the same league if I want. How would you add a constraint so that once a player has been added to a team, they can no longer be added to another team in the same league? -
Best way to use Django with Scrapy
I started using Django a few months ago since I switched from PHP to Python, and I started working on a small project and I would like to know the best way to let Django communicate with Scrapy. It's possible to make a Rest Api between Django App and Scrapy App? What is the best way? -
Django unable to render my template because it is unable to find my url. This only happens with url patterns from one of my apps
Django is unable to load my template because "NoReverseMatch at /books/outlines/20 " This issue lies within a link in the template: <a href="{% url 'test'%}" class="type">New Blank Outline</a> Here is my outlines/urls.py from django.urls import path from .views import Dashboard from . import views as outline_views urlpatterns = [ path('<int:pk>/', outlines_views.outline, name='url-outline') path('blank/<int:storyPk>', outline_views.newBlankOutline, name='url-blankOutline'), path('test/', outline_views.testView, name = 'test') ] urlpatterns += staticfiles_urlpatterns() Here is the testView: def testView(request): return render(request, 'outlines/test.html') Here is the outline view: def outline(request, pk): context = { 'storyPk': pk } return render(request, 'outlines/outline.html', context) The django error tells me: NoReverseMatch at /books/outlines/20 Reverse for 'test' not found. 'test' is not a valid view function or pattern name. The weird thing is, if I change the url name in the template to a url name from another app's urls.py file, it renders the template no problem. Any idea why it can't find the url? -
Run Django in root and phpMyAdmin in apach2
I want to serve my Django app from mysite.com and PHPMyAdmin from mysite.cm/phpmyadmin. So I have tried some methods to achieve so with modwsgi. It's / directory seems to take precedence over all directories. How can I set up my apache config to get expected output? I don't want to run my project in a subdirectory, instead, PHPMyAdmin should be in a subdirectory. Here is my apache config. ... <Directory /home/tareq/djproject/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djapp python-path=/home/tareq/djproject python-home=/home/tareq/djproject/dj_env WSGIProcessGroup djapp WSGIScriptAlias / /home/tareq/djproject/config/wsgi.py Alias /phphmyadmin /var/www/html/phpmyadmin <Directory /var/www/html/phpmyadmin> Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all </Directory> </VirtualHost> I tried placing WSGIScriptAlias top and bottom, no change. But everything works just fine if I use WSGIScriptAlias anything other than /. This settings throws error 404 by django app when I visit mysite.com/phpmyadmin -
clearing and seeding database from endpoint in django
I'm trying to set up a rest API that can be cleared and then have the data in my postgres db re-seeded via an endpoint. I'm doing this with Django with json data in a fixtures file, executing a series of functions in my views. This has worked great so far, but now I'm trying to add data with foreign key fields. models.py: class Profile(models.Model): name = models.CharField(max_length = 100) profile_name = models.CharField(max_length = 100) email = models.CharField(max_length = 100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length = 250) body = models.TextField(max_length = 4000) profile = models.ForeignKey(Profile, on_delete = models.CASCADE) def __str__(self): return self.title class Comment(models.Model): title = models.CharField(max_length = 200) body = models.TextField(max_length = 1000) profile = models.ForeignKey(Profile, on_delete = models.CASCADE) post = models.ForeignKey(Post, on_delete = models.CASCADE) def __str__(self): return self.title in views.py def seed(request): Profile.objects.all().delete() reset(Profile) for profile in all_profiles: add_profile(profile) Post.objects.all().delete() reset(Post) for post in all_posts: add_post(post) Comment.objects.all().delete() reset(Comment) for comment in all_comments: add_comment(comment) return HttpResponse('database cleared and seeded') def add_profile(new_profile): profile_instance = Profile.objects.create(**new_profile) profile_instance.save() def add_post(new_post): post_instance = Post.objects.create(**new_post) post_instance.save() def add_comment(new_comment): comment_instance = Comment.objects.create(**new_comment) comment_instance.save() def reset(table): sequence_sql = connection.ops.sequence_reset_sql(no_style(), [table]) with connection.cursor() as cursor: for sql in sequence_sql: cursor.execute(sql) some example seed … -
Getting the currently logged in user from django view form
This is my model. class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20) total = models.DecimalField(max_digits=7, decimal_places=2, default=0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comission_owed = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) comission_paid = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) def __str__(self): return self.name And this is my model form: class ProjectForm(ModelForm): required_css_class = 'required' class Meta: model = Project fields = '__all__' def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['user'].initial = self.user and then here's my view: def add_project(request): submitted = False if request.method == "POST": form = ProjectForm(data=request.POST, user=request.user) if form.is_valid(): form.save() return HttpResponseRedirect('/add_project/?submitted=True') else: form = ProjectForm() if 'submitted' in request.GET: submitted = True return render(request, 'add_project.html', {'form': form, 'submitted': submitted} ) I am trying to get the "user" filled by getting the logged in user but when loading the url "add_project/" where the form should load and let me submit I get an error that traces back to KeyError at /add_project/ 'user' Request Method: GET Request URL: http://127.0.0.1:8000/add_project/ Django Version: 3.1.2 Exception Type: KeyError Exception Value: 'user' Exception Location: /ArtistShop/homepage/forms.py, line 12, in init Python Executable: /usr/local/bin/python Python Version: 3.8.6 Python Path: ['/ArtistShop', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages'] Server time: Sat, 30 Jan 2021 19:16:12 … -
I need to hash a PIN in Django that will always be the same
I am making a Django project. I want users to be able to login by just entering a PIN. I need to store a PIN for users. I want the PIN to be hashed. The PIN (and therefore its hash) be unique. I need to know how to change a user-entered integer and hash it to save in the database. Then I need to know how to compare it when a user enters the PIN. -
Wagtail/Django: Is it possible to populate a given admin fields options out of the results of an API?
I'm working on a Django project and specifically a Wagtail project. I want to switch this code that I have below, to contain a prepopulated admin field, which will be populated by an API response. Here is the code I am currently using: """Flexible page.""" from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel class FlexPage(Page): """Flexibile page class.""" template = "flex/flex_page.html" # @todo add streamfields # content = StreamField() subtitle = models.CharField(max_length=100, null=True, blank=True) Flexbody = RichTextField(blank=True) bannerImage = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) audioUrl = models.URLField() content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('Flexbody', classname="full"), ImageChooserPanel('bannerImage'), FieldPanel('audioUrl'), ] class Meta: # noqa verbose_name = "Flex Page" verbose_name_plural = "Flex Pages" This would enable me to create a standard Wagtail URL field and I could set up a URL to an MP3 file. What I would like to do instead is pre-populate a drop-down menu out of an API response like the following: { "id":"83ee98f6-3207-4130-9508-8f4d15ed7d5c", "title":"some random description", "description":"some random description.", "audio":"https://somerandomurl.mp3", "slug":"some random description", "draft":false }, { "id":"83ee98f6-3207-4130-9508-8f4d15ed7d5c2", "title":"some random description2", "description":"some random description2.", "audio":"https://somerandomurl2.mp3", "slug":"some random description2", "draft":false2 }, I'm wondering how I would go … -
Django: send emails in local language
I'm trying to send a language in local language. Let's say, a user fills up the registration form on the French website, I would like to send him an email in French. I have tried with translation.override but it didn't work. What's the correct way of sending localized emails? subject = _('Please Activate Your Account') email_context = {'domain': current_site.domain, 'uid': reset_uid, 'token': token,} html_body = render_to_string('email/activation-request-email.html', email_context) text_body = render_to_string('email/activation-request-email.txt', email_context) send_mail(subject=subject, message=text_body, from_email='no-reply@example.com', recipient_list=[user.email], html_message=html_body) -
not a valid UUID , how to catch wrong UUID?
I am having a validation error when I set a random string in my url as token. How can i catch this validation error? For example: when accesing: https://www.example.com/stream/8e258b27-c787-49ef-9539-11461b251ffad The error is ValidationError at /stream/8e258b27-c787-49ef-9539-11461b251ffad ['“8e258b27-c787-49ef-9539-11461b251ffad” is not a valid UUID.'] my code is this: def stream(request, token): user = Creador.objects.filter(stream_token=token).first() if user: return render(request, 'app1/stream.html', { 'token':token, 'user':user }) else: return HttpResponse("Token no existe") any ideas? thanks -
Redirect after comment submission to post
I am trying to redirect my comment form submission to the post details page where all comments should be displayed. How do I pass in the unique id for post that the comment is related to into my URL for redirecting to that post? post_detail.html ... <p><a href="{% url 'comment_new' comment.post.pk %}">Create New Comment</a> ... urls.py ... path('comment_new/', views.CommentCreateView.as_view(), name = 'comment_new'), path('<int:pk>/', views.PostDetailView.as_view(), name = 'post_detail'), ... views.py ... class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'comment_new.html' form_class = CreateCommentForm login_url = 'login' def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) ... model.py ... class Comment(models.Model): post = models.ForeignKey( Post, on_delete = models.CASCADE, related_name = 'comments' ) comment = models.CharField(max_length = 280) author = models.ForeignKey( get_user_model(), on_delete = models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('post_detail', args = [str(self.post.id)]) ... -
Django/channel_redis Slow memory leak
I have tried various configurations for channel_redis, and my views.py. Using tracememalloc I found nothing missed by the garbage collection. I used tracememalloc in the websocket connection function. Whether I set a timeout for the connections or not memory still grows. I also use django_prometheus. Currently here is my ASGI.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "panoptes.settings") django.setup() application = get_default_application() Here is my redis settings. CHANNEL_LAYERS = { "default": { # Use InMemoryChannelLayer for testing only # "BACKEND": "channels.layers.InMemoryChannelLayer" "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], "capacity": 1500, "expiry": 60, "group_expiry": 42300, }, } } relevant views.py class NewAlert(View): def post(self, request): raw = request.body.decode("utf-8") data = json.loads(raw) for new_alert in data.get("alerts"): status = new_alert.get("status") new_alert["status"] = { "state": status, } create_or_update_alert(new_alert).save() gc.collect() return HttpResponse() urls.py urlpatterns = [ path("graphql/", csrf_exempt(GraphQLView.as_view(graphiql=True)), name="graphql"), path("alert/webhook/", csrf_exempt(views.NewAlert.as_view())), path("check", csrf_exempt(views.check_login), name="check_login"), path( "favicon.ico", RedirectView.as_view(url=staticfiles_storage.url("panoptes.ico")) ), path("", views.index, name="index"), path("post_login", csrf_exempt(views.post_login), name="post_login"), path("post_logout", csrf_exempt(views.post_logout), name="post_logout"), ] I am using react.js as a frontend. Tracememalloc only found "" as the largest blocks. https://docs.python.org/3/library/tracemalloc.html#get-the-traceback-of-a-memory-block I built part of the project, but I am taking over the websockets from a former coworker who had never solved the problem. It is a very slow growth. We never have more than 10 connections and … -
Django View: Avoid waiting for post_signal to improve request response time
It seems that before a response is sent back for particular request to an endpoint. All related signals must complete before request is complete. I have a function that takes quite a bit of time to process. How can I delay the function to be called AFTER the response has been sent? @receiver(post_save, sender=User) def user_post_save_func(sender, instance, created, **kwargs): update_user_related_objects(instance)