Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
default fields not working with an Embedded field on save(), in a django project with mongoDB
Let's say I have the below structure of Models for a django project with MongoDB Database, using djongo as DB engine. When I am trying to add a Department record if I don't provide the salary field which is marked as default=0 in the query am getting a ValidationError for not suplied fields class Person(models.Model): name = models.CharFields() surname = models.CharFields() salary = models.FloatField(default=0) class Meta: abstract = True class Department(models.Model): name = models.CharFields(max_length=60, unique=True, null=False) persons = models.EmbeddedField(model_container=Person) If I run the below query: Department( name='Networking', persons = { 'name': 'Mike', 'surname': 'Jordan' } ).save() I get a Validation error for not supplied field (Since is marked as default=0, why django asks for it ?): django.core.exceptions.ValidationError: ['{\'salary\': [\'Value for field "Project.Person.salary" not supplied\'] -
Facing issue while migrating from sqllite to postgresql in Django
I am getting below error when I am migrating from django SQLite to PostgreSQL. django.db.utils.ProgrammingError: cannot cast type smallint to boolean LINE 1: ... "merchant_view" TYPE boolean USING "merchant_view"::boolean I am able to see all the tables in Postgresql even the table which is giving me above error. But in Postgresql its datatype have changed from Boolean to smallint. I am not also not able to change the datatype from smallint to boolean in postresql. Most of the fields has Boolean datatype in postgresql.I dont know what causing this error. How can i solve this error. My Model class ContractLineItems(CommomFields): payment_app_id = models.AutoField(primary_key = True) code = models.CharField(max_length=11,unique=True) module = models.ForeignKey(ContractManager,on_delete=models.CASCADE) description = models.CharField(max_length=255) buy_rate = models.DecimalField(max_digits=10,decimal_places=10) default_rev_share = models.DecimalField(max_digits=10,decimal_places=10) list_price = models.DecimalField(max_digits=10,decimal_places=10) billing_type = models.ForeignKey("BillingType",on_delete=models.CASCADE) merchant_view = models.BooleanField(default=False) bound_descreption = models.CharField(max_length=255) user_id = None trash = None deleted_at = None deleted_by = None Thanks in Advance. -
Django authenticate() don't work after first logout
If I create new user from the page login after submit, if it's all ok, I do automatic login with login(request,user) and rederect user in home page. In this case script works. But if I do logout and subsequently login, authenticate() return None and the authentication fails. models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Email(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails") sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent") recipients = models.ManyToManyField("User", related_name="emails_received") subject = models.CharField(max_length=255) body = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) read = models.BooleanField(default=False) archived = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.email, "recipients": [user.email for user in self.recipients.all()], "subject": self.subject, "body": self.body, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "read": self.read, "archived": self.archived } register views def register(request): if request.method == "POST": email = request.POST["email"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "mail/register.html", { "message": "Passwords must match." }) # Attempt to create new user try: user = User.objects.create_user(email, email, password) user.save() except IntegrityError as e: print(e) return render(request, "mail/register.html", { "message": "Email address already taken." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "mail/register.html") login views import json from django.contrib.auth import authenticate, login, logout … -
Django - build form fields from database dynamically
I hope the title of this question is as it should be based on this explanation below. I have a model as below: class Setting(models.Model): TYPE_CHOICES = ( ('CONFIG', 'Config'), ('PREFS', 'Prefs'), ) attribute = models.CharField(max_length=100, unique=True) value = models.CharField(max_length=200) description = models.CharField(max_length=300) type = models.CharField(max_length=30, choices=TYPE_CHOICES) is_active = models.BooleanField(_('Active'), default=True) I use this to save settings. I have don't know all settings in advance and they can change in future. So I decided to save attributes and their values in this model instead of creating columns for each setting(attribute in the model). Now the problem I am facing is how do I present form with all attributes as fields so that a user can fill in appropriate values. Right now, as you can see, form shows columns 'Attribute' and "Value" as labels. I would like it to show value of column 'Attribute' as label and column 'Value' as field input. For example, in Setting model I have this: Attribute ------------ Value 'Accept Cash' ---------- 'No' I would like to appear this on form as <Label>: <Input> 'Accept Cash': 'No' I think I will have to build form fields from the database(Setting model). I am new to this and have … -
cookie isn't stored in browser localstorage cookies
hi I have a question about cookie first i'm using djangorestframework for backend and using react for frontend second, i decided to use jwt token for login authentication so i made jwt token and using django set_cookie() method for response cookie(jwt token is stored) enter image description here like this. and this is my cors settings in my settings.py file enter image description here and in the frontend side(react) enter image description here I wrote my code like this. so, what I expected was .. when I send 'login/' request, server check the id and password and if that is correct response with cookie(with jwt token) and that cookie is stored in local(browser) storage cookie part enter image description here but.. as a result.. enter image description here I got a cookie(with token) from response(that image is network tap) but.. it isn't stored in localstorage cookies as I uploaded above.. so, please tell me what is the solution with my case.. i tested it localhost react is 3000 port and django is 8000 port -
(Django 3.1.6/Python 3.8.7) Using a named method in fields or fieldsets admin.py does not work?
No matter what I try I cannot use a named method as a field name like they do in the docs. Eventually I'll make the method retrieve a field of a ForeignKey but for now I just want to figure out what I'm doing wrong with this simplified example. In this example from docs.djangoproject.com they are using the class method 'view_birth_date' just as I am using 'get_test' (below) and even through I'm using it in fieldsets instead of fields it should work. I've tried it with fields = and fieldsets = and I get the same result (error). It cannot find the field 'get_test' either way. I've also tried putting the def get_test(self) above the fieldsets = but it makes no difference. It should work the same as what is in the documentation but it does not. What am I doing wrong? This should work: @admin.register(Feeddata) class AdminFeeddata(admin.ModelAdmin): """Feeddata admin.""" list_display = ['id', 'eventtime', 'feed'] fieldsets = [ ('Meta', { 'fields': ['feed', 'eventtime', 'get_test'] }), ('JSON Data', { 'fields': ('json_data', ) }), ] # pylint: disable=no-self-use def get_test(self): """Test string.""" return 'test' But I get an error: FieldError at /admin/feeder/feeddata/fff1d764-52cd-499f-9ae9-b1251a806b5b/change/ Unknown field(s) (get_test) specified for Feeddata. Check fields/fieldsets/exclude attributes of … -
Host Django and React on the same server?
I am working on a SAS product. So there could be 1000 users using my application at the same time. Technologies Used: Django for Backend React.js for frontend Django Rest Framework for APIs I have hosted this project on a server with customized Nginx settings as shown here: https://stackoverflow.com/a/60706686/6476015 For now, I am having no issues but I want to know if there is some possibility of something going wrong in the future as usage and data will increase. Should I host the frontend and backend on separate servers? -
DoesNotExist at /cart/ matching query does not exist
I want show item in cart.html page in my cart but when i add tshirt item in cart it's gives Error Product matching query does not exist. and when i add Product item in cart it gives error Tshirt matching query does not exist when I click on Cart cartitem.py file: def cartitem(request): cart=request.session.get('cart') if cart is None: cart=[] for c in cart: tshirt_id=c.get('tshirt') product_id=c.get('product') product=Product.objects.filter(id=product_id) tshirt=Tshirt.objects.get(id=tshirt_id) c['size']= Sizevariant.objects.get(tshirt=tshirt_id, size=c['size']) c['tshirt']=tshirt c['product']=product return render(request,"cart.html",{"cart":cart}) -
Bounding box with longitude less than -180 django postgis
I'm trying to add a bounding box to django model. c.bounding_box = Polygon.from_bbox((-194.06250000000003, 31.952162238024975, -21.796875000000004, 76.3518964311259)) c.save() It works fine, but when I access django admin, I see incorrect box. I think it is because of the longitude less than -180. How can I fix it? -
How critical is pylint's no-self-use?
As an example I have a Django custom management command which periodically (APScheduler + CronTrigger) sends tasks to Dramatiq. Why the following code with separate functions: def get_crontab(options): """Returns crontab whether from options or settings""" crontab = options.get("crontab") if crontab is None: if not hasattr(settings, "REMOVE_TOO_OLD_CRONTAB"): raise ImproperlyConfigured("Whether set settings.REMOVE_TOO_OLD_CRONTAB or use --crontab argument") crontab = settings.REMOVE_TOO_OLD_CRONTAB return crontab def add_cron_job(scheduler: BaseScheduler, actor, crontab): """Adds cron job which triggers Dramatiq actor""" module_path = actor.fn.__module__ actor_name = actor.fn.__name__ trigger = CronTrigger.from_crontab(crontab) job_path = f"{module_path}:{actor_name}.send" job_name = f"{module_path}.{actor_name}" scheduler.add_job(job_path, trigger=trigger, name=job_name) def run_scheduler(scheduler): """Runs scheduler in a blocking way""" def shutdown(signum, frame): scheduler.shutdown() signal.signal(signal.SIGINT, shutdown) signal.signal(signal.SIGTERM, shutdown) scheduler.start() class Command(BaseCommand): help = "Periodically removes too old publications from the RSS feed" def add_arguments(self, parser: argparse.ArgumentParser): parser.add_argument("--crontab", type=str) def handle(self, *args, **options): scheduler = BlockingScheduler() add_cron_job(scheduler, tasks.remove_too_old_publications, get_crontab(options)) run_scheduler(scheduler) is better than a code with methods? class Command(BaseCommand): help = "Periodically removes too old publications from the RSS feed" def add_arguments(self, parser: argparse.ArgumentParser): parser.add_argument("--crontab", type=str) def get_crontab(self, options): """Returns crontab whether from options or settings""" crontab = options.get("crontab") if crontab is None: if not hasattr(settings, "REMOVE_TOO_OLD_CRONTAB"): raise ImproperlyConfigured( "Whether set settings.REMOVE_TOO_OLD_CRONTAB or use --crontab argument" ) crontab = settings.REMOVE_TOO_OLD_CRONTAB return crontab def handle(self, … -
inserting the request's user during put-as-create operations
I am using the following mixin. class PutAsCreateMixin(object): """ The following mixin class may be used in order to support PUT-as-create behavior for incoming requests. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object_or_none() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) if instance is None: if not hasattr(self, 'lookup_fields'): lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field lookup_value = self.kwargs[lookup_url_kwarg] extra_kwargs = {self.lookup_field: lookup_value} else: # add kwargs for additional fields extra_kwargs = {field: self.kwargs[field] for field in self.lookup_fields if self.kwargs[field]} serializer.save(**extra_kwargs) return Response(serializer.data, status=status.HTTP_201_CREATED) serializer.save() return Response(serializer.data) and I have the following view. class OwnStarPutDestroyView(CoreView, PutAsCreateMixin, MultipleFieldMixin, PutDeleteAPIView): serializer_class = StarSerializer queryset = Star.objects.all() permission_classes = [IsAuthenticated, AddStars] lookup_fields = ['upload_id', 'user_id'] def get_object(self): # explicitly set the user-id kwarg by referencing # the request's user because we cannot set the same # anywhere else during put-as-create operations self.kwargs['user_id'] = self.request.user.id return super(OwnStarPutDestroyView, self).get_object() path('uploads/<int:upload_id>/stars/me/', views.OwnStarPutDestroyView.as_view(), name='own-stars-put-destroy'), As you can see here, I am setting the user_id to the kwargs before getting the object. This enables the mixin to include the kwarg as a parameter while checking if the object exists However, I don't think that this seems right. Is there a better way to do the same? -
Django can't load static files even though all settings are fine
I don't know why django can't load static files even though I have defined static_url, static_root, staticfiles_dirs and urlpatterns including static_root. I put static files in root_dir/static/ directory. My templates also got right syntax with {% load static%} and {% static '...'%} Please give me some advice on this. Many thanks -
Django + Pymongo creating account confirmation link
I am building a user module from scratch where users can do pretty much all regular user operations from login,signup,..., to account deactivation. The thing is that I am not using mongoengine or django ready-made models that simplify sql connections, instead I am doing everything from scratch using pymongo driver to connect to mongodb database where I need to code all CRUD operations. I am stuck at creating a temporary link for users to (1) confirm account - this link should not be expired, (2) reset password, this link expires in few days. I have two questions regarding this: 1- can i still use django token generator/ authentication library? I am not using Users django library so my users are just ones I create and insert to database, if yes how can i do that?! 2- if no, how can I generate those temp links considering similar level of security that django library adopts, i.e. hashed username/ salted.. etc. any advice if I am doing something wrong or I should re-do everything considering mongoengine as my driver so that I can inherit and use django models?! any recommendation is highly appreciated. Thank you -
unable to upload data from csv into sqlite database using Django,pandas
When I run makemigrations command and then migrate,the fields in the db are not populated with the values from csv. import sqlite3 import pandas as pd conn = sqlite3.connect('/Users/XYZ/OneDrive/Desktop/XYZ/Django/db.sqlite') df = pd.read_csv('/Users/XYZ1q/OneDrive/Desktop/XYZ/Django/grades.csv') df['id']=df.index df=df[['id', 'Student','GradeTest1','GradeTest2','Grade']] df.to_sql('filterByGrade_grademodel', conn, if_exists='replace', index=False) -
Check id user into two fields with get and request
i want create if validation in my views to check before to site they are matched,but if someone is matched together: Models.py class Matched(models.Model): profile_user = models.ForeignKey(Profile, on_delete=models.CASCADE,related_name='profile_user') matched_user = models.ForeignKey(Profile,on_delete=models.CASCADE,related_name='matched_user') and model is with UniqueConstraint but my views def profileDetailView(request, pk): user = Profile.objects.get(pk=pk) if request.user.is_authenticated: pass and my question is to check in if user and request.user are in Matched Model, i mean i can do it like that: x = Matched.object.filter(profile_user=user, matched_user=request.user.profile) y = Matched.object.filter(profile_user=request.user.profile, matched_user=user) and if x or y: pass but its some more optimaze option for do it ? -
how to perform post request on nested serailizers in django rest framework
Hii I am new to django rest framework i am able to perform put delete and get operations but unable to perform post operations models.py class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class User_log(models.Model): user = models.OneToOneField(auth.models.User,on_delete=models.CASCADE,related_name='user_logs') fullname=models.CharField(max_length=255) fb_login=models.BooleanField(default=False) def __str__(self): return self.fullname serializers.py class userSerializers(serializers.ModelSerializer): password1=serializers.CharField(source="user.password1",write_only=True) password2=serializers.CharField(source="user.password2",write_only=True) fullname=serializers.CharField(source='user_logs.fullname') fb=serializers.BooleanField(source='user_logs.fb_login') class Meta: model = User fields=('id','username','email','password1','password2','fullname','fb') related_fields = ['user_logs'] def update(self, instance, validated_data): # Handle related objects for related_obj_name in self.Meta.related_fields: data = validated_data.pop(related_obj_name) related_instance = getattr(instance, related_obj_name) # Same as default update implementation for attr_name, value in data.items(): setattr(related_instance, attr_name, value) related_instance.save() return super(userSerializers,self).update(instance, validated_data) urls.py from django.urls import path,include from django.contrib.auth import views as auth_views from . import views from rest_framework import routers router=routers.DefaultRouter() router.register('accounts',views.Userview,basename='user') app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), path('logout/', auth_views.LogoutView.as_view(), name="logout"), path('signup/', views.SignUp.as_view(), name="signup"), path('password-reset/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset_email.html' ), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view( template_name='accounts/password_reset_complete.html' ), name='password_reset_complete'), path('',include(router.urls)), ] views.py class Userview(viewsets.ModelViewSet): def get_serializer_class(self): return userSerializers def get_queryset(self): return User.objects.all() def list(self,request): queryset = User.objects.all() serializer=userSerializers(queryset,many=True) if serializer.is_valid: return Response(serializer.data) this is the json format when i perform get request [ { "id": 1, "username": "karm", "email": "karm@gmail.com", "fullname": "ss", "fb": false } ] As mentioned … -
How to provide Share content functionality with discord in Python?
I am building an application using Python & Django in which I want to provide feature to share an event on discord. So what I want is a user can click on share with discord icon and get redirected to sign-in page where once he sign-in can be able to post the Event picture and it's details. I tried to create an application with Discord and followed some tutorial but they eventually end-up with sending messages using Hooks. I want user to share content like we do in Facebook and Twitter. Is that possible to do so with Discord? -
how to structure Django project
I am currently doing an online shopping site in Django. And I have following modules, Admin Moderators Service Packing and shipment Users Shops if I create only one app and write all views in one file, it will be mess. so can I create multiple view files(adminviews.py,modeartorview.py ..) in a single app (be deleting original views.py) or do I need to create different apps for modules can anyone suggest me which one is better? -
Building web applications around TTN: how to best store the data (DynamoDB or PostgreSQL)?
I’m currently thinking about an architecture for a web application with following functionality: Generate sensor data charts (up to years) from an environment sensors that I’ve connected to TTN. I’m aware of Cayenne but I’d like to build my own application. Currently, I’ve already integrated a couple of RaspberryPis over MQTT witih following architecture: RPI → internet connection / MQTT → Amazon IoT & DynamoDB → Query Data from a Django server and show it to the User. I’d like to keep Django, which runs on pythonanywhere.eu, as my backend. I have checked and tried the Amazon AWS Api: https://www.thethingsnetwork.org/docs/applications/aws/index.html I also know the swagger and how to work with it: https://www.thethingsnetwork.org/docs/applications/storage/api.html Is there any restriction on how often a Request can be send? I didn’t find anything. I would just like to reach out for your help to check my options for storing and accessing sensor data. How would you do it? -
Django Queryset with custom property
I have a simple model like below class Parishioner(models.Model): def _age(self): return date.today().year - self.dob.year """Parishioner model""" first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() age = property(_age) GENDER_CHOICES = [("Male", "Male"), ("Female", "Female"), ("Other", "Other")] gender = models.CharField(max_length=10, choices=GENDER_CHOICES) address = models.CharField(max_length=1000) fathers_name = models.CharField(max_length=500) mothers_name = models.CharField(max_length=500) baptism_certificate = models.ImageField(null=True, upload_to=baptism_certificates_image_file_path) marriage_certificate = models.ImageField(null=True, upload_to=marriage_certificates_image_file_path) As you can see age is a calculated property. I have my viewset like below class ParishionerViewSet(viewsets.ModelViewSet): queryset = Parishioner.objects.all() serializer_class = serializers.ParishionerSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): first_name = self.request.query_params.get('first_name') last_name = self.request.query_params.get('last_name') gender = self.request.query_params.get('gender') address = self.request.query_params.get('address') fathers_name = self.request.query_params.get('fathers_name') mothers_name = self.request.query_params.get('mothers_name') age = int(self.request.query_params.get('age')) queryset = self.queryset if first_name: queryset = queryset.filter(first_name__contains=first_name) if last_name: queryset = queryset.filter(last_name__contains=last_name) if gender: queryset = queryset.filter(gender__contains=gender) if address: queryset = queryset.filter(address__contains=address) if fathers_name: queryset = queryset.filter(fathers_name__contains=fathers_name) if mothers_name: queryset = queryset.filter(mothers_name__contains=mothers_name) if age: queryset = queryset = queryset.filter(age__gte=age) return queryset.filter() All I want is to return obects who has age >= provides value. So if I send a request to this url http://localhost:8000/api/parishioners/?age=32 I'm getting this error --> Cannot resolve keyword 'age' into field So how can I use this url http://localhost:8000/api/parishioners/?age=32 and get objects who has age … -
Django User.date_joined.date using UTC time?
In my template, I want to show the join date of a user, so I am using {{ user.date_joined }} which shows the date and time (in local time zone - same as what is shown in the admin panel). To just show the date, I use {{ user.date_joined.date }}, but it seems to be converting the date and time to UTC before showing the date (I am in EST/EDT - I never remember which is which). For example: {{ user.date_joined }} ==> Feb. 18, 2021, 7 p.m. {{ user.date_joined.date }} ==> Feb. 19, 2021 Is there a way for me to change this so that it shows the same date as the full date and time? -
How to update a User and its Profile in nested serializer using generic ListCreateAPIView?
I am working on genericAPIViews in DRF. I am using a built in user model with UserProfile model having one to one relation with it. But I am unable to create user due to nested serializer. My question is that how I can update my built in User model and Profile User model at the same time as UserProfile model is nested in User model.Here is my code: Models.py USER_CHOICE = ( ('SS', 'SS'), ('SP', 'SP') ) LOGIN_TYPE = ( ('Local', 'Local'), ('Facebook', 'Facebook'), ('Google', 'Google') ) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') cell_phone = models.CharField(max_length=15, blank=True, default="", null=True) country = models.CharField(max_length=50, blank=True, default="", null=True) state = models.CharField(max_length=50, blank=True, default="", null=True) profile_image = models.FileField(upload_to='user_images/', default='', blank=True) postal_code = models.CharField(max_length=50, blank=True, default="", null=True) registration_id = models.CharField(max_length=200, null=True, blank=True, default=None) active = models.BooleanField(default=True) # roles = models.ForeignKey(Role, null=True, on_delete=models.CASCADE, related_name='role', blank=True) user_type = models.CharField(max_length=50, choices=USER_CHOICE, null=True, blank=True) login_type = models.CharField(max_length=40, choices=LOGIN_TYPE, default='local') reset_pass = models.BooleanField(default=False) confirmed_email = models.BooleanField(default=False) remember_me = models.BooleanField(default=False) reset_code = models.CharField(max_length=200, null=True, blank=True, default="") reset_code_time = models.DateTimeField(auto_now_add=True, blank=True) longitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) latitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) r_code = models.CharField(max_length=15, null=True, blank=True) refer_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_refer") referred = models.ManyToManyField(User, related_name="user_referred", null=True, blank=True) otp = … -
type object 'Post' has no attribute 'published' Django (ERROR)
I am working on the application and I have entered all the code correctly. But when I enter the runserver command, browser gives me such an error My codes are as follows: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. and views.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) What changes do I need to make now? -
How to run celery tasks on another Azure VM server?
I am working on a django application that uses Celery to run a video encoding task. But right now, every task is run on the same VM as the main application thereby using that server's memory. I was wondering if there was any way to run these tasks on a separate VM so that the main application is not affected by the encoding tasks memory usage. -
Why do I get typeerror while migrating mysql in django?
python 3.8, django 3.1.6 when i input like this: enter image description here the error is: enter image description here even if I googled, I couldn't find this case and in a library file 'django\db\backends\mysql\base.py' there is a method: enter image description here I think it's an error because cursor.fetchall() returns a byte. Can you figure out a solution to this problem?