Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django:how to upload image file with ckeditor?
i write a function to upload the image file import os import uuid from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.conf import settings @csrf_exempt def upload_file(request): """ ckeditor5图片上传 """ upload = request.FILES.get('upload') # 生成uuid uid = ''.join(str(uuid.uuid4()).split('-')) # 修改图片名称 names = str(upload.name).split('.') names[0] = uid # 拼接图片名 upload.name = '.'.join(names) # 构造上传路径 print(upload.name, '='*100) new_path = os.path.join(settings.MEDIA_ROOT, 'upload/', upload.name) # 上传图片 with open(new_path, 'wb+') as destination: for chunk in upload.chunks(): destination.write(chunk) # 构造要求的数据格式并返回 filename = upload.name url = '/media/upload/' + filename retdata = { 'url': url, 'uploaded': '1', 'fileName': filename } return JsonResponse(retdata) this is the url setting from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static from utils.upload import upload_file urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('blog.urls')), path('uploads/', upload_file, name='uploads') # 上传图片url ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is ckeditor.js, i add ckfinder: { uploadUrl: '/uploads/' }, into it import ...... class Editor extends ClassicEditor {} // Plugins to include in the build. Editor.builtinPlugins = [ ...... ]; // Editor configuration. Editor.defaultConfig = { toolbar: { ...... }, language: 'zh', image: { ...... }, ckfinder: { uploadUrl: '/uploads/' }, table: {......} }; export default … -
how to create user if email address is not exist same time with log in
if the user with the email address already exists it logs the user in and shows a dashboard for the user. If the email address does not exist, a user is created with the email address and the user logs in -
Can't create superuser/ TypeError: NewUser() got an unexpected keyword argument 'username'
I try to create a custom superuser model, but when I try to create the actual superuser account with "python manage.py createsuperuser" I fill in the email, user name, first name, password, and password 2. But when I press enter after I input the second password I got an error. from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from datetime import datetime from .country import COUNTRY_CHOICE from django.utils.translation import gettext_lazy as _ from django.db import models # Create your models here. country_choice = COUNTRY_CHOICE class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, first_name, password, **other_fields) def create_user(self, email, user_name, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=user_name, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=30, blank=False) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=False) birthday = models.DateTimeField() # gender model GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) gender = models.CharField(max_length=1, … -
How to create an a model instance
Ok, I have two models here (Room & Message) and the message model is the child of room. so i wanted to add a comment section where a user can comment to other rooms topic.Unfortunately i tried this code below here, and django says; (Cannot assign "(<Room: MYSQL Triggers>,)": "Message.room" must be a "Room" instance.) I mean i don't understand this. please help me figure this out if you can. #room model class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name #message model class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body #VIEWS TEMPLATE def room(request , pk): room = Room.objects.get(id=pk), comments = Message.objects.filter(room=pk).order_by('-created') #get comments comments_no = comments.count() #count number of comments #create comments if request.method == 'POST': #The problem seems to be here, but i don't understand how to fix it. messaging = Message.objects.create( host = request.user, room = room, body = request.POST.get('body') ) return redirect('room', id=room.id) context = {'room': room, 'comments':comments, 'noofcomm':comments_no} return render(request, 'base/rooms.html', context) -
Can not get links to work in Django project
Library/urls.py| urlpatterns = [ path('admin/', admin.site.urls), path('catalog/',include('catalog.urls')), path('',RedirectView.as_view(url='catalog/')), path('accounts/', include('django.contrib.auth.urls')), |Catalog/URL.PY| urlpatterns = [ path('',views.index,name='index'), path('',views.memb,name='memb'), path('create_book/',views.BookCreate.as_view(),name='create_book'), path('book/<int:pk>/',views.BookDetail.as_view(), name='book_detail'), path('my_view/',views.my_view, name='my_view'), |Catalog/View| def memb(request): return render(request, 'memb.html',context=context) |Catalog/index.html| <a href="memb.html">MEMBERS</a> |Catalog/memb.html| <li><a href="#news">News</a></li> Next menu option. |ERROR| Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/memb.html Using the URLconf defined in library.urls, Django tried these URL patterns, in this order: admin/ catalog/ [name='index'] catalog/ [name='memb'] catalog/ create_book/ [name='create_book'] catalog/ book/int:pk/ [name='book_detail'] catalog/ my_view/ [name='my_view'] accounts/ The current path, catalog/memb.html, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page Says Request URL: http://127.0.0.1:8000/catalog/memb.html NOT FOUND! Why does it not match path: catalog/ [name='memb'] in URLS? I have tried with and without .html different name selections,whatever. Please help....Stuck!!!!! Could it be some conflict with Admin? Have tried straight html links...same effect??? -
In Django is urlsafe_base64_encode encrypted?
I want to encrypt pk of the user in the signup form, e.g.: e.g. http://localhost:8000/user/pk/complete_signup/ -
Get Django to return related objects
I'm trying to filter one table and obtain the related rows from another table as a nested object. Models are as follow: class KpiArea(models.Model): harvest = models.CharField(max_length=45) area_id = models.IntegerField() percentage = models.FloatField(max_length=10) class Meta: managed = False db_table = 'kpi_area' unique_together = ['harvest', 'area_id'] class KpiAreaProducts(models.Model): product = models.CharField(max_length=45) percentage = models.FloatField(max_length=10) area_id = models.IntegerField() harvest = models.ForeignKey(KpiArea, on_delete=models.PROTECT, db_column = "harvest") class Meta: managed = False db_table = "kpi_area_products" unique_together = ['harvest', 'area_id'] My goal would be to be able to get the related objects whenever I'm filtering on KpiArea, ideally as a property containing a related object's array. Something like this: [ { area_id : 1, harvest: '2020/2021', percentage: 25, products: [ { product: 'soy', percentage: 15, area_id : 1 }, { product: 'wheat', percentage: 35, area_id : 1 }, ] } ] I've tried linking with 2 foreing keys on KpiAreaProducts model, and unique_together (as per other SO questions) to achieve this. Could somebody point me in the right direction? -
Django TestCase fails to load fixture data with MySQL
I am trying to create tests to check a newly implemented login process, however I got stuck at the very beginning. When I try to make a query in my tests, Django throws a MySQLdb._exceptions.OperationalError and fails to continue. I noticed, that this issue happens only when I use django.test.TestCase, but not when I use django.test.TransactionTestCase. Now I read that there is a difference between how these two handle transactions, but I still cannot understand why one fails when the other one works. Can someone please point me in the right direction? This code fails: class AuthenticateUserTest(TestCase): fixtures = ["test_users.json"] serialized_rollback = True def test_login_success(self): print(User.objects.all()) but this code doesn't: class AuthenticateUserTest(TransactionTestCase): fixtures = ["test_users.json"] serialized_rollback = True def test_login_success(self): print(User.objects.all()) with this fixture: [ { "model": "app.user", "pk": 1, "fields": { "created_at": "2022-04-07T13:34:53+01:00", "email": "test@test.com", "password": "topsecret", "is_active": true, "roles": "[\"SUPER_ADMIN\"]", "first_name": "Test", "last_name": "User" } } ] and with the following error: ERROR: test_login_success (tests.auth.test_auth_api.AuthenticateUserTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/tests/auth/test_auth_api.py", line 36, in test_login_success print(User.objects.all()) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line … -
Django add a field to a model based on another model
I have a model for a product: class Product(models.Model): name = models.CharField(verbose_name=_("Name"), max_length=120) slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True) I want to have a separate model ProductFields: class ProductFields(models.Model): field_name = models.CharField() field_type = models.CharField() field_verbose_name = models.CharField() field_max_length = models.IntegerField() filed_null = models.CharField() field_blank = models.BooleanField() field_default = models.CharField() ... So the idea is whenever I add new ProductField I want Product model to migrate that added field to its database. For Example: ProductFields.objects.create(field_name='description', field_type='CharField', field_verbose_name='Description', field_max_length=255, filed_null=True, filed_blank=True) This should transform Product modal to: class Product(models.Model): name = models.CharField(verbose_name=_("Name"), max_length=120) slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True) description = models.CharField(verbose_name="Description", max_length= 255, null=True, blank=True) Please let me know if you have any idea how this can be done? -
|PYTHON/DJANGO| Wait before resuming a task (Without sleep)
I am trying to do a simple task : Waiting. Here is an example : # Inform the user about the closing new_message = Message.objects.create(content='Game closing in 10 seconds...', game=self) new_message.save() time.sleep(10) # After waiting, delete the game self.delete() However, my host only allows me 1 worker process , hence, if I decide to use sleep, every other requests will be freezed and my app will become unresponsive to the users. Is there a way to work around this problem ? Also, I can't use threads in case of Thanks and sorry for the poor english -
How to call double nested reverse foreign key relation in django?
I'm working on forum project. Currently, I need to fetch somehow the latest posts for each category. My models structure is following (pseudo code): class Category(models.Model): ... class Topic(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ... class Post(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) ... I need to fetch latest Post objects within Category model's functions, so I can call it latter on in my template. With single reverse foreign key call I would do something like: category: Category = self.topic_set.all() but I need to get one level deeper for Post. Is there any smarter way to do it instead of list comprehension like [topic.post_set.first() for topic in self.topic_set.all()] ?? -
How to resolve Positional Arguments error in Python
Am getting an error with below code. How can i get this error resolved def verify_payment (request: HttpRequest, ref: str, amount )-> HttpResponse: payment = get_object_or_404(Payment, ref=ref) amount = get_object_or_404(Payment, amount=amount) verified = payment.verify_payment() if verified : with transaction.atomic(): account = Account.objects.select_for_update().get(user=request.user) account.balance += amount asof = account.modified account.save(update_fields=[ 'balance', 'modified', ]) else: messages.error(request, "verification failed") return redirect('initiate-payment') Error response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: verify_payment() missing 1 required positional argument: 'amount' How do i resolve this error. amount is a field in Payment model -
Connect two Django models
Hi! I'm trying to make a auctions website for a project and I can't get to connect 2 models I have in my models.py page, a model for the auction listings (Alisting) and a model for the bids that are made(Bid). -The Alisting model has 4 fields: "title" CharField for the title of the auction, "sta_bid" for a starting bid, "las_bid" ForeignKey to Bid model, and user ForeignKey to User. -The Bid model has 3 fields: "user" ForeignKey to User for the user that makes the bid, "listing" a ForeignKey to Alisting, and "new_bid" IntegerField for the latest bid. class User(AbstractUser): pass class Alisting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=32) sta_bid = models.IntegerField() las_bid = models.ForeignKey(Bid, on_delete=models.CASCADE) class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) listing = models.ForeignKey(Alisting, on_delete=models.CASCADE) new_bid = models.IntegerField() How could I connect these 2 models so that when I create a listing I can create new bids to this listing from the other model. Because later in the project I'll have to allow users to modify bids from other user's listings. Thank you in advance! -
Saving data to Django database with Views
I need help with one thing in my django project. I have class games_renderer in my views.py which is connected to the path in URLs. I need this class to take three values and then store them in the SQL database in Django in the created UserGameScore model. I tried to do this using model.object.score but the application reports an error. I think the problem is that the application does not know which line to assign the value to, but I do not know where I can determine this value, using the value player_id. The Game_id value is used to specify in which column the value is to be written.Can anybody help me, it is urgent! views.py def games_renderer(request, game_id, player_id, score): if game_id == 1: UserGameScore.objects.create(game1_score = score) elif game_id ==2: UserGameScore.objects.create(game2_score = score) elif game_id ==3: UserGameScore.objects.create(game3_score = score) else: return render(request, 'result.html',{'game_id' : game_id, 'player_id' : player_id, "score" : score} ) models.py class UserGameScore(models.Model): user_rec = models.ForeignKey(User, on_delete=models.CASCADE) game1_score = models.IntegerField(null=True, blank=True) game2_score = models.IntegerField(null=True, blank=True) game3_score = models.IntegerField(null=True, blank=True) -
I'm trying to override a django formtools wizard form widget, but it is just using the standard widget
I have the following form class ProviderSignUp1(forms.ModelForm): class Meta: model = models.Provider fields = [ 'childcare_type_informal', 'childcare_type_accredited', ] wigdets = { 'childcare_type_informal': PatchRadioSelect( attrs={ 'class':'form-control' } ), 'childcare_type_accredited': PatchRadioSelect( attrs={ 'class':'form-control' } ) } def clean(self): cleaned_data = self.cleaned_data if cleaned_data['childcare_type_informal'] == True and cleaned_data['childcare_type_accredited'] == True: raise ValidationError("You must select only one type of childcare") if cleaned_data['childcare_type_informal'] == False and cleaned_data['childcare_type_accredited'] == False: raise ValidationError("You must select at least one type of childcare") return super().clean() The widget is defined as from django.forms.widgets import RadioSelect class PatchRadioSelect(RadioSelect): template_name = 'userprofiles/form_widgets/radio.html' option_template_name = 'userprofiles/form_widgets/radio_option.html' And my wizard is: PROVIDER_SIGNUP_TEMPLATES = { 'page0': 'userprofiles/provider_signup_wizard/page0.html', 'page1': 'userprofiles/provider_signup_wizard/page1.html', 'page2': 'userprofiles/provider_signup_wizard/page2.html', 'page3': 'userprofiles/provider_signup_wizard/page3.html', 'page4': 'userprofiles/provider_signup_wizard/page4.html', 'page5': 'userprofiles/provider_signup_wizard/page5.html', 'page6': 'userprofiles/provider_signup_wizard/page6.html', 'page7': 'userprofiles/provider_signup_wizard/page7.html', 'page8a': 'userprofiles/provider_signup_wizard/page8.html', 'page8b': 'userprofiles/provider_signup_wizard/page8.html', 'page9': 'userprofiles/provider_signup_wizard/page9.html', 'page10': 'userprofiles/provider_signup_wizard/page10.html', } PROVIDER_SIGNUP_FORMS = [ ("page0", forms.ProviderSignUp0), ("page1", forms.ProviderSignUp1), ("page2", forms.ProviderSignUp2), ("page3", forms.ProviderSignUp3), ("page4", forms.ProviderSignUp4), ("page5", forms.ProviderSignUp5), ("page6", forms.ProviderSignUp6), ("page7", forms.ProviderSignUp7), ("page8a", forms.ProviderSignUp8a), ("page8b", forms.ProviderSignUp8b), ("page9", forms.ProviderSignUp9), ("page10", forms.ProviderSignUp10), ] def accredited_only_condition(wizard): cleaned_data = wizard.get_cleaned_data_for_step('page1') or {} return cleaned_data.get('childcare_type_accredited', True) def informal_only_condition(wizard): cleaned_data = wizard.get_cleaned_data_for_step('page1') or {} return cleaned_data.get('childcare_type_informal', True) class ProviderSignUpWizard(SessionWizardView): form_list = PROVIDER_SIGNUP_FORMS condition_dict = { 'page2': accredited_only_condition, 'page8a': accredited_only_condition, 'page8b': informal_only_condition, 'page9': informal_only_condition, } def get_form_instance(self, step): if step == 'page4': return self.instance_dict.get(step, self.request.user) … -
Unique together in models
I have a model called Company. In a second model which is Branch, I use Company as a foreign key. class Branch(models.Model): tenant = models.ForeignKey(Company, on_delete=models.CASCADE) Now in some other model, I want to set a property(name) unique together with the Company but I use the branch as a foreign key. class ABC(models.Model): name = models.CharField() branch = models.ForeignKey(Branch, on_delete=models.CASCADE) class Meta: unique_together = ( ('branch.Company', 'code'), ) can I do something like the above? It gives me an error that the field is nonexistent. Or can I use both company and branch in my model as foreign key? class ABC(models.Model): name = models.CharField() branch = models.ForeignKey(Branch, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) class Meta: unique_together = ( ('company', 'code'), ) I want to attach ABC object with a branch but if once added it should be unique to that company. (other branches of that company can not have the same name). Read about the circular error and was thinking of the same here. Unique together will bE depreciated in the future but I'm not thinking about this right now. Any advise ? -
Django ORM prefetch field from manual join table on many-to-many relationship
I'm facing an n-plus-1 query explosion after changing a Django model and I think it is because I am having to re-query for fields from a manual join table As a stripped-down example class Dashboard(models.Model): team: models.ForeignKey = models.ForeignKey("Team", on_delete=models.CASCADE) items = models.ManyToManyField("Item", related_name="dashboards", through="DashboardItem") class Item(models.Model): deleted: models.BooleanField = models.BooleanField(default=False) class DashboardItem(models.Model): class Meta: unique_together = ( "dashboard", "item", ) dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE) item = models.ForeignKey("Item", on_delete=models.CASCADE) combo_hash: models.CharField = models.CharField(max_length=400, null=True, blank=True) If I'm querying for a dashboard and know I need to see its items with only 2 queries I can do this dashboards = Dashboard.objects.filter(items__deleted==False).select_related("team").prefetch_related('items') but later in the code, despite having the opportunity to prefetch on dashboard or item. I find I'm needing to do DashboardItem.objects.filter(item=item,dashboard=dashboard).first().combo_hash How do I prefetch values on the manual through table when I load the dashboard or item? -
Docker and django No module named 'corsheaders'
Im trying to dockerize an existing django project. I have corsheaders installed and its included in my installed apps as follows: INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] and in the middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] after that i build my docker using docker-compose --build and then run it docker-compose up but always the same error ModuleNotFoundError: No module named 'corsheaders' i have tried to delete corsheaders from my installed aps but then i get ModuleNotFoundError: No module named 'restframework' ps: if i run the server through py manage.py runserver it works perfectly. -
Sum gives wrong results in Django [closed]
Why would such single sum still return wrong results? total = Mark.objects.filter(marks_class=card_class, year=year, term=term).values('child','exam_set').annotate( mtotal=Sum('marks'), ptotal=Sum('value'), avg=Round(Avg('marks', output_field=IntegerField()), 0)).order_by('-mtotal') -
Tastypie: How can I create an "abstract" ModelResource class with a Meta class
Using django-tastypie I'd like to create a child class of ModelResource to define some common things, which all my other API resource classes would inherit from. e.g.: class MyModelResource(ModelResource): class Meta: authentication = SessionAuthentication() authorization = APIAuthorization() always_return_data = True # Some other common methods here class UserResource(MyModelResource): class Meta(MyModelResource.Meta): queryset = User.objects.all() However, if I do this, I get the following error: django.core.exceptions.ImproperlyConfigured: ModelResource (MyModelResource) requires Meta.object_class or Meta.queryset So I must set object_class or queryset in MyModelResource.Meta, even though it's a kind of 'Abstract' class. I can set abstract = True in MyModelResource.Meta, and this works, so long as I remember to set abstract = False in every one of its child classes. Is there a better way to do this? -
Rendering local web pages as an iFrame in Django
I have a view that uploads a zip file, checks if it contains an index.html file, and unzips it in a specific folder in the static directory. I want to be able to view this by going to a page where there is an iFrame pointing to this directory, and the user will be able to navigate inside this html page. But I can't seem to get it to work. Here is the function that uploads the zip file, and the view that uses it: views.py: @user_passes_test(lambda u: u.is_staff or u.is_superuser) def createCategory(request): if request.method == "POST": name = request.POST.get("name_kw") lang = request.POST.get("lang_kw") moduleid = request.POST.get("module_kw") zip = request.FILES.get("zip_kw") category = Category() category.name = name category.lang = lang category.module = Module.objects.get(id=moduleid) category.zip = zip category.created_by = request.user try: if zip.name.endswith(".zip"): rtn = publish_doc(category.name, zip) if rtn == "No index file found": messages.error( request, "Pas de fichier index.html détecté. Assuez-vous qu'un fichier index.html est présent dans votre fichier ZIP", ) return redirect("categoryList") else: category.root = rtn category.save() messages.success(request, "Catégorie créée avec succès") print("categorie et zip créées") return redirect("categoryList") else: messages.error( request, "Seuls les fichiers .ZIP sont acceptés", ) return redirect("categoryList") except IntegrityError: print("erreuuuuuuuur") messages.error( request, "Une erreur s'est produite. Veuillez réessayer … -
Using templatetag "get_comment_list" from view, in Django comments?
I have a template expression {% get_comment_list for data.post as comment_list %}, it uses get_comment_list from Django-comments. It gets a list of comment objects for a specified object (in this case the Post object through data.post) However, I'm currently working on client side Ajax API to retrieve the comments and its related user data. So I cannot use the template html way to get/render the data, but in a view, Python script. I found that the tag get_comment_list is defined as follows: # django_comments/templatetags/comments.py @register.tag def get_comment_list(parser, token): return CommentListNode.handle_token(parser, token) I know how to import custom template tag to a view so Python can use it, like: @register.simple_tag def addFoo(value=""): return value + "Foo." The above type of tag is simply passing a string value, but the get_comment_list(parser, token) tag requires two parser thing and object thing object, it's not a plain string type. Now, I have no idea how I can construct that parser and token or pass a model to get_comment_list to get the comment objects. Is it possible to use this type of template tag in a view? Thanks. -
Connection to the postgres refused in Github Actions
I have a Django app with Postgres default database, running in docker. I also use Github actions as a CI. When I run the tests locally using the command docker-compose run --rm app sh -c "python manage.py wait_for_db && pytest -s -v" everything works fine. However, I get the following error when I use the same command in GitHub actions: E django.db.utils.OperationalError: connection to server at "postgres" (172.18.0.2), port 5432 failed: Connection refused E Is the server running on that host and accepting TCP/IP connections? /usr/local/lib/python3.10/site-packages/psycopg2/__init__.py:122: OperationalError Here is my github workflow code: # This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python application on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.10 uses: actions/setup-python@v2 with: python-version: "3.10" - name: Install docker-compose run: | pip install docker-compose - name: Test with pytest run: | docker-compose run --rm app sh -c "python manage.py wait_for_db && pytest -s -v" My docker-compose code: version: "3" services: postgres: image: postgres:14-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=123 ports: - "5432:5432" app: build: context: … -
Django REST Framework update record mixin
I'm using Django 3.2 and the last version of djangorestframework. I need to be able to update the values of JobStatus record already crated before. As example I have { "id": 1, "status_timestamp": "2022-04-07T10:51:42Z", "status_activity": "Sync DDT", "status_status": "running", "launcher": 1 } and I need to obtain this (in the DB) via API { "id": 1, "status_timestamp": "2022-04-07T11:51:42Z", "status_activity": "Sync DDT", "status_status": "completed", "launcher": 1 } Can someone help me out? PS I need to mantain the Token authentication method MODELS class JobStatus(models.Model): status_timestamp = models.DateTimeField() status_activity = models.CharField(max_length=200) status_status = models.CharField(max_length=200) launcher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) class Meta: verbose_name = "Status" verbose_name_plural = "Status list" def __str__(self): return str(self.status_timestamp) + " " + self.status_activity URLS from django.urls import path, include from apps.api_c import views from rest_framework.routers import DefaultRouter from rest_framework.urlpatterns import format_suffix_patterns router = DefaultRouter() router.register('alert', views.AlertViewSet) router.register('jstatus', views.UpdateStatus) urlpatterns = [ ... path("", include(router.urls)), ] VIEWS class UpdateStatus(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin): """update status""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = StatusSerializer #queryset = JobStatus.objects.all() #TEST1 def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) #TEST2 def perform_update(self, serializer): serializer_class.update() -
Class-Based View of 'User' model auto-authenticates user
I've made a class-based view (DetailView) of app user's profile and for some reason anyone who visits the view is automatically considered authenticated even without entering any credentials. This happens without adding any extra logic in neither view nor template, just basic DetailView. The code is below: views.py from django.views.generic import DetailView from django.contrib.auth.models import User class ProfileDetail(DetailView): model = User template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context urls.py from django.urls import path from .views import ProfileDetail urlpatterns = [ path('<int:pk>/', ProfileDetail.as_view()) ] template (index.html) {{ user.is_authenticated }} {# returns True #} {{ user }} {# returns the user with the corresponding id #} The question is why does Django do it and is there any way to circumvent it except of using function-based view? I've looked through the docs, but couldn't find an answer.