Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get first -random- interation in a Wagtail Page Queryset that is not the page itself
So I am using Wagtail (a Django CMS) and I on the bottom of a page I need a next button. Which will go to a random Page that is not the current page. I am using a custom context processor for this purpose. My code: from cases.models import CasePage def random_case(request): case = CasePage.objects.live().order_by('?').first() for entry in case: if entry.get_url != request.get_full_path(): return {'random_case': case} So I want to get a random url from the CasePage object. And check it in the template wether this is the url of the current page (and skip that one ofcourse). In the template something like this: {% for entry in random_case %} <a class="ajax-link project-next" href="{{ entry.get_url }}"> <div class="nav-project-title">{{ entry.title }}</div> <div class="nav-title">next</div> </a> {% endfor %} But the above code is not working. How can I do this on the proper way to keep all the logic in the context processor and only use a for loop in the template? -
Django template with javascript rendering problem
I ran into a problem when my template contains some javascript. For instance <script>var i = /{{([a-z]*)}}/gi;</script> Sure enough the template interpreter wants to interpret everything that is in double curled braces {{}} as a variable. Now I wonder if there is a way to turn of such variable interpretation similar to {% autoescape off %}{% endautoescape %}. -
Problem with the Postgresql database installation in django
I have a problem with the postgresql database in dajngo. When I run the command "python -m pip install psycopg2" it works. So I run the command "python manage.py makemigrations", I have this issues : (env) PS C:\projects\first_project\webdev> python manage.py makemigrations Traceback (most recent call last): File "C:\projects\first_project\env\lib\site-packages\django\db\backends\postgresql\base.py", line 20, in import psycopg2 as Database File "C:\projects\first_project\env\lib\site-packages\psycopg2__init__.py", line 50, in from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: specified module not found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\projects\first_project\env\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\projects\first_project\env\lib\site-packages\django\core\management__init__.py", line 357, in execute django.setup() File "C:\projects\first_project\env\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\projects\first_project\env\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\projects\first_project\env\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Louise\AppData\Local\Programs\Python\Python38\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "C:\projects\first_project\env\lib\site-packages\django\contrib\auth\models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\projects\first_project\env\lib\site-packages\django\contrib\auth\base_user.py", line … -
Video storage for a web application
Im developing an API using Python-Django and I need some way to store videos to be retrieved. Should I store the videos in a sql/no-sql db ? , or should they be retrieved in a way from a cloud-storage? or maybe firebase or google-drive? Thanks. -
How to filter SIP character correctly in Django with MariaDB?
I was trying to filter out some data from my database, but it failed filtering and eventually collected all rows from the table when filtering SIP (Supplementary Ideographic Plane) characters such as "𠋫" in ext-B, "𭨡" in ext-F. This only applies in production environment using MariaDB (utf8mb4), but it is totally normal in development environment (SQLite). mysite/settings/production.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', ... 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'; SET NAMES utf8mb4;", 'charset': 'utf8mb4', 'use_unicode': True, } } } enter code here mysite/myapp/views.py def query_dzih(dzih): result = list(Dzih.objects.filter(dzih=dzih)) MariaDB MariaDB [django]> show variables like "chara%"; +--------------------------+----------------------------+ | Variable_name | Value | +--------------------------+----------------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | character_sets_dir | /usr/share/mysql/charsets/ | +--------------------------+----------------------------+ MariaDB [django]> describe myapp_dzih; +---------------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------------+------------+------+-----+---------+-------+ | dzih_no | int(11) | NO | PRI | NULL | | | dzih | varchar(5) | NO | MUL | NULL | | | dzihm | longtext | NO | | NULL | | | dzihs … -
KeyError: 'instance': send_activation_notification(kwargs['instance'])
I am trying to implement registration in Django and faced with error: models.py", line 20, in user_registrated_dispatcher send_activation_notification(kwargs['instance']) KeyError: 'instance' How can I solve the error? Could you recommend good tutorial about registration with email in Django? Full code of the application located here (branch Login-version-2-site ): https://github.com/mascai/reg_app/tree/Login-version-2-site models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Пpoшeл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Email address") password1 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) def clean_password1(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) else: return self.cleaned_data def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = False user.is_activated = False if commit: user.save() user_registrated.send(RegisterUserForm, isinstance=user) return user class Meta: model = AdvUser fields = ('username', 'email', 'password', 'password2', 'first_name', 'last_name', 'send_messages') urls.py from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate urlpatterns = [ path('', views.post_list, name='post_list'), … -
How to send mail after api endpoint is provoked, Django?
My application is using React for frontend and Django & Django RestFramework. I am trying to send email. It is not possible from React Side. So what I thought is to create a Model Mail here in django with class Mail(models.Model): MAIL_SENT= ( ('Y', 'Yes'), ('N', 'No'), ) send_to= models.CharField(max_length=120) reply_to= models.CharField(max_length=120) message= models.TextField() subject= models.TextField() mail_sent= models.CharField(max_length=1, default="Y", choices=MAIL_SENT) def __self__(self): return self.send_to What I want to do is create an API endpoint for Mail and send method at the time of post method. Can anyone please help me with this? -
Django app - data processing on the server
I have some question about some django app. Simple example: On the server I'd like to run some program, which should display some value. Example: for(i in range(10)): print(10**i) sleep(1) So value changes every 1 second without refreshing. It could be some progress bar etc. How to start with it? Celery is the good start? What should I look for? Best regards! -
How to merge similar data into a custom field using serializers in django-rest-framework?
I have an api which returns the material_id,material_name and it's store_id (foreign key) and store_name and it also has a search backend. So i want to return all the material_name and material_id's on one key material and similarly all the store fields in the key store. So i've tried the code below class MaterialSuggestions(generics.ListAPIView): search_fields = ['name', 'shape', 'color', 'material_type', 'surface_type', 'store__name'] filter_backends = (filters.SearchFilter,) queryset = Material.objects.all() serializer_class = MaterialSuggestionsSerializer class MaterialSuggestionsSerializer(serializers.ModelSerializer): class Meta: model = Material fields = ('material','store') material = serializers.SerializerMethodField('get_material') store = serializers.SerializerMethodField('get_store') def get_material(self,obj): return {'material_id':obj.id,'material_name':obj.name} def get_store(self,obj): return {'store_id':obj.store.id,'store_name':obj.store.name} when i call the api i get something like this: { "material": { "material_id": 14, "material_name": "test" }, "store": { "store_id": 28, "store_name": "test1" } }, { "material": { "material_id": 13, "material_name": "test3" }, "store": { "store_id": 29, "store_name": "test2" } } ] This is what I would ideally want to return. { "material": [ { "material_id": 14, "material_name": "test" }, { "material_id": 13, "material_name": "test3" } ] "store": [ { "store_id": 28, "store_name": "test1" }, { "store_id": 29, "store_name": "test2" } ] } or Even this would be great { "material": { "material_id": 14,13 "material_name": "test","test3" }, "store": { "store_id": 28,29 "store_name": "test1","test2" }, … -
Excel random tuple, Convert to python datetime format
How to convert '=RANDBETWEEN(DATE(1975, 1, 1),DATE(2015, 3, 1))' excel date format to python datetime format.its showing ["'=RANDBETWEEN(DATE(1975, 1, 1),DATE(2015, 3, 1))' value has an invalid date format. It must be in YYYY-MM-DD format."] error plz help me how to convert -
Django Form is_valid() missing 1 required positional argument: 'self'
I am trying to create a form(boqform) to post data into a model(boqmodel) but i am getting this typeerror is_valid() missing 1 required positional argument: 'self' I need to display a form called boqform on html template and post the data user entered into boqmodel my view def boqmodel1(request): if boqform.is_valid(): form = boqform(request.POST) obj=form.save(commit=False) obj.save() context = {'form': form} return render(request, 'create.html', context) else: context = {'error': 'The post has been successfully created. Please enter boq'} return render(request, 'create.html', context) -
NoReverseMatch at / in django
Hi Everyone i want to go on detail view but i get this error while paste the url NoReverseMatch at / Reverse for 'test' with no arguments not found. 1 pattern(s) tried: ['test/(?P<pk>[0-9]+)/$'] Here is my Models.py from django.db import models # Create your models here. class article(models.Model): Title = models.CharField(max_length=200) Content = models.CharField(max_length=1000) Here is my Views.py from django.shortcuts import render from django.views.generic import (ListView,DetailView) from .models import * # Create your views here. class Article(ListView): model = article class Test(DetailView): model = article Here is my Urls.py from django.contrib import admin from django.urls import path from cbs import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.Article.as_view(),name="Article"), path('test/<int:pk>/', views.Test.as_view(),name="test"), ] Here is my Article_list.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {% for article in article_list %} <h1><a href="{% url 'test' %}">{{ article.Title }}</a></h1> {% endfor %} </body> </html> -
How do I access a data value in a dictionary in the html template
I'm passing a dictionary in the context in my views.py to my html template. How do I know access a value in the template based on a particular key. For instance I'd wanna do something like {{ dictionary.keyname.value }} but I don't know the correct syntax and for some reason I can't seem to find the documentation. I want to achieve the same effect as this without having to use a for loop: <b>Calories</b> {% for key, value in output.items %} {% if key == "calories" %} {{ value }} {% endif %} {% endfor %} -
how to fix 'Exception in thread django-main-thread'
Here i was trying to print ''Hello world' using django MVT pattern. while running my code got below error. kindly help me to understand where i am doing wrong. expected output was "hello world" but getting below error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\sonal\Envs\test\lib\site-packages\django\urls\resolvers.py", line 586, in url_patterns iter(patterns) TypeError: 'module' object is not iterable -
django.core.exceptions.ImproperlyConfigured: . You must either define the environment variable DJANGO_SETTINGS_MODULE
I made an app djecommerce. Got an django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings in urls.py. Here is my code from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
@get data from browser,but giving lots problems
def page(request): # a = int(request.GET['num1']) # b = int(request.GET['num2']) # val = a + b val1 = request.POST.get(['num1']) a = int(val1) val2 = request.POST.get(['num2']) b = int(val2) val = a+b return render(request,'khushi/block.html',{'result':val}) -
Paging with RawQuerySet
I'm making a raw sql query using Django. I need to do pagination of the output, because for some inputs these queries return more than 100k results which takes a very long time. I cannot use Django ORM because my sql query contains interaction with quite specific postgres plugin (RDKit PostgreSQL cartridge). Currently I am fetching all the results and make the pagination only after that. However, this is really a bottleneck in my program as fetching all the results might take more than a minute for more than 100k rows. # making a specific sql statement sql = compose_sql_statement(parameters) molecules = Molecule.objects.raw(sql) paginator = Paginator(molecules, 10) molecules_page = paginator.get_page(page) -
Django, Custom action functions in GenericViewSet or Viewset
I am trying to implement a basic messaging system. User can get unread/read/sent messages. Each of these routes also returns a different serialized jsons. So I do not have one serializer for the whole ViewSet. To do this I tried to implement ApiView which does not allow me to create custom actions. So I tried Viewset, viewset never hits get_serializer_class (I need this as I need different serialized models returned. So I tried GenericViewSet which seems to work. But Since get_queryset or queryset need to be implemented. I am doing the following. I am checking the action in def get_queryset(self): if self.action is 'unread': return Message.objects.filter(recipient=user,recipient_deleted_at=None,read_at=None) elif self.action is 'recieved': return Message.objects.filter(recipient=user,recipient_deleted_at=None) elif self.action is 'sent': return Message.objects.filter(sender=user,recipient_deleted_at=None) And one of the action is like so def unread(self,request): user = self.request.user message_set=Message.objects.filter(recipient=user,recipient_deleted_at=None,read_at=None) serializer = MessageSerializerFlatList(message_set, many=True) return Response(serializer.data) This works great but again I am querying the db twice, one in the unread action and also once in the get_queryset function. Is there a way to access the returned data from get_queryset function so I do not have re query the information. I mean I can hack the get_query set and just return None and do my db operations in … -
Django automatically converting double quotes to single quotes in text field
I have a very basic django view and serializer and a Postgres database in conjunction with a popular package, dj-stripe. Dj-stripe is saving some json data in a textfield in the database, and it looks like so, with double quotes: {"address":{"city":null,"country":null,"line1":null,"line2":null,"postal_code":"94303","state":null},"email":null,"name":"Jenny Rosen","phone":null} Unfortunately, it seems that something (django? python?) is converting it to single quotes, (and adding some spaces after colons) as so: {'address': {'city': None, 'country': None, 'line1': None, 'line2': None, 'postal_code': '94303', 'state': None} My view is very basic: class GetCustomerView(generics.ListAPIView): authentication_classes = (TokenAuthentication,) PaymentMethodSerializer def list(self, request): customer = Customer.objects.get(subscriber=request.user.organization_id) cards = PaymentMethod.objects.filter(customer=customer.djstripe_id) serializer = PaymentMethodSerializer(cards, many=True) pprint(serializer.data) if cards: return Response(serializer.data) else: return Response('error', status=status.HTTP_400_BAD_REQUEST)` and my serializer is basic too: class PaymentMethodSerializer(serializers.ModelSerializer): card = json.loads(serializers.JSONField()) billing_details = json.loads(serializers.JSONField()) class Meta: model = PaymentMethod fields = ( 'id', 'billing_details', 'card',) Obviously it would probably be best stored in a JSONB field, but changing the package is not an option. That said, how do I go about preventing this conversion? -
DRF: Unable to make authenticated calls with token in header
I have a list view that is authenticated but whenever I try to make a request with the token in the header, I get a 400 error. Any ideas? list view class EventListView(ListAPIView): authentication_classes = () permission_classes = (IsAuthenticated, ) serializer_class = EventFilterSerializer ... Postman Screenshot -
Is it possible in Django to grab a field from the first foreign key?
I'm trying to optimize my Django query. Right now, I'm grabbing all products, then looping through them and making a separate query for the 'feature' image url. Is there a way to grab the url for the 'Image' foreign key object where feature = True in the original query? Current Code: products = Product.objects.values('id') for product in products: image_url = Image.objects.filter(product=product["id"]).order_by('-feature').values("url").first().get("url", None) print(image_url) What I wish I could do: products = Product.objects.values('id', 'images__url') for product in products: print(product["images__url"] When I try this, it seems to return a Product for each Image, which is not at all what I want. To remedy this I tried to add a .distinct('id') on the end, but then I got this error: NotImplementedError('annotate() + distinct(fields) is not implemented.') After that I wasn't sure how to proceed, or if this is possible? Models (for reference): class Product(models.Model): title = models.CharField(max_length=255) class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, related_name="images") url = models.CharField(max_length=255, blank=True) feature = models.BooleanField(default=False) Any help much appreciated! -
What does this mean in the django documentation about class-based views?
A rookie here. As I am reading the django documentation, I came up with a note that I cannot fully understand. It says: Note While your class is instantiated for each request dispatched to it, class attributes set through the as_view() entry point are configured only once at the time your URLs are imported. Here is the link: https://docs.djangoproject.com/en/2.2/topics/class-based-views/intro/ So which one is better? What advantage does each have? I've tried both and cannot experience any difference(Pretty sure that's because I've not considered enough) -
Pillow not uploading pictures in Django
I am not sure what i am doing wrong below but Pillow is not uploading the picture when I edit a user profile. from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models from django.core.validators import RegexValidator from PIL import Image class CustomUser(AbstractUser): GENDER_CHOICES = ( ('Male', 'Male'), ('Woman', 'Woman'), ) profile_picture = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.CharField(max_length=200) phone_number = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) is_host = models.BooleanField(default=False) gender = models.CharField(max_length=30, choices=GENDER_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) forms.py from django.contrib.auth import get_user_model from django.forms import ModelForm from django import forms from users.models import CustomUser User = get_user_model() class EditProfileForm(ModelForm): class Meta: model = CustomUser fields = [ 'username', 'first_name', 'last_name', 'bio', 'phone_number', 'gender', 'profile_picture', ] views.py def edit_profile(request, id): """Update user profile.""" user = get_object_or_404(User, id=id) form = EditProfileForm(request.POST or None, instance=user) if form.is_valid(): form.save() messages.success(request, 'Your account was updated successfully') return redirect('users:profile') context = {'form': form} return render(request, 'users/edit-profile.html', context) project-urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls', namespace='users')), path('', include('core.urls', namespace='core')), path('auth/', include('django.contrib.auth.urls')), ] # Media Files URL if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py # Static files STATIC_ROOT = os.path.join(BASE_DIR, … -
How can I serialize an object in queryset TruncYear Django 1.11
I manage to get time series data with TruncYear/TruncMonth/TruncDay/etc like below from Tracking table. However the data for the venue just produce the venue_id. I would like to have that serialized so that it returns the "name" from the relation Venue table. I am using Django 1.11 a postgres 9.4 Here is my time series code: tracking_in_timeseries_data = Tracking.objects.annotate( year=TruncYear('created_at')).values('year', 'venue_id').annotate( count=Count('employee_id', distinct = True)).order_by('year') return Response(tracking_in_timeseries_data, status=status.HTTP_200_OK) currently it output like this: [ { "venue_id": 4, "year": "2017-01-01T00:00:00Z", "count": 1 }, { "venue_id": 2, "year": "2018-01-01T00:00:00Z", "count": 2 }, { "venue_id": 6, "year": "2019-01-01T00:00:00Z", "count": 1 } ] I want to explode venue data to return the id & name like this: [ { "venue": { id: 4, name: "room A" }, "year": "2017-01-01T00:00:00Z", "count": 1 }, { "venue": { id: 2, name: "room B" }, "year": "2018-01-01T00:00:00Z", "count": 2 }, { "venue": { id: 6, name: "room C" }, "year": "2019-01-01T00:00:00Z", "count": 1 } ] How to explode the "venue" to return the id and name. The name is useful for presentation purpose. -
range() on QuerySet
I am trying to add a progress bar to a loop of Django objects. So I need to put the list (QuerySet) in range() so I can get the number of total loop iteration. Code: rows = DjangoObjects.objects.all() for i in tqdm(range(rows)): row = rows[i] ... Error: range() integer end argument expected, got QuerySet.