Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is it required to manually create Django groups through programming?
I have doubt that after hoisting if groups are not created programmically, does it affect on login as my website have multiple user login of patient, doctor as well as receptionist. -
ValueError: invalid literal for int() with base 10: 'slug-1-2'
ValueError: invalid literal for int() with base 10: 'slug-1-2' 2nd time i am facing this error again. I am trying to allow users to edit their comments in any blog post but it seems that there is a problem with this line: comment = get_object_or_404(Comment, id=post_id) This has worked for other functions but not this one. Any idea how I can resolve this without changing the url etc. Thanks models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) slug = models.SlugField(blank=True, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) views.py def edit_own_comment(request, post_id): context = {} comment = get_object_or_404(Comment, id=post_id) if request.method == 'POST': form = UpdateCommentForm(request.POST, instance=comment) if comment.name == request.user and form.is_valid(): obj = form.save(commit=False) obj.save() messages.success(request, 'Your comment has been edited', extra_tags='editedcomment') return redirect(reverse("HomeFeed:detail", kwargs={'slug': comment.post.slug })) form = UpdateBlogPostForm( initial = { "body": comment.body, } ) context['form'] = form return render(request, 'HomeFeed/edit_comment.html', context) forms.py class UpdateCommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] def save(self, commit=True): comment = self.instance comment.body = self.cleaned_data['body'] if commit: comment.save() return comment -
Page is not found
I have the following urls: path('login/', auth_views.LoginView.as_view(),name ='login'), path('logout/', auth_views.LogoutView.as_view()), path('password_change/', auth_views.PasswordChangeView.as_view(),name='password_change'),] In views for the first url I have this: user = get_object_or_404(User, username = username) posts = Post.objects.filter(author = user).order_by('-pub_date') return render(request,'profile.html', {'posts':posts,'user':user}) So when I go to the page login, logout or password_change I get the error "Page is not found" Request Method: GET Request URL: http://127.0.0.1:8000/password_change/ Raised by: posts.views.profile But if I comment the profile view and its url everything works just fine. Why does the url 'logout' etc goes to profile view? -
Why my annotation group by is not working as expected?
I wanna do a query like raw sql select count(b.status) from a left out join b on a.id = b.user_id group_by(b.status). I know how to get what I wanted using raw sql. But when I try to implement this using orm, it failed. Below is the code: query_kwargs_dict = {'id__in': [10000, 10001]} statistics = UserAuthModel.objects.filter( **query_kwargs_dict ).select_related( 'obbyuserinfomodel' ).values('obbyuserinfomodel__status').annotate(count=Count('obbyuserinfomodel__status')).query print('statistics', statistics) And the print statement output is: statistics SELECT `users_obby_info`.`status`, COUNT(`users_obby_info`.`status`) AS `count` FROM `users_auth` LEFT OUTER JOIN `users_obby_info` ON (`users_auth`.`id` = `users_obby_info`.`user_id`) WHERE `users_auth`.`id` IN (10000, 10001) GROUP BY `users_auth`.`id`, `users_obby_info`.`status` ORDER BY `users_auth`.`id` DESC What confusing me is the group_by. It should be grouped by the field specified in values. In my case, it is obbyuserinfomodel__status , but the output sql statement showed it was grouped by users_auth.id. Below are the two tables(I have omitted some fields for simplicity): class UserAuthModel(AbstractBaseUser): ... class ObbyUserInfoModel(models.Model): user = models.OneToOneField(UserAuthModel, on_delete=models.CASCADE) ... status = models.CharField(max_length=15, default=ACCOUNTSTATUS.UNACTIVATED.value, null=True) -
Multiple models in Django form
I have the following models: class Category(models.Model): label = models.CharField(max_length=40) description = models.TextField() class Rating(models.Model): review = models.ForeignKey(Review, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) rating = models.SmallIntegerField() class Review(models.Model): author = models.ForeignKey(User, related_name="%(class)s_author", on_delete=models.CASCADE) coach = models.ForeignKey(User, related_name="%(class)s_coach", on_delete=models.CASCADE) comments = models.TextField() I'd like to create a form which allows a user to review a coach, including a rating for some pre-populated categories. In my head, the form would look something like: Coach: _______________ # Selection of all coach users from DB, this works as standard Category: "Professionalism" # These would be DB entries from the Category model Rating: _ / 5 Category: "Friendliness" Rating: _ / 5 Category: "Value" Rating: _ / 5 Comments: _________________________________ _________________________________ Submit I've seen Django Formsets in the documentation but these appear to exist for creating multiple forms from the same model as a single form? Not looking for a full answer, but if someone could point me in the right direction, it'd be hugely appreciated. -
How do i access django form's image field in js code
I am building a BlogApp and I am Build a feature of preview image before save into Database. BUT at the last moment, I am stuck on a Problem. As i did before, I used to access image field in template like {{ form.image }} but i put js code in template for preview the selected image in Choose file. create_blog_post.html General method for choose image field Choose file in browser `{{ form.image }}. {{ form.image|as_crispy_field }} js code in create_blog_post.html <script> window.onload = function() { if (window.File && window.FileList && window.FileReader) { var filesInput = document.getElementById("uploadImage"); filesInput.addEventListener("change", function(event) { var files = event.target.files; var output = document.getElementById("result"); for (var i = 0; i < files.length; i++) { var file = files[i]; if (!file.type.match('image')) continue; var picReader = new FileReader(); picReader.addEventListener("load", function(event) { var picFile = event.target; var div = document.createElement("div"); div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>"; output.insertBefore(div, null); }); picReader.readAsDataURL(file); } }); } } </script> The Problem I have no idea , how to access {{ form.image }} attribute in js code, which can show both Preview before save and upload that image. What have i tried 1). I have … -
Django is not displaying items as it should
I'm building an ecommerce website with a template I'm using and I want the items to be displayed. I've created a database already and want to render them to the HTML, but when it renders, the item doesn't appear correctly. and this is how it should look like: I've tried putting the HTML like this: <section class="ftco-section bg-light"> <div class="container"> <div class="row justify-content-center mb-3 pb-3"> <div class="col-md-12 heading-section text-center ftco-animate"> <h2 class="mb-4">New Shoes Arrival</h2> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia</p> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-12 col-md-6 col-lg-3 ftco-animate d-flex"> <div class="product d-flex flex-column"> <a href="#" class="img-prod"><img class="img-fluid" src='{% static "images/product-1.png" %}' alt="Colorlib Template"> <div class="overlay"></div> </a> {% for item in items %} <div class="text py-3 pb-4 px-3"> <div class="d-flex"> <div class="cat"> <span>{{ item.get_category_display }}</span> </div> <div class="rating"> <p class="text-right mb-0"> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> </p> </div> </div> <h3><a href="#">{{ item.title }}</a></h3> <div class="pricing"> <p class="price"><span>${{ item.price }}</span></p> </div> <p class="bottom-area d-flex px-3"> <a href="#" class="add-to-cart text-center py-2 mr-1"><span>Add to cart <i class="ion-ios-add ml-1"></i></span></a> <a href="#" class="buy-now text-center py-2">Buy now<span><i class="ion-ios-cart ml-1"></i></span></a> </p> </div> </div> </div> and it … -
django-el-pagination: how to reload displayed paginated results based on user form input using AJAX without reloading the entire page?
Have scroll-based pagination working so far using django-el-pagination. Want to have a form textfield at the top of the page and then as users type, to send the search terms into the view using AJAX and have the updated queryset used for the pagination. I'd like the existing objects to be removed from the page and the objects from this updated queryset to get displayed in the template. The problem is I can send the form field values into the view using an AJAX GET-request which does filter the queryset inside the view, but the displayed paginated items are not getting changed. I don't think the queryset inside the template and sent to the pagination plugin is getting updated. Here's what I have so far (function-based views): def search_restaurants(request): template = 'search_restaurants.html' page_template = 'search_restaurants_list_page.html' restaurants = Restaurant.objects.all() name_initial_value = None if len(request.GET) !=0: name = request.GET.get('restaurant_name','') if name != '': restaurants = restaurants.filter(name__istartswith=name) name_initial_value = name if request.is_ajax(): template = page_template return render(request, template, {'restaurants':restaurants, 'name_initial_value':name_initial value} In the templates, just have what's required, ie. $.endlessPaginate({paginateOnScroll:true} Then to make the AJAX request in response to the formfield typing: $('#restaurant_name_form_field').on('input',function() { $.ajax({ type:'GET': url:'/search_restaurants/' data: { 'restaurant_name':(val here) //I've tried … -
How to prevent IntegrityError in case of using UUID in django
I want to use UUID as PK in my django model as follows (database is Postgresql): class Post(models.Model): pk = models.UUID(primary_key=True, default=uuid.uuid4, editable=False) ... Every time uuid.uuid4 generates a new UUID. My question is: Is it possible that uuid.uuid4 generate a duplicate UUID? And if it's possible, how to prevent IntegrityError in case of duplicate UUID generated? -
How to upload file in django
this might be a pretty stupid question. Also I am new to django. But I was trying to create a basic file upload approach with django where user uploads a file and it gets stored into the defined media path (or whatever that it's called) and that the file size, name, and some other attributes that are needed can be stored into the database. So I have the model ready which will help you understand the question better. class Document(models.Model): file_uid = models.CharField(max_length = 16) file_name = models.CharField(max_length = 255) file_size = models.CharField(max_length = 255) file_document = models.FileField(upload_to='uploaded_files/') uploaded_on = models.DateTimeField(auto_now_add=True) uploaded_by = models.CharField(max_length=16) Now it's clearly plain that we don't need to create all the fields in the form and that most them can be received from the file itself (like the name, size). for other attrs like uid and uploaded by those also will be added by the backend. So that's where I am stuck. I have searched for 2 days straight and still couldn't find a proper solution. As of now this is my views.py def uploadView(request): if(request.method == 'POST'): form = FileUploadForm(request.POST, request.FILES) uploaded_file = request.FILES['uploaded_file'] file_dict = { 'file_uid' : get_random_string(length=10), 'file_name' :uploaded_file.name, 'file_size' : … -
Cannot deploy django project with postgres database in azure
I know it may be a novice problem but I got stuck here for quite some time. In my azure account I wanted to deploy my django-postgresql project in a subdomain. so I did the following steps, Created a python webapp with linux resource Created a postgresql server (single server) with the same resource Setup CI/CD in Development center Also set the production.py file in my project and set those variable values in the Configuration of my App service. I successfully created my database in postgresql using azure CLI (This is the only step I use CLI in this process) Then I opened my SSH session and activated antenv. After that I ran the python manage.py migrate command and got the following error.... Traceback (most recent call last): File "/opt/python/3.8.6/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/opt/python/3.8.6/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/opt/python/3.8.6/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/opt/python/3.8.6/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/opt/python/3.8.6/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/opt/python/3.8.6/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting … -
IntegrityError (wrong) instead of ValidationError (correct)
Django Version: 3.1.5 Python Version: 3.6.9 Model class GoogleAnalytics(models.Model): counter = models.SlugField(max_length=17, null=False, default="", unique=True, verbose_name="Counter") tracking_code = models.TextField(null=False, default="", verbose_name="Tracking code", validators=[validate_google_analytics_tracking_code]) Form class CounterForm(forms.ModelForm): """ Validate if the value in counter field really corresponds to the tracking code for this counter. """ def clean(self): counter_manager = CounterManager() if "GoogleAnalytics" in str(self.Meta.model): counter_from_tracking = counter_manager.get_counter(self.cleaned_data['tracking_code'], Counters.GOOGLE_ANALYTICS) else: assert "YandexMetrika" in str(self.Meta.model) counter_from_tracking = counter_manager.get_counter(self.cleaned_data['tracking_code'], Counters.YANDEX_METRIKA) if self.cleaned_data['counter'] != counter_from_tracking: raise ValidationError("Код не соответствует счетчику") return self.cleaned_data class Meta: model = GoogleAnalytics exclude = [] Admin class GoogleAnalyticsAdmin(admin.ModelAdmin): form = CounterForm admin.site.register(GoogleAnalytics, GoogleAnalyticsAdmin) Traceback https://dpaste.com/6CUL2VZAW Well, unique constraint for counter field worked. But I extected a validation error rather than IntegrityError. Could you tell me how to fix that? -
Django queryset bulk_update with and without lookup
I was wondering what exactly is the difference between retrieving entries and then bulk updating in Django vs creating an array of the model objects and pushing it to bulk_update. NOTE: The entries with the given name are unique and always exist in the database. models.py from django.db import models class Subject(models.Model): name = models.CharField(max_length=30, unique=True) credits = models.FloatField() The updating entries logic: update_logic.py from my_app.models import Subjects def update_credits_without_lookup(subjects): """ This method will update credits without getting a resultset from the DB. eg: subjects = [ {"name":"Physics","credits":10}, {"name":"Chemistry","credits":10}, {"name":"Mathematics","credits":10}, {"name":"English","credits":5} ] """ subject_objects = [Subject(name=subject["name"], credits=subject["credits"]) for subject in subjects] Subject.objects.bulk_update(subject_objects, ['credits']) def update_credits_with_lookup(subjects): """ This method will update credits by first looking up in the DB. eg: subjects = [ {"name":"Physics","credits":10}, {"name":"Chemistry","credits":10}, {"name":"Mathematics","credits":10}, {"name":"English","credits":5} ] """ subject_entries = Subject.objects.filter( name__in=[[subject["name"] for subject in subjects]]) # I can make this better by ignoring/creating subjects that might have no resultset in the DB. # Please consider that the subjects passed are always there in the DB. for subject_entry, subject in zip(subject_entries, subjects): subject_entry.credits = subject["credits"] Subject.objects.bulk_update(subject_entries, ['credits']) Considering my NOTE is it advised to use the update_credits_without_lookup method, since it will save an extra lookup in the DB and the … -
how i can solve this error of url mapping in django
Reverse for 'edit_course_landing_page' with arguments '(UUID('7e12b860-c4a0-4037-ba7d-2a4f5297d510'),)' not found. 1 pattern(s) tried: ['edit_course_landing_page/uuid:data'] -
How to assign a group to user as the time of signup in class based view in django?
I am using class based views in my djanog project. i need to assign a group named 'customer' (from django.contrib.auth.Group) at the time of when a user signsup (register) this is my view for signup class UserSignup(SuccessMessageMixin, CreateView): template_name = 'users/signup.html' success_url = reverse_lazy('home') form_class = UserSignupForm success_message = 'Account Created with the name of %{first_name} %{last_name}' -
django db settings into a .env file with decouple
I want to put my django database settings into a .env file for production. While I successfully wrote SECRET KEY and DEBUG in my .env file, when I try to do the same thing for my database settings, I get an error in the webapp. Here is the way I went about it: SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) DATABASE_ENGINE ='django_tenants.postgresql_backend' DATABASE_NAME = config('DATABASE_NAME') DATABASE_USER = config('DATABASE_USER') DATABASE_PASSWORD = config('DATABASE_PASSWORD') DATABASE_HOST = config('DATABASE_HOST', cast=db_url) DATABASE_PORT = config('PORT', cast=int) and in my .env file SECRET_KEY = supersecretkey DEBUG = False DATABASE_NAME = mydb DATABASE_USER = me DATABASE_PASSWORD = greatpassword DATABASE_HOST =urlurl DATABASE_PORT = 5432 Previously I had my db settings written as such and everything was working great: DATABASES = { 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': 'mydb', 'USER': 'me', 'PASSWORD' : 'greatpassword', 'HOST': 'urlurl', 'PORT': '5432', } } I am wondering if anybody has a clue on what I am doing wrong here? -
Django user model,Groups and profiles
well , I'm creating API with rest. and the front part is react based. each user have to login by phone number, and after the number verification, its becomes 'simple user'. after that this user can become a 'seller' or 'customer' by filling some forms. each rule in our app has a different profile and different permissions and access to views. i made a simple User Model in my account app like : class User(AbstractUser): groups = models.ForeignKey(Group, on_delete=models.CASCADE) phone_number = models.PositiveIntegerField(unique=True) and i made profile model for each user.like: class CustomerProfile (models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField() email = models.EmailField() class ServiseProviderProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField() id_card_num = models.IntegerField(unique=True) address = models.TextField() email = models.EmailField() now, I have to create groups, and somehow make relation between profiles and groups and user. but am confused... I have never worked with django before, so I have no idea how can i make it happened. APPRECIATE ANY HELP :) -
Validate several fields together in django admin
Django 3.1.5 form class GoogleAnalyticsCounterForm(forms.ModelForm): def clean(self): pass # Break return self.cleaned_data class Meta: model = GoogleAnalytics exclude = [] Registration for admin site class GoogleAnalyticsAdmin(admin.ModelAdmin): form = GoogleAnalyticsCounterForm admin.site.register(GoogleAnalytics, GoogleAnalyticsAdmin) Problem I want to validate the several form fields together. But the interpreter doesn't stop at the breakpoint in the clean method. Could you tell my why? -
Testing urls django
I have a flatpage in my website. I created it by writing this: urlpatterns = [path('admin/', admin.site.urls),path('facts/', include('django.contrib.flatpages.urls')),] After that in admin page I created a page about-me, so the whole url for that page is ‘localhost/facts/about-me/’ I tried to write test for this page: class StaticURLTests(TestCase): def setUp(self): self.guest_client = Client() def test_about_author(self): response = self.guest_client.get('/facts/about-me/') self.assertEqual(response.status_code, 200) But I get the following error: self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 FAILED (failures=1) Destroying test database for alias ‘default’… Can’t figure out why. Maybe smb was facing the same problem. I thought that the error was because of the flatpage but, the same error occured when I tried to test url of the Task model urlpatterns = [path('task/<slug:slug>/',views.task, name='task'),] Test: @classmethod def setUpClass(cls): super().setUpClass() Task = Task.objects.create( title='Title', slug=' test-slug', description='Desc', ) def setUp(self): self.guest_client = Client() user = get_user_model() self.user = user.objects.create_user(username='Bob') def test_task_url_exists_at_desired_location_authorized(self): response = self.guest_client.get('/task/test-slug/') self.assertEqual(response.status_code, 200) I tried to change response = self.guest_client.get('/task/test-slug/') to response = self.guest_client.get(reverse('/task/')) but nothing seems to work. -
Display only those objects on django admin based on the user profile which is related to user that has logged in currenty
I want to have an admin where any operator who logs in the admin dashboard can only view their package objects and not see/change package objects added by other operators (from user). My models: class Package(models.Model): operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE) destination = models.ForeignKey(Destination, on_delete=models.CASCADE) package_name = models.CharField(max_length=255) city = models.CharField(max_length=255) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) user_type = models.CharField(max_length=1, choices=USER_TYPES, default='g') first_name = models.CharField(max_length=255, default="") My package/admin.py: class PackageAdmin(ModelAdmin): icon_name = 'explore' autocomplete_fields = ['destination'] list_display = ('image_display','package_name', 'featured', 'price', 'discounted_price', 'savings', 'fix_departure', 'rating', 'date_created',) image_display = AdminThumbnail(image_field='thumbnail') image_display.short_description = 'Image' readonly_fields = ['image_display'] def get_queryset(self, request): abc = super(PackageAdmin, self).get_queryset(request) if request.user.is_superuser: return abc else: operator = request.user.id return abc.filter(operator=operator) I have overridden the get_queryset(self, request) function but it is not working. -
I am unable to Post Total HitCount Or Views from anonymous user to related Post using django web framework
I am doing a online streaming site as someone click on any post to watch then this should add a view tracking their Ip address simply and I m not getting the results Please look into the code and help my identifying the problem or if there is any better way to do that then please mention too. models.py there I created and Ip model and also added a views variable for the main Post model class IpModel(models.Model): ip = models.CharField(max_length=100) def __str__(self): return self.ip 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') cover = models.ImageField(upload_to='upload/', null=True) body = models.TextField() link = models.CharField(max_length=1000, null=True) imdb_rating = models.DecimalField(null=True, max_digits=12, decimal_places=1) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views = models.ManyToManyField(IpModel, related_name="post_views", blank=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() def total_views(self): return self.views.count() views.py Here I think there is problem in logic to render the actual count and retracting the Ip from visitor. … -
TransactionManagementError when saving model with OneToOne relationship in Django
I'm trying to make it so that when a User model is created, it also creates the corresponding MyAppProfile class to go with it. But when I do so, as I've seen online, I get an error. An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I've tried various methods to do this, and they give that error when I try it. I can't figure out why I'm getting that error, or where exactly it's coming from. My profile class: class MyAppProfile(models.Model): user = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="myapp_profile") # Other fields for this app's profile go here def __str__(self): return f'{self.id}: MyApp Profile for {self.user.username}' def save(self, *args, **kwargs): super().save(*args, **kwargs) @receiver(post_save, sender=AUTH_USER_MODEL) def update_profile_signal(sender, instance, created, **kwargs): if created: MyAppProfile.objects.create(user=instance) instance.myapp_profile.save() -
ASGI vs WSGI resource needs
i need to choose a web server for a project im doing with the need to serve a web application. while i know the difference between ASGI and WSGI web servers, i could not find any information regarding the resource needs difference between them. currently i want to make development fast and easy so i intend to use FastAPI with Uvicorn, but uncertain about the resources needed. the machine ill run it on is fairly weak, should i use Flask + gunicorn for resource saving? whats the benchmark resource difference between the 2 technologies? -
Celery Periodic task getting executed multiple times
I have a celery task that is scheduled to run at a specific time of the day. The problem is this task is getting executed multiple times, so I am receiving the same email at least 2 to 3 times. @periodic_task(run_every=crontab(hour=7, minute=10)) def send_reminder_email_at_7(): obj = Service() obj.send_email() return On server, I have setup the project using gunicorn and the supervisor Following is the configuration of celery and celery beat [program:proj_worker] command=/home/ubuntu/venv/bin/celery -A baseproj worker -l debug directory=/home/ubuntu/proj/ user=ubuntu numprocs=1 stdout_logfile=/home/ubuntu/logs/celerylogs/proj_worker.log stderr_logfile=/home/ubuntu/logs/celerylogs/proj_worker_err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 [program:proj_beat] command=/home/ubuntu/venv/bin/celery -A baseproj beat -l debug --scheduler django_celery_beat.schedulers:DatabaseScheduler directory=/home/ubuntu/proj/ user=ubuntu numprocs=1 stdout_logfile=/home/ubuntu/logs/celerylogs/proj_beat.log stderr_logfile=/home/ubuntu/logs/celerylogs/proj_beat_err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 Following is gunicorn configuration [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/ubuntu/proj ExecStart=/home/ubuntu/venv/bin/gunicorn --access-logfile /home/ubuntu/logs/gunicorn/gunicorn-access.log --error-logfile /home/ubuntu/logs/gunicorn/gunicorn-error.log --workers 3 --bind unix:/home/ubuntu/proj/proj.sock baseproj.wsgi [Install] WantedBy=multi-user.target -
django models imagefield upload_to method not working
I am using create view to create a model instance (product). Evey thing is working fine bt after doing some new migrations i can't get the uploaded image, instead getting default image. I think upload_to method of models isn't working. i also used this in my urls urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my settigs vars: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' This is my models.py: class Product(models.Model): TYPE = [ ('Sell','Sell'), ('Rent','Rent'), ('Sell or Rent','Sell or Rent'), ] owner = models.ForeignKey(Owner, on_delete=models.CASCADE) title = models.CharField(max_length = 25) type = models.CharField(max_length = 12, choices = TYPE, default = 'Sell') price = models.IntegerField() description = models.TextField(default="No Description Given") image = models.ImageField(default='default.jpeg', upload_to='product') def __str__(self): return self.title def get_absolute_url(self): return reverse('store') and this is my views.py: class ProductCreateView(LoginRequiredMixin, CreateView): model = Product fields = ['title','type', 'price','description', 'image'] def form_valid(self, form): print(self.request.POST) owner , created = Owner.objects.get_or_create(user=self.request.user) form.instance.owner = self.request.user.owner return super().form_valid(form) I am getting default image for every new product created. Thanks P.S. when i am adding product from admin panel then every thing is working fine.