Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework : Only last record is saved in DB when trying to call "perform_create" function iteratively
I'm newbie in Django and trying to build API server using Django Restframework. With sincere help from @cagrias, I got a success in parsing json and save several records in my DB. Now, I'm struggle in saving multiple records in my DB with iteratively call 'perform_create' function. My View.py function is as follows. models have 6 tables BankA, BankB, BankC, and CardA, CardB, CardC. What I want to is save 4 records when call the post api, but now, only last one(('카드매출', sales_card)) is saved. I hope your help, and it will be very grateful for me. Thank you. # API to save trading history (aggregated Purchase/Sales for Bank/Card) class SalesAndPurchaseInPeriodListView(ListCreateAPIView): def post(self, request): quiry = request.data serializer = SalesAndPurchaseInPeriodListSerializer(data=request.data) banklist = [BankA, BankB, BankC] cardlist = [CardA, CardB, CardC] # Purchase Bank purchase_bank = 0 for bank in banklist: records_bank = bank.objects.filter(resAccountIn='0', creator_id=request.user.id) for record in records_bank: purchase_bank += record.resAccountOut # Purchase Card purchase_card = 0 for card in cardlist: records_card = card.objects.filter(creator_id=request.user.id) for record in records_card: purchase_card += record.resUsedAmount # Sales Bank sales_bank = 0 for bank in banklist: records_sales_bank = bank.objects.filter(resAccountIn='0', creator_id=request.user.id) for record in records_sales_bank: sales_bank += record.resAccountOut # Sales Card sales_card = 0 for card … -
Android phone no longer wants to connect to Django server
I've been running a Django server for the past few days and have been using my phone to make POST requests and such. However, today my phone doesn't see the server anymore. I have made no changes to my server since last night. I think it's a problem with my phone because I can connect to the server through my other Windows machine, also on the same network. At first, I thought it was the fact that they have different IP addresses but the Windows computer that can connect also has a different IP address and connects fine: Windows computer running Django server: 10.35.24.13 Windows computer able to connect: 10.35.105.108 Android phone unable to connect: 10.35.109.137 If it helps, Chrome on the phone displays: This site can't be reached. http://10.35.24.13:8181/ is unreachable. ERR_ADDRESS_UNREACHABLE I'm completely baffled and have no idea what's wrong. Any suggestions are appreciated. Thanks. -
Django TemplateView get template from a field from DB
I want create a templateview but need to use a editable template on-the-fly, to this i can set a template from a code stored inside a field from a table. # some_app/views.py from django.views.generic import TemplateView class AboutView(TemplateView): template_name = "about.html" -> from table.field Some ideia? -
Django Listview Displays 0 results
I have a weird situation (translation: I'm missing something obvious) where I have a ListView that renders fine when I iterate over each object in my queryset and yield, but returns 0 results when I just return the queryset. class TestListView(ListView): model = Result context_object_name = 'results' template_name = 'cases/test_list2.html' def get_queryset(self): # Get latest results results = Result.objects.filter(canonical=True, environment__config__in=['staging', 'production']).order_by('test__id', '-created_at').distinct('test__id').select_related('test', 'environment') # Return Queryset return results # type <class 'django.db.models.query.QuerySet'>, returns 0 elements from view for result in results: yield result # returns correct number of results, assuming above 'Return Queryset' line is commented out What am I doing incorrectly? -
TypeError: config() got an unexpected keyword argument 'ssl_require'
I am trying to launch a django app using heroku and got the following error TypeError: config() got an unexpected keyword argument 'ssl_require' when running 'heroku run python manage.py migrate' in Django project using Heroku The complete output is Running python manage.py migrate on ⬢ serene-taiga-89672... up, run.6367 (Hobby) Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/friendzone/settings.py", line 212, in <module> django_heroku.settings(locals()) File "/app/.heroku/python/lib/python3.7/site-packages/django_heroku/core.py", line 69, in settings config['DATABASES']['default'] = dj_database_url.config(conn_max_age=MAX_CONN_AGE, ssl_require=True) File settings.py is import os import dj_database_url import django_heroku import dotenv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for … -
Setting pagination_class in Django ListAPIView causes Runtime Error
I have a class-based view for text messages inheriting from the django generic view ListAPIView. As you can probably tell from the inheriting class name, the view is being used as an API with pagination (from the Django Rest framework). I would like to turn off pagination for some specific queries, however even when I try turning off pagination for all queries via this stack overflow question (Turn off automatic pagination of Django Rest Framework ModelViewSet), I get the following error: RuntimeError: Do not evaluate the `.queryset` attribute directly, as the result will be cached and reused between requests. Use `.all()` or call `.get_queryset()` instead. I am overwriting the get_queryset() method in the view without issue, however by just setting the paginator_class variable to None I am receiving this error. Any help would be appreciated. Here's some code: view.py: class TextMessageView(generics.ListAPIView): queryset = TextMessage.objects.all() serializer_class = TextMessageSerializer pagination_class = None def get_queryset(self): """ If a phone number is included in the url query, return only the text messages sent by that number in the queryset, otherwise return all text messages. :return: A Django queryset with a variable number of text messages. """ from_phone_num = self.request.query_params.get('from_phone_number', None) distinct_nums = self.request.query_params.get('distinct_numbers', None) … -
Can I write a function that takes data from two different tables, transforms it and saves to a third table in Django?
I'm making a carpooling service app. I have 2 tables: drivers and passengers. I have an algorithm to match users from the 2 tables. I need a script/function that takes data from the 2 tables, implements the algorithm and saves the output to a third table. What is the best way to do this? (I'm very new to Django) Can I make the script/function be executable from the shell? -
DJANGO+REACT (Failed to load resource)
I follow the tutorials here https://www.youtube.com/watch?v=r0ECufCyyyw&list=PLLRM7ROnmA9FxCtnLoIHAs6hIkJyd1dEx&index=5&t=0s then i have problem like this: image plz help me, thanks a lot -
Django Multiple Users can view single model object
How to define a condition where we can set multiple users access for that single model object. Let's suppose we have the following model. class Project(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.TextField() And i have 2 users: admin and jobert Since user field in above model is single one to one field which means either admin or jobert are saving that object. if that object created by admin then jobert can't see that object and vice-versa for jobert. How do i made that user field to accept or allow multiple users to access that object. i want adminand jobert users to access that model object. -
ModuleNotFoundError: No module named 'django.contrib.static'
Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.6/site-packages/six.py", line 693, in reraise raise value File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.6/site-packages/six.py", line 693, in reraise raise value File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in __call__ response = response or self.get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/usr/local/lib/python3.6/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.6/site-packages/six.py", line 693, … -
URL in the Django REST API
Serializer looks like this: class Require_assistanceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=Require_assistance fields=('id', 'url', 'title','description') REST API works well without the 'url' field. Some tutorials show that HyperlinkedModelSerializer must generate that url but I get the error. I think it is written that there is no detail view for the 'url'. ImproperlyConfigured at /en/buyers_apprest_apiRequire_assistance/ Could not resolve URL for hyperlinked relationship using view name "require_assistance-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. urls.py from django.conf.urls import url from django.urls import include, path from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('Require_assistance', views.Require_assistanceView) app_name = "buyers_app" urlpatterns=[ path('rest_api',include(router.urls)), ] views: from django.shortcuts import render from .models import Require_assistance from django.views import generic from rest_framework import viewsets from .models import Require_assistance from .serializers import Require_assistanceSerializer class Require_assistanceView(viewsets.ModelViewSet): queryset=Require_assistance.objects.all() serializer_class=Require_assistanceSerializer Do you have any idea how to display the URL for the detailed view without this error? -
Django/Celery 4.3 - jobs seem to fail randomly
These are the tasks in tasks.py: @shared_task def add(x, y): return x * y @shared_task def verify_external_video(video_id, media_id, video_type): return True I am calling verify_external_video 1000+ times from a custom Django command I run from CLI verify_external_video.delay("1", "2", "3") In Flower, I am then monitoring the success or failure of the jobs. A random number of jobs fail, others succeed... Those that fail, do so because of two reasons that I just cannot understand: NotRegistered('lstv_api_v1.tasks.verify_external_video') if it's not registered, why are 371 succeedings? and... TypeError: verify_external_video() takes 1 positional argument but 3 were given Again, a mystery, as I quit Celery and Flower, and run them AGAIN from scratch before running my CLI Django command. There is no code living anywhere where verify_external_video() takes 1 parameter. And if this is the case... why are SOME of the calls successful? This type of failure isn't sequential. I can have 3 successful jobs, followed by one that does not succeed, followed by success again, so it's not a timing issue. I'm at a loss here. -
Django timezone struggles
I am having difficulty getting queryset results in my own timezone. for example: model field definition: some_datetime_field= models.DateTimeField(null=True) Query: MyModel.values_list("some_datetime_field",flat=True).first() returns datetime.datetime(2019, 11, 5, 14, 56, 16, tzinfo=<UTC>) instead of returning datetime.datetime(2019, 11, 5, 6, 56, 16, tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>) I am working with python V3.7.5, Django V2.2.7 and PostgreSQL V12 as my database. In my setting I have: TIME_ZONE = "America/Los_Angeles" USE_TZ = True USE_I18N = True USE_L10N = True From the documentation it says with regard to the "TIME_ZONE" settings: (https://docs.djangoproject.com/en/2.2/ref/settings/#time-zone) When USE_TZ is True and the database supports time zones (e.g. PostgreSQL), it is an error to set this option. so I tried to remove the TIME_ZONE from my setting: USE_TZ = True USE_I18N = True USE_L10N = True but that didnt work either, even worse, when I try to localize it with timezone.localtime(datetime_example) i get the time in Chicago time: datetime.datetime(2019, 11, 5, 8, 56, 16, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>) How can I get my query set to return DateTime in my chosen timezone instead of UTC? -
Django: annotate QuerySet with number of seconds since object created
I have a model, call it Foo, which has an attribute created_at which notes the time (UTC) when an instance was created. I would like to annotate a query set over this model with the number of seconds since each item returned was created. (to be more precise, I would like to "discount" items based on the time they have been open, with a configurable stale-out time, but I can do that computation if I can get the number of seconds since create) I have tried some obvious things like Foo.objects.annotate(time_since_create=now-F('created_at')) and Foo.objects.annotate(time_since_create=now.timestamp()-F('created_at')) but these get me AttributeError: 'float' object has no attribute 'tzinfo', which suggests that DB arithmetic on dates is a little more complex than I'm thinking it ought to be. Obviously, I can do this arithmetic in python, ie, [(id, now-created_at) for id, created_at in Foo.objects.values_list("id", "created_at")] but it would be nicer if I could get this back in the queryset. -
WebDriverException at / Service /usr/bin/chromium-browser unexpectedly exited. Status code was: 127
I'm trying to run my crawler using selenium, webdriver and xvfb on pythonanywhere server (if it can help). I also tried to use pyvirtualdisplay instead of xvfb to create a browser window for webdriver. But I keep receiving error "Message: Service /usr/bin/chromium-browser unexpectedly exited. Status code was: 127" Traceback: File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/Sayn0toWar/parser_test/parser_test/main/views.py" in index 13. main(int(iterations)) File "/home/Sayn0toWar/parser_test/parser_test/main/parser_script.py" in main 111. b = Bot(iterations) File "/home/Sayn0toWar/parser_test/parser_test/main/parser_script.py" in init 24. self.driver = webdriver.Chrome(executable_path='/usr/bin/chromium-browser', chrome_options=options) File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/selenium/webdriver/chrome/webdriver.py" in init 73. self.service.start() File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/selenium/webdriver/common/service.py" in start 98. self.assert_process_still_running() File "/home/Sayn0toWar/.virtualenvs/parser/lib/python3.7/site-packages/selenium/webdriver/common/service.py" in assert_process_still_running 111. % (self.path, return_code) Exception Type: WebDriverException at / Exception Value: Message: Service /usr/bin/chromium-browser unexpectedly exited. Status code was: 127 My code: from bs4 import BeautifulSoup from selenium import webdriver from webdrivermanager import ChromeDriverManager from xvfbwrapper import Xvfb from pyvirtualdisplay import Display from time import sleep class Bot: def __init__(self, iterations): display = Display(visible=0, size=(800, 600)) display.start() cdm = ChromeDriverManager() chromedriver_path = cdm.download_and_install() options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') self.driver = webdriver.Chrome(executable_path='/usr/bin/chromium-browser', chrome_options=options) self.navigate(iterations) self.close() display.stop() I am sorry for my code, i'm not good at … -
Count number of attributes of a class
I want to make a fully dynamic table which adjusts its self number of columns depending on which type of object I'm passing in the view. What I tried is: from Food.models import Food for field in Food: # Count how many fields do my class Food has. But PyCharm is showing the following error: Expected 'collections.Iterable', got 'Type[Food]' instead. Pretty obvious since it's not an actual initialized object. But how can I achieve this? Thanks! -
How to use field value as a label in Django formsets? E.g. datagrid where one field's value is a label for another field (changeable)
I'm trying to display piece of a data-grid (product specifications table) as a form, but can't figure out how to use value of one column as a label for another column. E.g: Feature name (as label) .. Feature value (as an input). so far my code is this: models.py class ProductSpecs(models.Model): sku = models.CharField(max_length=30, blank=False) f_feature = models.CharField(max_length=100, blank=False) f_value = models.TextField(blank=True) f_unit = models.CharField(max_length=20, blank=True) ic_feature_name = models.CharField(max_length=50, blank=True) ic_feature_id = models.SmallIntegerField(blank=True) ic_feature_type = models.CharField(max_length=30, blank=True) ic_value = models.CharField(max_length=100, blank=True) last_update = models.DateTimeField(default=timezone.now, blank=True) status = models.CharField(max_length=20, blank=True) def __repr__(self): return str(self.sku) views.py def product_specs(request, pk): obj = BrandMainData.objects.get(pk=pk) prod_specs = ProductSpecs.objects.filter(sku=obj.sku).all() if prod_specs: spec_formset = modelformset_factory(ProductSpecs, fields=('ic_feature_name', 'ic_value',), widgets={'ic_feature_name': TextInput(attrs={'readonly': True, 'disabled': True, 'border':'none'})}) if request.method == 'POST': formset = spec_formset(request.POST) formset.save() return HttpResponseRedirect('') else: formset = spec_formset(queryset=prod_specs) context = { 'formset': formset, 'main_prod': obj, } return render(request, 'imports/product_specs.html', context=context) else: return render(request, 'imports/404.html') HTML template <form action="" method="POST" name=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {% for field in form %} {% if field.value %} {% if field.label == 'Ic feature name' %} <div style="float:left; width:450px; padding-left:40px; margin-bottom:0px"> {{ field }}</div> {% else %} <div>{{ field }}</div> {% endif %} {% … -
Modal popup with single field rendering and functional, but not submitting?
I have a form that keeps track of when a user enters/leaves an area and whenever there is a time discrepancy, it prompts the user for an estimate of a time. Currently the main parts of the form work, and the modal shows up when it needs to, but when you try to submit the "edited timestamp" the modal just gets stuck on loading and nothing happens until you refresh the page, and even when you do, nothing has been submitted to the database for the edited timestamp. It just stays with the loading symbol moving over the submit button like shown below: What could be causing this to get stuck? Looking through the code (I'm not too familiar with python) I believe it has to do with not having a .save()/.update() for the field being modified (edited_timestamp), or maybe the redirection after modal "submit" is not set (not sure how to go about this either). views.py def enter_exit_area(request): form = WarehouseForm(request.POST or None) enter_without_exit = None exit_without_enter = None if form.is_valid(): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in request.POST: new_entry = form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) # … -
django login error "Account with this Email already exists"
Django login error is being shown that "Account with this Email already exists". I'm trying to login but it is showing this error. I tried some previously given solutions but it's not getting resolved. What's the problem? Please have a look at it, help me resolve this isssue. Thanks in advance. . I'm adding my code below: This is my forms.py- ''' from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate from account.models import Account class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text='Required. Add a valid email address') class Meta: model = Account fields = ("email", "username", "password1", "password2") class AccountAuthenticationForm(forms.ModelForm): #always use (forms.Form) here, instread of (forms.ModelForm) password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = Account fields = ('email', 'password') def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] if not authenticate(email=email, password=password): raise forms.ValidationError("Invalid login") ''' This is my views.py- ''' from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, AccountAuthenticationForm def registration_view(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password') account = authenticate(email=email, password=raw_password) login(request, account) return redirect('home') else: context['registration_form'] = form else: #GET request form = RegistrationForm() context['registration_form'] = … -
Django how to make family relations
I wonder how can we make a relations between 2 users, which can be applied in reverse. The goal is when creating an object via django admin to add relation between 2 users and create the opposite of it in the second user, the sex of the user is very important for the reverse connection. I have tried to create the reverse of it when creating the object but then it crashes because it tries to recreate the object again and again. models.py SEX = ( ('m', 'Male'), ('f', 'Female'), ) class User(models.Model): first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) sex = models.CharField(max_length=1, choices=SEX) def __str__(self): return f"{self.first_name} {self.last_name}" RELATIONS = ( ('mother', 'Mother'), ('daughter', 'Daughter'), ('father', 'Father'), ('son', 'Son') ) RELATIONS_REVERSE = { 'mother':{ 'm':'son', 'f':'daughter' }, 'father':{ 'm':'son', 'f':'daughter' }, 'son':{ 'm':'father', 'f':'daughter' }, 'daughter':{ 'm':'father', 'f':'mother' } } class UserRelation(models.Model): User_1 = models.ForeignKey(User, related_name="User_1", null=False, blank=False, on_delete=models.CASCADE) User_2 = models.ForeignKey(User, related_name="User_2", null=False, blank=False,on_delete=models.CASCADE) relation = models.CharField(max_length=30, choices=RELATIONS, null=False, blank=False) #THIS DOES NOT WORK! # def save(self): # UserRelation.objects.create( # User_1= self.User_2, # User_2= self.User_1, # relation= RELATIONS_REVERSE[str(self.relation)][self.User_2.sex] # ) admin.py from django.contrib import admin # Register your models here. from .models import User, UserRelation … -
Django: Problem with Understanding Super Save Function
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. Right now, I am facing a problem understanding this code: def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() It comes from models.py: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tag(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tag) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.review def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() It looks like the save function is saving the slug. But I don't understand it completely. Does it converting integer to string? What is super doing here? Would you please give me a complete explanation about the save function? -
Django validation error messages only showing in admin page
I have a SignUp form that interacts with Django's user model to create new users. If both password fields are different, the user is not created, so I guess validation is working. But somehow, a validation error message is not shown, the form page is just rendered again. When I go to Django's admin page, the error messages pop up there! Why is it not popping in my template?! This is my form: class SignUpForm(forms.ModelForm): password = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'}),) password2 = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'placeholder':'Confirm Password', 'class':'form-control', 'type':'password'}),) class Meta: model = User widgets = {'first_name': forms.TextInput(attrs={'placeholder':'First Name', 'class':'form-control'}), 'last_name': forms.TextInput(attrs={'placeholder':'Last Name', 'class':'form-control'}), 'email': forms.TextInput(attrs={'placeholder':'Email', 'class':'form-control', 'type':'email'}), 'username': forms.TextInput(attrs={'placeholder':'Username', 'class':'form-control'}), 'password': forms.TextInput(attrs={'placeholder':'Password', 'class':'form-control', 'type':'password'}) } fields = {'first_name', 'last_name', 'email', 'username', 'password'} def clean(self): cleaned_data = super(SignUpForm, self).clean() password = cleaned_data.get('password') password2 = cleaned_data.get('password2') if password != password2: raise forms.ValidationError('Passwords do not match!') And this is my view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) form.save() user = authenticate(username=username, password=password) login(request, user) messages.add_message(request, messages.SUCCESS, 'Account created successfully!') return HttpResponseRedirect('/') else: messages.add_message(request, messages.ERROR, "There's an error in the form! Please fill it again.") return render(request, … -
Django admin download data as csv
I want to download data from django admin as .csv file. I followed tutorial https://www.endpoint.com/blog/2012/02/22/dowloading-csv-file-with-from-django. I didn't see download csv option. How can I solve my problem? I am using Python3, migration created. This is my code models.py from django.db import models from django.contrib import admin class Stat(models.Model): code = models.CharField(max_length=100) country = models.CharField(max_length=100) ip = models.CharField(max_length=100) url = models.CharField(max_length=100) count = models.IntegerField() class StatAdmin(admin.ModelAdmin): list_display = ('code', 'country', 'ip', 'url', 'count') def download_csv(self, request, queryset): import csv f = open('some.csv', 'wb') writer = csv.writer(f) writer.writerow(["code", "country", "ip", "url", "count"]) for s in queryset: writer.writerow([s.code, s.country, s.ip, s.url, s.count]) admin.site.register(Stat, StatAdmin) -
Developing a dashboard using Django?
Apologies in advance as this question is quite broad. My overall goal is to create a web application that allows for interactive analysis of NOAA model output data. For now, let's say the project will consist of two different dashboards: The first dashboard will take current output model data from NOAA based on user inputs (e.g., location) and display the data using interactive plotly plots. The second dashboard will be for displaying historical data from archived NOAA data. My background is more in chemistry and science, so while I have a good understanding of data analysis packages like Pandas, I'm much newer to web dev tools such as Django. I was originally able to create my two dashboards using Plotly Dash. I saved some sample data to my local computer and used Pandas to select subsets of data that were then plotted with plotly. However, I'd like to scale this to a fully-functioning webpage and therefore need to migrate this project to a Django framework. This is where I need help. Basically I'm trying to determine how the big-picture flow of this project would need to look. For example, below I give the workflow for a specific example in which … -
Django-cms Content Creation Wizards Custom Text Editor Implementation
I am learning Django-CMS and now I am trying to add content creation wizards. Currently, it is working nice but the problem is: it doesn't have a rich text editor. I am not getting how to implement this in content creation wizards. This is models.py : class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=500) this is my forms.py file class PostForm(ModelForm): class Meta: model = Post fields = ['title', 'content',] exclude = [] and this is my cms_wizers.py file: from cms.wizards.wizard_base import Wizard from cms.wizards.wizard_pool import wizard_pool from blog.forms import PostForm class BlogWizard(Wizard): pass blog_wizard = BlogWizard( title="Create Content", weight=200, form=PostForm, description="Create a new Content", ) wizard_pool.register(blog_wizard) Can anyone help me to implement rich text editor here? I know Django-cms uses CKEditor in page creation but I am not getting how to bring/implement this in my content creation wizards. It would be much appreciated if anyone can help me to implement this.