Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add custom tags to sentry event dynamically
I want to add a dynamic tag to all sentry events being logged. Django 1.11 sentry_sdk 0.9.5 python 3.5 def init_sentry_integration(sentry_dsn, app_env, release=None): import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( environment=app_env, dsn=sentry_dsn, integrations=[DjangoIntegration()], attach_stacktrace=True, release=release) add_tenant_tag() def add_tenant_tag(): hub = Hub.current logging_integration = hub.get_integration(LoggingIntegration) if not logging_integration: return handler = logging_integration._handler old_emit = handler.emit def new_emit(record): with push_scope() as scope: tenant_schema_name = connection.get_tenant().schema_name scope.set_tag("tenant", tenant_schema_name) return old_emit(record) handler.emit = new_emit Tried monkey patching it but it di -
(Django REST) Override Non-Editable Field in the `create` Method
In my models.py, I create a field that is supposed to be non-editable by the user: request_status = models.CharField( max_length = 100, default = 'received', editable = False ) In the views.py file, I override the create() method (from the generics.ListCreateAPIView and CreateModelMixin superclasses) to activate a docker container and, if it is successfully done, I want to modify the request_status field to something like container_activated and then send back the HTTP response to the user. So... is there a way of modifying a non-editable field? Is there a better way of setting up the model instead? My best guess is that there is a way of modifying the data that gets registered in the API DB through one of the lines of the standard create() method (non-editable fields do not appear in the data property): serializer = self.get_serializer(data = request.data) serializer.is_valid(raise_exception = True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) -
Please why is there a circular import error
I am working on a django project, but it returns the included urlconf "myapp.urls"does not appear to have any patterns in it. I tried checking my views to ensure I imported everything correctly from django.contrib import admin from django.urls import path from .views import home from accounts.views import login_view urlpatterns = [ path('admin/', admin.site.urls), path('',home), path('accounts/login/', login_view), ] I expect the site to run and redirect me to the login page This is my views in the same directory with the urls.py @login_required def home(request): return render(request,"home.html") -
Django contact form modal ? can i pass a form as extra context?
I have a contact form with bootstrap modal.The problem is the form is out of shape and isn't rendered right.so how can i render it right and fix the modal? here's the form class ContactForm(forms.Form): subject = forms.CharField(max_length=720,label="Subject",required=True) message = forms.CharField(widget=forms.Textarea( attrs={'placeholder': 'Enter your message here'}),label="Message",required=True) the views def emailView(request): user = request.user if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = user.email message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message.') The Template <div class="modal fade" id="modalContactForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <form method="POST" action="{% url 'contact' %}"> {% csrf_token %} so how can i render the form right ?can i pass the form as extra context as the form is shown as a modal in the homepage ? <div class="modal-header text-center"> <h4 class="modal-title w-100 font-weight-bold">Write to us</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="md-form mb-5"> <i class="fas fa-tag prefix grey-text"></i> <label data-error="wrong" data-success="right" for="form32">Subject</label> <input type="text" id="form32" class="form-control validate"> </div> <div class="md-form"> <i class="fas fa-pencil prefix grey-text"></i> <label data-error="wrong" data-success="right" for="form8">Your message</label> <textarea type="text" id="form8" … -
What are the differences between http and socket inside of ini file in uWSGI?
I'm learning nginx and uwsgi to deploy my Django web app. While learning them, I got confused with "socket" and "http". I think I should write .ini like the following. when I use only uwsgi ... http=127.0.0.1:8001 ... when I use uwsgi and nginx and I want to make clients connect to my server through nginx ... socket=127.0.0.1:8001 ... When I only use uwsgi to run my server, I guess I should use "http" instead of "socket" in .ini file http=127.0.0.1:8001 because if i use "socket" it emits errors when clients connect to my server, like this. invalid request block size: 21573 (max 4096)...skip However, when I use nginx with uwsgi, I should use socket instead of http. If I use http, I guess the server emitted timeout error. My codes this is my codes that works in /etc/nginx/sites-available/blog.conf upstream blog{ server 127.0.0.1:8001; } server { listen 80; server_name 127.0.0.1; charset utf-8; client_max_body_size 75M; # adjust to taste location /static { alias /django_static/djProject; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass blog; } } in project directory, app.ini [uwsgi] plugins=python3 chdir={myProject location} module=djProject.wsgi:application # Settings module, relative to the chdir path env='DJANGO_SETTINGS_MODULE=djProject.settings' # Python virtual env path home=/home/su/uwsgi/uwsgi-tutorial # File used … -
i am getting error while integrating angular js code into the django application error:csrf missing
enter image description here above error, I am getting -
Change data visibility and permission on Geonode
I am working on Geonode and when I add a new layer, people who are not logged in are not suppose to see the layers but I would like to change it and allow it to everyone. I saw on an old forum that it was possible by changing the SKIP_PERMS_FILTER in a file and the read_list too, but I am not use to django and I don't know what to change. SKIP_PERMS_FILTER = strtobool(os.getenv('SKIP_PERMS_FILTER', 'False')) def read_list(self, object_list, bundle): permitted_ids = get_objects_for_user( bundle.request.user, 'base.view_resourcebase').values('id') return object_list.filter(id__in=permitted_ids) -
Serializers not displaying foreign key data
My serializers are not showing related Models. I mean the models that have got many-to-one relationship. Please see the code below. Forgive my English. Completely confusing me please help. I am new to django. I am trying to save my Draft js ContentState to the database. I have made the Post model a Foreignkey to my Block models. But When I try to retrieve the data using django-rest-framework serializers the blocks are not displaying. Same applies with the Blocks I tried to serialize them on their own but the inlineStyleRanges and entityRanges data is not coming up. #models.py class Post(models.Model): created_by= models.ForeignKey(User, on_delete=models.CASCADE) cat= models.ForeignKey(Category, on_delete=models.CASCADE) class Block(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) key = models.CharField(max_length=255) text = models.TextField() type = models.CharField(max_length=90) depth = models.IntegerField(default=0) class InlineStyleRange(models.Model): block = models.ForeignKey(Block, on_delete=models.CASCADE) offset = models.IntegerField() length = models.IntegerField() style = models.CharField(max_length=90) class EntityRange(models.Model): block = models.ForeignKey(Block, on_delete=models.CASCADE) offset = models.IntegerField() length = models.IntegerField() key = models.IntegerField() class Data(models.Model): data = models.TextField() class EntityRangeData(Data): enityrange = models.ForeignKey(EntityRange, on_delete=models.CASCADE) #Entity map here we go class EntityEntry(models.Model): key = models.IntegerField() block= models.ForeignKey(Block, on_delete=models.CASCADE) type = models.CharField(max_length=90) mutability = models.CharField(max_length=90) class EntityEntryData(Data): entityentry = models.ForeignKey(EntityEntry, on_delete=models.CASCADE) ```#Serializers.py``` class EntityEntryDataSerializer(serializers.ModelSerializer): class Meta: model = models.EntityEntryData fields = … -
Trying to create an efficient way to produce a cross join with combined results
Let's assume we have these models: class ClassRoom(models.Model): name = models.CharField(max_length=255) class Student(models.Model): name = models.CharField(max_length=255) classroom = models.ForeignKey(ClassRoom...... class Course(models.Model): name = models.CharField(max_length=255) class Grades(models.Model): student = models.ForeignKey(Student.... course = models.ForeignKey(Course.... grade = models.CharField(..... I want to create the crossjoin of the courses and students, but with the grades in the table. | | Student A | Student B | | Course 1 | 8 | | | Course 2 | 6 | 4 | Please note that student B did not receive a grade for course 1 yet! I currently solve this like this query = list(product(courses, students) grades = Grades.objects.all..... for i, query_tuple in enumerate(query): grade = grades.filter(query_tuple[0], query_tuple[1] if grade: # Note 1 # Here I add it to a list of the grades But at the point of '# Note 1' it runs an query each time, which drastically decreases performance (A class can have up to 30 students with each more that 50 courses). Is there a better way to do this? Maybe more in Django-ORM style? -
django security: can an indirect view be called by a non-admin?
Say I have the following methods @staff_member_required def foo(request): return say_hello(request) def says_hello(request): #do secret stuff return "hello And in urls.py path("/hello", foo) As you can see, I have only exposed foo to my admins. From a security standpoint, is it ever possible for a non-admin to call say_hello()? -
How to edit image dimensions before saving to model (database) using ImageField.update_dimension_fields() in Django
I am trying to implement a Django ImageField class function for resizing images however I am not certain where this function accepts my new image dimensions Running on Linux and Python 3.7 I've had a look at this documentation, but can't quite make sense of it: https://docs.djangoproject.com/en/1.11/_modules/django/db/models/fields/files/#ImageField I'd really appreciate it if someone can show me an example of how to use this function. class Posts(models.Model): title = models.CharField(max_length=200, blank=True) body = models.TextField(blank=True) created_at = models.DateTimeField(default=datetime.datetime.now) post_image = models.ImageField(upload_to=get_image_path, blank=True, null=True) def __str__(self): return self.title def save(self, *args, **kwargs): # I would like to use the function beneath to resize my images before I save them to my database self.post_image.update_dimension_fields(self, instance, force=False, *args, **kwargs) super().save(*args, **kwargs) # Call the "real" save() method. class Meta: verbose_name_plural = "Posts" -
Django test if json and if content is present
I have to test if a url returns json, which I can do with self.assertJSONEqual( str(response.content, encoding='utf8'), [{"id": self.group.pk, "text": "Guest", "state": {"opened": True}, "li_attr": {"id": self.group.pk}, "a_attr": {"href": "#"}, "parent": "#"}] ) If the response is huge I have to paste the whole response in the second parameter. Is there a way to test if the response is json, no matter of the content? -
How to you negate a q object within a query?
I want to negate a Q object if a specific condition is met without having to duplicate multiple queries in a view. I have tried breaking the query into multiple functions but I cannot help but think I still have a large amount of duplicated code. query = User.objects.all() if active: query.filter(Q(active=active)) elif active == False: query.filter(Q(active=active) | Q(active__isnull=True)) else: query.filter(Q(active__isnull=True) | Q(setup=False)) -
Make user required to complete profile info first before checking out
I'm very new to Django and trying to create my first e-commerce website. I have a "User" app which the user could go there and enter their name, and address. The problem i'm facing is that I want the user to complete the profile first before they could checkout from the shopping cart. If the user didn't create the profile yet, i want to redirect them to that url. I have a very little knowledge on authentication, so please someone help giving me some clue -
How to join two tables in Django ORM without any column in first table referencing the second
Check the models below Now I want to join the tables and get product name and price I cannot join the tables as I have no column in Product model referencing Price model class Product(models.Model): name = models.CharField(max_length=100) class Price(models.Model): price = models.ForeignKey(Product) -
I need to know the technology used in building a page like this
I want to know the technology used in building a web page like this , a Cisco webpage. webpage link django developers input also required for backend . -
Django ModuleNotFoundError: frozen importlib._bootstrap>", line 953
python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python3/dist-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_project' import os import netifaces def ip_addresses(): ip_list = [] for interface in netifaces.interfaces(): addrs = netifaces.ifaddresses(interface) for x in (netifaces.AF_INET, netifaces.AF_INET6): if x in addrs: ip_list.append(addrs[x][0]['addr']) return ip_list BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '...' DEBUG = False ALLOWED_HOSTS = ['...'] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'accounts', 'hashtags', 'tweets', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'django_project.urls' LOGIN_URL ="/login" LOGIN_REDIRECT_URL ="/" LOGOUT_REDIRECT_URL ="/" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
django how to get model field as object
Is it possible to get model's field as object For example: I have this model class User(models.Model): name = models.CharField(max_length=255) email = models.TextField(blank=True) phone = models.TextField(blank=True) now I want to use the field as object I want to be able to do this def update_a_field(field): model_field = field query_set = User.objects.values(field.__name__).filter(field__isnull=False) then I can call my function like this update_a_field(name) update_a_field(email) -
When add cors in settings, the server stops working. Error 502 Bad Gateway
I add in project settings INSTALLED_APPS = [ ..., 'corsheaders', ..., ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ] + MIDDLEWARE CORS_ORIGIN_WHITELIST = [ 'http://url.ru', 'https://url2.ru', 'https://url3.ru', ] After adding - any server url stops working. with the error 502 Bad Gateway nginx/logs/error.logs [error] 1986#1986: *9504 connect() failed (111: Connection refused) while connecting to upstream, client: **.***.***.**, # IP server: server-url, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:9000/favicon.ico", host: "server-url", referrer: "server-url/api/title/20/" -
cannot import name patterns with Django1.6
Python v2; Django v1.6 when i start server, i get a error 'ImportError: cannot import name patterns' Code: from django.conf.urls import patterns, include, url urlpatterns = patterns( '', url(r'^payment/', include('payment.urls', namespace='payment', app_name='payment')), ) Next: i has tried to change import code like this: from django.conf.urls import * but get another error: 'NameError: name 'patterns' is not defined' pls help -
Django ORM: checking if a field is blank or filled
title = models.ForeignKey(blank=True, null=True) I am trying to check if title filed is filled or blank, how can i achieve this? -
Filtering related models using django-filters
There are two related models class Skill(models.Model): """Information about an employee's skills.""" LEVELS = ( ('basic', 'Basic'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced'), ('expert', 'Expert'), ) YEAR_CHOICES = [] for r in range(1, 11): YEAR_CHOICES.append((r, r)) employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) year = models.IntegerField(verbose_name='Duration of technology use (years)', choices=YEAR_CHOICES, default=1) level = models.CharField("level", max_length=64, choices=LEVELS) def __str__(self): return '{} is {} in {}'.format( self.employee.full_name, self.level, self.technology.name) class Project(models.Model): """Project information.""" name = models.CharField("project name", max_length=64) description = models.TextField("project description") technologies = models.ManyToManyField( Technology, verbose_name="technologies used on the project") def __str__(self): return self.name filters.py class EmployeeFilter(django_filters.FilterSet): skills = django_filters.ModelChoiceFilter(queryset=Technology.objects.all()) class Meta: model = Employee fields = ['skills'] template.html <form method="get"> <div class="card-body"> <div class="row"> <div class="form-group w-100"> <label for="skills">Technology</label> {% render_field filter.form.skills class="form-control bg-light" %} </div> </div> <button type="submit" class="btn btn-warning"> <span ><i class="fas fa-search"></i></span> Search </button> <button type="button" class="btn btn-secondary"><span ><i class="fas fa-recycle fa-fw"></i></i></span><a href="{% url 'account_list' %}" class="text-white">Clear</a></button> </div> </form> In this case, the skills search works, i.e. I get filtered users with the selected values from the Technology model, but I need to pull the level from the Skills model, and with this complexity. The user model contains a link to the Technology model class … -
Can i use sqlite3 for simple django blog application in production?
After hours of watching tutorials and reviewing the documentations of django and heroku, i finally deployed my simple django web application. For the database part, i came to know about an issue using sqlite database as default database for production. I fear that i lose my records after deploying the application once done, as said by heroku themselves. I am currently having one user, who post posts and announcements in the website and public viewers can only view it. My question is, is it correct to use sqlite database for production or will the free postgres database be enough for what i am doing with? -
Unable to connect to server: PgAdmin 4
I have installed pgadmin on a new laptop and when I try to create a new server, it says: When I try to run my django app in pycharm it is giving me the same error could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? How to solve this ? -
Django: Email being sent as html for password reset
The email sent for resetting password are being displayed as raw HTML content. This is not the case for every users but for significant number of users, this problem arrives. This is my url for password reset: from django.contrib.auth.views import password_reset url(r'^accounts/password/reset/', password_reset, {'template_name':'users/login.html','html_email_template_name':'registration/password_reset_email.html', 'post_reset_redirect':'/users/accounts/login/?reset=1', 'extra_context':{'reset':'1'}}, name='password_reset'), These are my password reset email templates: registration/password_reset_email.html {% extends 'users/email_base.html' %} {% block content %} {% load i18n %} <table width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f0f0" align="center"> <tbody> <tr> <td style="font-size:0;" align="center"> <div style="display:inline-block;width:100%;max-width:800px;vertical-align:top;" class="width800 mrt-30"> <!-- ID:BG SECTION-1 --> <table class="display-width" style="max-width:800px;" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff" align="center"> <tbody> <tr> <td class="padding" align="center"> <div style="display:inline-block;width:100%;max-width:600px;vertical-align:top;font-family:Ubuntu, sans-serif;" class="main-width"> <table class="display-width-inner" style="max-width:600px;" width="100%" cellspacing="0" cellpadding="0" border="0" align="center"> <tbody> <tr> <td style="mso-line-height-rule:exactly;line-height:30px;font-size:0;" height="30"> </td> </tr> <tr> <td style="mso-line-height-rule:exactly;line-height:10px;font-size:0;" height="10"> </td> </tr> <tr> <td style="color:#666666;font-family:Ubuntu, sans-serif;font-weight:400;font-size:14px;line-height:24px; text-align:justify;"> {% blocktrans %} You're receiving this email because you requested a password reset for your user account at {{ site_name }}. {% endblocktrans %} </td> </tr> <tr> <td style="color:#666666;font-family:Ubuntu, sans-serif;font-weight:400;font-size:14px;line-height:24px; text-align:justify;"> Please go to the following page and choose a new password: {% block reset_link %} https://{{ domain }}{% url 'auth_password_reset_confirm' uidb64=uid token=token %} {% endblock %} Your username, in case you've forgotten: {{ user.get_username }} </td> </tr> <tr> …