Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : How i can logged in by email instead of username
I want to make the email be set in the frontend of the django application 1/I have go and create this class to make the authentification based on the email class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None 2/then I have go and define the path of this class in the settings.py 3/ everything is good without error and I logged in by typing the email, But in the frontend still the label "Username" , How i can modify it please. enter image description here Here it's the Html code form login page: <form method="POST"> {% csrf_token %} <!--this protect our form against certeain attacks ,added security django rquires--> <fieldset class="form-group"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> <small class="test-muted ml-2"> <a class="ml-2" href="{% url 'password_reset' %}">Forgot Password?</a> </small> </div> <!--- put div for a link if he is already have account---> <div class="border-top pt-3"> <small class="test-muted">Need an account? <a class="ml-2" href="{% url 'register' %}">Sign Up</a></small> <!--it a bootstrap --> </div> </form> Thanks in advance. -
how to make my trigger function to perform asyncronously to update tsvector field?
I am new to postgres. Suppose i have two models AnimalType and Animal. And i have search_vector field of type tsvector in Animal model. i created trigger that whenever i update a AnimalType row, the searchvector should update itself for every Animal related to that AnimalType. CREATE OR REPLACE FUNCTION update_animal_type() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN UPDATE animal SET search_vector = NULL WHERE animal_type_id = NEW.id; RETURN NEW; END; $$; CREATE TRIGGER animal_type_update_trigger AFTER UPDATE OF animal_type_name ON animal_type FOR EACH ROW EXECUTE PROCEDURE update_animal_type(); It takes a lot of time to update a single animal type row when we have large number of animals related to that particular animal type. Is this behaviour is synchronous or asynchronous? If it is synchronous how can i make it to behave asynchronous? -
Original exception text was: 'int' object has no attribute 'name'. in django rest framework
I am trying to call a get api but it gives me this error everytime. The error: AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer. The serializer field might be named incorrectly and not match any attribute or key on the int instance. Original exception text was: 'int' object has no attribute 'name'. My models: class Destination(models.Model): Continent_Name = ( ('Europe', 'Europe',), ('Asia', 'Asia',), ('North America', 'North America',), ('South America', 'South America',), ('Africa', 'Africa',), ('Oceania', 'Oceania',), ('Polar', 'Polar',), ('Regions', 'Regions',), ) name = models.CharField(max_length=255, unique=True) continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe') top = models.BooleanField(default=False) dest_image = models.ImageField(blank=True) def __str__(self): return self.name class Package(models.Model): TOUR_TYPE = ( ('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',), ('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',), ('Group Tour', 'Group Tour',), ('Cruise Tour', 'Cruise Tour',), ) 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) featured = models.BooleanField(default=False) price = models.IntegerField(verbose_name="Price in Nrs") price_2 = models.IntegerField(verbose_name="Price in $") duration = models.IntegerField(default=5) duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour") discount = models.IntegerField(verbose_name="Discount %", default=15) #discounted_price = models.IntegerField(default=230) #savings = models.IntegerField(default=230) tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour') new_activity … -
How to get Substr when annotate Django
I'm try to sort by order_number had many kind Input: ADC123 ADC14 ADC23 ERD324 ERD12 Sort default just sort by alphabet Expected results (Sort only by number): ERD12 ADC14 ADC23 ADC123 ERD324 Code example: Person.objects.annotate( order_only_number=AddField(Substr("order_number", 1)) ).order_by("order_only_number") -
Cropper JS zooms image on mobile when disabled
I am trying to use cropper JS to allow users to crop images on upload. However I want to disable zooming on mobile as I don't believe it is very user friendly. I have attempted to disable everything to do with zoom, moving and scaling but every time I try resize the cropper on my mobile it zooms. Any ideas on how to disable? <div class="img-container image-container" id="id_image_container"> <img class="profile-image" id="id_image_btn_display" src=""> <div class="img-btn" id="id_middle_container"> <div class="btn btn-primary" id="id_text">Upload Picture<br><small>(Max size: 10MB)</small></div> </div> <div class="p-5"> <input class="d-none" type="file" name="profile_image" id="id_image_btn" onchange="readURL(this)"> </div> </div> <script type="module" src="{% static 'cropperjs/dist/cropper.min.js' %}"></script> <script> // start cropperjs var cropper; var imageFile; var base64ImageString; var cropX; var cropY; var cropWidth; var cropHeight; const minCroppedWidth = 300; function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { disableImageOverlay() var image = e.target.result var imageField = document.getElementById('id_image_btn_display') imageField.src = image cropper = new Cropper(imageField, { // attempted to disable all zooming features zoomable: false, zoomOnTouch: false, zoomOnWheel: false, toggleDragModeOnDblclick: false, scaleable: false, movable: false, crop(event) { var cropWidth = event.detail.width // Stop crop box at minCroppedWidth if (cropWidth < minCroppedWidth) { cropper.setData({ width: Math.max(minCroppedWidth, cropWidth)}) }; setImageCropProperties( image, event.detail.x, … -
constrains on django model with ForeignKey
Suppose we have this django models: from django.db import models # Create your models here. class Artist(models.Model): name = models.CharField(max_length=10) class Album(models.Model): name = models.CharField(max_length=10) date = models.DateField() artist = models.ForeignKey(Artist, on_delete=models.CASCADE) So I can write: artist_one = models.Artist.objects.create(name='Santana') album_one = models.Album.objects.create(name='Abraxas', date = datetime.date.today(), artist=artist_one) album_two = models.Album.objects.create(name='Supernatural', date = datetime.date.today(), artist=artist_one) How can I add a constrain to the Album class as to say an artist cannot publish two albums the same year? -
django form queryset filter using request user
I want to filter queryset using current user data but it's return only a Nonetype Suppose When I remove None its shows the error user can't recognize In Forms.py class oldenquiryForm(forms.ModelForm): class Meta: model=enquiry fields=['product','type','created_at'] widgets={ 'created_at':forms.DateInput(attrs={'type':'date'}), } def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) user = kwargs.pop('user', None) super(oldenquiryForm, self).__init__(*args, **kwargs) employee = emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True) print (employee) self.fields['created_by'].queryset=emp.objects.filter(branch=user.admin.branch_name).values_list('firstname',flat=True) -
Django HttpResponseRedirect wont redirect when message sent
I want my page to reload and show the django messages sent to the page when a POST call is made (by another user). From api I am calling the method like that: def create(self, request, pk=None): json_data = json.loads(request.body) sample_path = json_data['sample_path'] try: sample = BloodSample.objects.get(sample_path = sample_path) if json_data['status'] == 201: BloodSampleAdmin(sample, BloodSample).display_messages(request, sample) return Response(json_data['body'], status = status.HTTP_201_CREATED) and the method in BloodSampleAdmin is: def display_messages(self, request, sample): messages.success(request, ("hurray")) return HttpResponseRedirect(reverse( "admin:backend_bloodsample_change", args=[sample.id] )) I am 100% sure that the method is called (debug). But message wont pop anyway. I am using Postman to send the POST request. Any ideas on what is going wrong? -
Python, django sessions, how update django session by key
i try to update my session data my code: try: s = Session.objects.get(session_key=token) except ObjectDoesNotExist: return 400, {"error": "Token invalid."} newObject = {'user_pk': 3, 'company_id': 55} s['user_login_info'] = newObject s.save() but i get error TypeError: 'Session' object does not support item assignment how correctly update session data? -
How to pass two or more parameters in Django URL
How can I able to pass two or more parameters in Django URL in this way api/Data/GetAuditChecklistDataForEdit/HRR6627687%7C458%7CRegular It is a get method so I can't get the values of the two parameter (SID, Type) so I'm trying to pass it through the URL Is it possible to pass two or more parameter in this way views.py: @api_view(['GET']) def GetAuditChecklistDataForEdit(request, ticket, SID, Type): if request.method =='GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetAuditChecklistDataForEdit] @ticket=%s, @setid=%s, @Type=%s', (ticket, SID, Type)) result_set = cursor.fetchall() data =[] for row in result_set: print("GetAuditChecklistDataForEdit",row[0]) data.append({ 'QId':row[0], 'Question':row[1], 'AnsOption':row[2], 'Choice':row[3], 'Agents':row[4], 'StreamId':row[5], 'Supervisor':row[6], 'Action':row[7], 'subfunction':row[8], 'region':row[9], 'Comments':row[10], 'TicketType':row[11], }) return Response(data) urls.py: path('Data/GetAuditChecklistDataForEdit/<str:ticket>', GetAuditChecklistDataForEdit, name='GetAuditChecklistDataForEdit'), -
Need to take two fields from one model and use it as foreign key for a new model using django
Model 1 class Users(models.Model): employee_name = models.CharField(max_length=210) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=100,default=None) aadhar=models.CharField(max_length=100,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) emergency_contact_no=models.IntegerField(default=None) name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) joining_role=models.CharField(max_length=250,choices=JOINING_ROLES_CHOICES,null=True) billable_and_non_billable=models.CharField(max_length=250,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) def __str__(self): return self.employee_name Model 2 class Consolidated(models.Model): emp_name=models.ManyToManyField(Users,related_name="employee_name+") proj_name=models.ManyToManyField(Project) custom_name=models.ManyToManyField(Client) Cons_date=models.ManyToManyField(Add_Timelog) bill_no_bill=models.ManyToManyField(Users,related_name="billable_and_non_billable+") hour_spent = models.ManyToManyField(Add_Timelog,related_name="hour_spent") def __str__(self): return str(self.emp_name) I need to take the value updated on the "employee_name" and "billable_and_non_billable" field in the "User" model to "emp_name" and "bill_no_bill" field in "Consolidated" model. Will it be possible to take two fields as foreign key from one model to another. I'm new this django kindly help me if there is any possible ways. -
gunicorn.service: Failed to determine user credentials: No such process - django, gunicorn, and nginx
When I run sudo systemctl status gunicorn, I get the following error: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2022-02-08 07:29:18 UTC; 17min ago Main PID: 21841 (code=exited, status=217/USER) Feb 08 07:29:18 ip-172-31-37-113 systemd[1]: Started gunicorn daemon. Feb 08 07:29:18 ip-172-31-37-113 systemd[21841]: gunicorn.service: Failed to determine user credentials: No such process Feb 08 07:29:18 ip-172-31-37-113 systemd[21841]: gunicorn.service: Failed at step USER spawning /home/ubuntu/bookclub/venv/bin/gun Feb 08 07:29:18 ip-172-31-37-113 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Feb 08 07:29:18 ip-172-31-37-113 systemd[1]: gunicorn.service: Failed with result 'exit-code'. I'm following this tutorial from DigitalOcean to get my Django website onto my EC2 instance. I'm using Nginx and Gunicorn with Django to accomplish this. This is my gunicorn.service file at /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/ubuntu/bookclub ExecStart=/home/ubuntu/bookclub/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/bookclub/books.sock books.wsgi:application [Install] WantedBy=multi-user.target I checked for books.sock in my project folder with ls and I saw that books.sock does not exist. -
Django Session Variable Is Accessible Even After Deletion
I tried to delete the session after the work is complete. But, it still shows a different value when checking if the session variable exists. if 'order_id' in request.session: # here the value of session variable is 28 del request.session['order_id'] request.session.modified = True When I checked again it returned True even though I deleted the variable, if 'order_id' in request.session: # here the value of session variable is 5118 print('yes') -
After dropping database, I am getting this ModuleNotFoundError: No module named 'myproject' error
I ran into a database out of sync error and so I dropped one database in development mode and synced my settings to a newly created postgresql database. I removed my pycache and migrations prior to creating a new database and then ran the "python3 manage.py makemigrations" and "python3 manage.py migrate". Here is a link to the prior error and code if that's necessary to know. django.db.utils.ProgrammingError: column accounts_account.username does not exist However, when I ran "python3 manage.py createsuperuser" it gave me this ModuleNotFoundError: No module named 'myproject' error. I don't quite understand this error because I never named my project 'myproject'. Perhaps, I am not understanding something when dropping one database and setting up a new database. Traceback (most recent call last): File "/Users/taniryla/ecommerce/manage.py", line 22, in <module> main() File "/Users/taniryla/ecommerce/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/anaconda3/envs/skincareryland/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/Users/taniryla/ecommerce/accounts/models.py", line 27, in create_superuser user = self.create_user( File "/Users/taniryla/ecommerce/accounts/models.py", line 22, in create_user … -
Alternative for StringRelatedField
I am trying to get following user with their names instead of PrimaryKey, I tried to use StringRelatedField. It worked for GET request, but it does not allow to write. Could not find any alternatives for this. I want to get json result as this: { "id": 1, "user": "admin", "following": "user_1" } I assume instead of using StringRelatedField I should redefine create in serializers, am I right? model.py class Follow(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='follower' ) following = models.ForeignKey( User, on_delete=models.CASCADE, related_name='following' ) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'following'], name='unique_user_following' ) ] def __str__(self) -> str: return self.following serializer.py class FollowSerializer(serializers.ModelSerializer): user = serializers.SlugField( read_only=True, default=serializers.CurrentUserDefault() ) # following = serializers.StringRelatedField() class Meta: model = Follow fields = ('id', 'user', 'following',) validators = [ serializers.UniqueTogetherValidator( queryset=Follow.objects.all(), fields=('user', 'following',) ) ] def validate_following(self, value): if value == self.context.get('request').user: raise serializers.ValidationError( 'You can not follow yourslef!' ) return value views.py class FollowViewSet(viewsets.ModelViewSet): serializer_class = FollowSerializer def get_queryset(self): new_queryset = Follow.objects.filter(user=self.request.user) return new_queryset def perform_create(self, serializer): serializer.save(user=self.request.user) -
How to position content beside sidebar?
I am not very well versed in HTML and CSS. I am currently building a web application using Django and I integrated a sidebar into my web application using Bootstrap, but it has messed my layouts, and I can't seem to figure out how to move the content in a block to the left of side of my sidebar. As seen in the pictures above, my sidebar is located at the top and my content is located at the bottom. Below are my codes for my sidebar and the base template. sidebar_template.html <div class="d-flex flex-column vh-100 flex-shrink-0 p-3 text-white bg-dark sidebar-height" style="width: 250px;"> <a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none"> <svg class="bi me-2" width="40" height="32"> </svg> <span class="fs-4">CPRS Admin</span> </a> <hr> <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="#" class="nav-link active" aria-current="page"> <i class="fa fa-home"></i><span class="ms-2">Home</span> </a> </li> <li> <a href="{% url 'coordinator_dashboard' %}" class="nav-link text-white"> <i class="fa fa-dashboard"></i><span class="ms-2">Dashboard</span> </a> </li> <li> <a href="{% url 'coordinator_view_students' %}" class="nav-link text-white"> <i class="fa fa-first-order"></i><span class="ms-2">Students</span> </a> </li> <li> <a href="#" class="nav-link text-white"> <i class="fa fa-cog"></i><span class="ms-2">Settings</span> </a> </li> <li> <a href="#" class="nav-link text-white"> <i class="fa fa-bookmark"></i><span class="ms-2">Bookmarks</span> </a> </li> </ul> <hr> <div class="dropdown"> <a href="#" class="d-flex align-items-center text-white … -
Dockerized kong not able to redirect the request to django which is inside docker
am new to kong and i installed kong and django inside my docker.from kong am able to forward the request to other servers but it is giving "received an invalid response from upstream server " when am trying to test the django api please help, Thanks -
Make django parent model accessible to formset without displaying it in html
I have page1 with two links (‘A’ and ‘B’) on it the specific link that is clicked determines a query parameter /page2/?q=A or /page2/?q=B. On page 2 the user completes an inline formset, the parent form of which has been set to a value of ‘A’ or ‘B’ depending on the link clicked on the previous page. I do not want to display the parent form but if this is not displayed then I am unable to successfully save the formset and parent form. The views.py for page 2 is: class CaseView(TemplateView): model = Case template_name = “page2/page2.html” def get(self, *args, **kwargs): # parent form case_form = CaseForm # child formset sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none()) return self.render_to_response( { "case_form": case_form, "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) def post(self, *args, **kwargs): form = CaseForm(data=self.request.POST) sideeffect_formset = SideeffectFormSet(data=self.request.POST) if form.is_valid(): case_instance = form.save(commit=False) if self.request.user.is_authenticated: case_instance.user = self.request.user case_instance.save() if sideeffect_formset.is_valid(): sideeffect_name = sideeffect_formset.save(commit=False) for sideeffect in sideeffect_name: sideeffect.case = case_instance sideeffect.save() return redirect( reverse( "results", kwargs={"case_id": case_instance.case_id}, ) ) I want to be able to save CaseForm and have it available for the childformset without actually displaying CaseForm in the html -
How to save python class object / instance in django models Fields
I am trying to authenticate with some proxies with requests.Session(). after authenticated I want to save the session object for future use. Is there any method that can help me to save request class object in Django fields. What I want is in My model want too create an field class Proxy(models.Model): name = models.CharField(max_length=300) username = models.CharField(max_length=60, blank=True, default="") password = models.CharField(max_length=20, blank=True, default="") ip = models.GenericIPAddressField(protocol='IPv4',unique=True) session=models.**ObjectofRequests**(requests.Session,on_delete=models.CASCADE)<-- like this def __str__(self): return self.name save this after getting session s = requests.Session() proxies = { "http": "http://user:pass@Ip:port", "https": "http://user:pass@Ip:port" } s.proxies = proxies obj = Proxy(name='Any',username=user,password=pass,session=s) obj.save() -
OSError: no library called "cairo-2" was found on mac m1
I've recently installed weasyprint and cairo and tried to run django server. But, I'm getting this error OSError: no library called "cairo-2" was found no library called "cairo" was found no library called "libcairo-2" was found cannot load library 'libcairo.so.2': dlopen(libcairo.so.2, 0x0002): tried: 'libcairo.so.2' (no such file), '/usr/lib/libcairo.so.2' (no such file), '/Users/ajaypatel/Desktop/Dukaan/optimus-order/libcairo.so.2' (no such file), '/usr/lib/libcairo.so.2' (no such file) cannot load library 'libcairo.2.dylib': dlopen(libcairo.2.dylib, 0x0002): tried: 'libcairo.2.dylib' (no such file), '/usr/lib/libcairo.2.dylib' (no such file), '/Users/ajaypatel/Desktop/Dukaan/optimus-order/libcairo.2.dylib' (no such file), '/usr/lib/libcairo.2.dylib' (no such file) cannot load library 'libcairo-2.dll': dlopen(libcairo-2.dll, 0x0002): tried: 'libcairo-2.dll' (no such file), '/usr/lib/libcairo-2.dll' (no such file), '/Users/ajaypatel/Desktop/Dukaan/optimus-order/libcairo-2.dll' (no such file), '/usr/lib/libcairo-2.dll' (no such file) I'm facing this issue on mac m1 chip -
Customize django-otp email template
I'm doing two-factor authentication (2FA) in my Django app and using django-otp package. I want to send my custom email to users. I followed the official documentation and added my custom settings as follow: # django-otp template OTP_EMAIL_SUBJECT = _('Please confirm your login attempt') OTP_EMAIL_BODY_TEMPLATE_PATH = 'account/email/login_confirmation_otp.html' The above settings are working and it's sending the email in text/plain content type but I want text/html content type. The following code is sending the email: def generate_challenge(self, extra_context=None): """ Generates a random token and emails it to the user. :param extra_context: Additional context variables for rendering the email template. :type extra_context: dict """ self.generate_token(valid_secs=settings.OTP_EMAIL_TOKEN_VALIDITY) context = {'token': self.token, **(extra_context or {})} if settings.OTP_EMAIL_BODY_TEMPLATE: body = Template(settings.OTP_EMAIL_BODY_TEMPLATE).render(Context(context)) else: body = get_template(settings.OTP_EMAIL_BODY_TEMPLATE_PATH).render(context) send_mail(settings.OTP_EMAIL_SUBJECT, body, settings.OTP_EMAIL_SENDER, [self.email or self.user.email]) message = "sent by email" return message in django_otp/plugins/otp_email/models.py. I want to override generate_challenge() function and add html_message in send_email() function but don't know how to do it? -
How to run my Django project continuously on EC2 server?
I am trying to deploy my Django Project on our EC2 server continuously. The application is running good but it is stopping when I close putty. So to achieve this I followed this documentation https://studygyaan.com/django/how-to-setup-django-applications-with-apache-and-mod-wsgi-on-ubuntu When I tried this blog with sample example then it is working good and it is running continuously on apache but the same process when I am applying to my Django project then it is not working on apache. The below versions I am using Python 3.8 Django==3.0.5 djongo==1.2.38 pymongo==3.10.1 Can anyone please help me with this ? How to deploy Django application to run continuously on EC2 server ? -
How foreign key is working here - Django class based models?
I have added a sample table. Can someone explain how this is One to Many relationships? And how is foreignKey working here? class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.FOreignKey(User, on_delete=models.CASCADE) # USER TABLE # user_id user_name pwd # 1 Alex 123 # 2 Bob 123 # AUTHOR TABLE # author_id(fk) author_name # 1 Alex # 2 Bob # POST TABLE # post_id title content date_posted author(fk) # 1 bp1 bc1 12 alex # 2 bp2 bc2 12 alex # 3 bp3 bc3 12 bob -
Celery beat sends the same task twice to the worker on every interval
I have the following scheduled task in example_app -> tasks.py: @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute='*/1'), test.s(), ) @app.task def test(): print('test') However this scheduled task is executed twice every minute: celery_1 | [2022-02-08 16:53:00,044: INFO/MainProcess] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] received celery_1 | [2022-02-08 16:53:00,046: INFO/MainProcess] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] received celery_1 | [2022-02-08 16:53:00,046: WARNING/ForkPoolWorker-6] test celery_1 | [2022-02-08 16:53:00,047: WARNING/ForkPoolWorker-7] test celery_1 | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-6] Task example_app.tasks.test[a608d307-0ef8-4230-9586-830d0d900e67] succeeded in 0.0014668999938294291s: None celery_1 | [2022-02-08 16:53:00,048: INFO/ForkPoolWorker-7] Task example_app.tasks.test[5d5141cc-dcb5-4608-b115-295293c619a9] succeeded in 0.001373599996441044s: None I read that this can be caused when you change django timezone from UTC, which I have done on this project. I tried this solution from another question but it doesn't stop the duplication: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.base') class MyCeleryApp(Celery): def now(self): """Return the current time and date as a datetime.""" from datetime import datetime return datetime.now(self.timezone) app = MyCeleryApp('tasks') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() settings: CELERY_BROKER_URL = "redis://redis:6379/0" CELERY_RESULT_BACKEND = "redis://redis:6379/0" running in docker: celery: restart: always build: context: . command: celery --app=config.celery worker -l info depends_on: - db - redis - django celery-beat: restart: always build: context: . command: celery --app=config.celery beat -l info depends_on: - db - redis - … -
My sqlite3 database does not creates new post when its deployed in heroku [duplicate]
I have created a site for posting blogs and sites . Here is the link . But the point is after I have created it and hosted it. And when I am creating new posts in the deployed site. The posts disappear after some time and the posts which I have deleted again get showing up . I want to know why this happens and how can I overcome the situation and make the site working . I am beginner in django . Any kind of suggestion will be very helpful and it will help me a lot . Also the new users which were created after the deployment of the site also were deleted or disappeared and the posts created by the new users were deleted . Kindle help me . Any thing which you want I will provide all the things here . This is the github repository for the site Github link