Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django project on apache2 over HTTPS
Currently, I have deployed django project on AWS Ec2 instance using Gunicorn and apache2 as server Also for executing Gunicorn, I have used supervisor Following is my current configuration: gunicorn.conf (location: /etc/supervisor/conf.d) [program:gunicorn] directory=/home/ubuntu/python-projects/web-app command=/home/ubuntu/python-projects/web-app/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:5010project.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicron.out.log [group:guni] programs:gunicorn django.conf (location: /etc/apache2/sites-available) server { listen 5010; server_name <server_name_here>; location /{ include proxy_params; } location /static/ { autoindex on; alias /home/ubuntu/python-projects/web-app/project/static/; } } Everything is working properly over HTTP and can also serve static files Issue is, I want to run the project over HTTPS, tried many solutions but unsuccessful till now -
Update table values based on which button clicked
I have a DetailView that show all the transaction information from transaction id, name, created_date,...., and status. In this pages I have 3 button they are cancel, approve, and reject. what I want to do is when I clicked button cancel the status changed to "Cancelled", some goes for reject and approve that change the status to "Rejected" and "Success". how can I do this? I've tried to add form in the template with hidden input and method post, but after submit it show 405 error page. -
Can we connect locally created lambda to local dynamodb?
I am trying to establish a connection between the locally created lambda function and local dynamodb. I set up both lambda and dynamodb locally but don't know how to connect them? Actually, I am intended to create a Django project in local lambda and I want to use local dynamodb in it. If someone knows how to configure this, please guide me. -
Dockerized Django Application Deployed to AWS Elastic Beanstalk Flushes Database Everytime I Rebuild My Environment
I have deployed a django application using docker to AWS Elastic Beanstalk that is connected to an AWS RDS postgresql database. Everytime I update my code and rebuild my docker image, the database is always wiped clean. I am using github actions to deploy my application everytime I push my code. After searching for similar issues, most people suggest that there might be a flush command in one of the deployment scripts. That is not the case in my deployment scripts because I never explicitly flush the database. Github Actions Config name: Staging Docker Image CI on: push: branches: [ staging ] pull_request: branches: [ staging ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: lfs: 'true' - name: Build the Docker image run: docker build -t scrims -f Dockerfile . - name: Generate Deployment Package run: zip -r deploy.zip * - name: Get timestamp uses: gerred/actions/current-time@master id: current-time - name: Run string replace uses: frabert/replace-string-action@master id: format-time with: pattern: '[:\.]+' string: "${{ steps.current-time.outputs.time }}" replace-with: '-' flags: 'g' - name: Deploy to EB uses: einaregilsson/beanstalk-deploy@v14 with: aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} application_name: scrims environment_name: scrims-env-staging version_label: "scrims-staging-${{ steps.format-time.outputs.replaced }}" region: ap-southeast-1 deployment_package: deploy.zip Dockerfile # … -
django models relations getting count of given tasks
Trying to fetch a function from a table that is supposed to be there, but cannot get the value. Trying to get the amount of task that is completed. models.py class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") start_date = models.DateTimeField() due_date = models.DateTimeField() checklist = models.ManyToManyField(Checklist, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def get_url(self): return reverse('checklists', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task_completed(self): return self.task_completed.count() class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, related_name='projects') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default="Project description") date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() due_date = models.DateTimeField() tasks = models.ManyToManyField(Task, blank=True) teams = models.ManyToManyField(Team, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def get_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task(self): return self.tasks.count() Then in the html is just loop through all projects {% for projects in projects.all %} <span class="text-small"> {{ projects.tasks.num_task_completed }} /{{ projects.num_task }}</span> I manage to get the amount of tasks, but not the amount completed. -
Automate deploying of synapse artifacts to devops repo
im trying to deploy some synapse artifacts to a synapse workspace with devops repo integration via a python runbook. By using the azure-synapse-artifacts library of the python azure sdk the artifacts are published directly to the live mode of the synapse workspace. Is there any way to deploy artifacts to a devops repo branch for synapse? Didnt find any devops repo apis or libaries, just for the direct integration of git. -
How to display one models data in another model django admin panel
I have two models: 1) SchoolProfile & 2) Content I want to show content data in schoolprofile, But data should be display as per user foreignkey. User foreignkey common for both the models. School Profile Model class SchoolProfile(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True) school_name = models.CharField(max_length=255) school_logo=models.FileField(upload_to='media/', blank=True) incharge_name = models.CharField(max_length=255, blank=True) email = models.EmailField(max_length=255, blank=True) phone_num = models.CharField(max_length=255, blank=True) num_of_alu = models.CharField(max_length=255, blank=True) num_of_student = models.CharField(max_length=255, blank=True) num_of_cal_student = models.CharField(max_length=255, blank=True) def __str__(self): return self.school_name Content Model class Content(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) content_type = models.CharField(max_length=255, blank=True, null=True) show=models.ForeignKey(Show,on_delete=models.CASCADE, blank=True, null=True) sponsor_link=models.CharField(max_length=255, blank=True, null=True) status=models.BooleanField(default=False, blank=True, null=True) added_on=models.DateTimeField(auto_now_add=True) content_file=models.FileField(upload_to='media/', blank=True, null=True) title = models.CharField(max_length=255) subtitle = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=500, blank=True, null=True) draft = models.BooleanField(default=False) publish_now = models.CharField(max_length=255, blank=True, null=True) schedule_release = models.DateField(null=True, blank=True) expiration = models.DateField(null=True, blank=True) tag = models.ManyToManyField(Tag, null=True, blank=True) topic = models.ManyToManyField(Topic, null=True, blank=True) category = models.ManyToManyField(Categorie, null=True, blank=True) def __str__(self): return self.title I have used Inline but it's show below error: <class 'colorcast_app.admin.SchoolProfileInline'>: (admin.E202) 'colorcast_app.SchoolProfile' has no ForeignKey to 'colorcast_app.SchoolProfile'. My admin.py class SchoolProfileInline(InlineActionsMixin, admin.TabularInline): model = SchoolProfile inline_actions = [] def has_add_permission(self, request, obj=None): return False class SchoolProfileAdmin(InlineActionsModelAdminMixin, admin.ModelAdmin): inlines = [SchoolProfileInline] list_display = ('school_name',) admin.site.register(SchoolProfile, SchoolProfileAdmin) -
Using python-lambda-local for django project
I am using python-lambda-local for testing aws-lambda function on local environment. Now I have django project like this /chatbot - /utilities settings.py entry.py and settings.py has entry point def hander For example, I can exec entry.py handler like this $python-lambda-local -f handler -t 5 entry.py event.json However of course it ignores the settings.py, and django environment. What is the bet practice to use django with aws lambda. -
JSON generated by json.dumps() is NOT valid according to RFC 4627
My Django management command generates some JSON. It creates a couple of Python dictionaries, puts them into another dictionary, and uses json.dumps() to convert to JSON. It then tries to save it to JSONField in database using a Django Model. The JSON is not saving due to it not being valid. I checked the JSON with many validators. They all said the JSON is invalid due to: Error: Parse error on line 1: { 'nodes': [{ 'name' --^ Expecting 'STRING', '}', got 'undefined' Eventually I found a validator that said the JSON is Javascript valid but not RFC4627 valid: I can't post the JSON here due to it being sensitive. Is there any reason json.dumps() would generate invalid JSON ? -
DRF serializer parsing comma-delimited string into a list field
Is there a way of modifying how DRF serializers parse incoming request payload? I'm trying to let clients send a comma-delimited list as query parameter but receive it inside the serializer as a list instead but DRF keeps complaining. Right now I'm manually intercepting the request in the view and doing the parsing that field manually before passing it to the serializer which doesn't seem elegant to me. What I'm doing right now class ExampleSerializer(...): list_field = serialzers.ListField(child=serializers.Integerfield(...)) # more fields def view(request): payload = request.GET payload["list_field"] = str(payload.get("list_field", "")).split(",") serializer = ExampleSerializer(data=payload) What I'd prefer (using same serializer as above) def view(request): serializer = ExampleSerializer(data=request.GET) -
How to prevent image bigger than box
I have this code : <div class="row d-flex p-3 mb-4" style="border: 1px solid rgba(0, 0, 0, 0.1)"> {{ content_page.additional_content|safe }} </div> "additional content" is text field (using CKEditor) and can contain images. I want to make it so that the contents can't be bigger than the box or parent. How can I do that? Thanks. -
Group queryset into categories django
I have a Ingredient model and a Shopping model for a shopping list and I would like to group ingredients by their category in the shopping list view. Is there a SQL method to do this or will running for loops for every category in the Shopping model the easiest way to accomplish this? The below image is an example of what I would like to achieve in my shopping list view: #models.py class Ingredient(models.Model): name = models.CharField(max_length=220) category = models.CharField(max_length=50, default="uncategorised") class Shopping(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=220, blank=True, null=True) # users can create their own items not just those in the Ingredient model category = models.CharField(max_length=80, default="uncategorised") -
'RelatedManager' object has no attribute 'payment_status'
I am creating an app in which I want to query all the members and their status. but I am getting this error. these are my both models. class Member(models.Model ): user = models.ForeignKey(Users,verbose_name='User Id', on_delete=models.CASCADE) com = models.ForeignKey(Committee, on_delete=models.CASCADE,verbose_name='Committee Name') class PaymentDetail(models.Model): mem = models.ForeignKey(Member,on_delete=models.CASCADE, related_name='payment_details', verbose_name='Memeber Phone no') com = models.ForeignKey(Committee, on_delete=models.CASCADE,related_name='committee_details',verbose_name='Committee Name') payment_month = models.DateField(default=datetime.now()) payment_status = models.CharField(max_length=16, choices=PAYMENT_DETAILS_CHOICES, default="1") First I am getting all the members by (members.objects.all() then looping over like this for member in members: member.payment_details.payment_status but I am getting this error related manager has no attribute. actually I can get data from PaymentDetail.objects.all() but it will only show data from PaymentDetail table. I want all the members and next to them their status from PaymentDetail table -
getting trouble in django-admin setup
PS C:\Users\laveen\pycharmprojects\DjangoCourse> django-admin django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django-admin + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Recieve and use JWT token/Token in Web Socket using django-channels
What I need to know? I want to receive JWT Token while connecting in web socket. I want to use JWT token. What I am using? django for project. django-channels for implementing Web Socket. -
How to delete a Django model object automatically after 24 hrs
I am new to django. I want to delete a model object automatically after the specific time. This is my model i want to delete class CustomerOrder(models.Model): order_types = ( ('dinein','Dinein'), ('delivery','Delivery'), ('pickup','Pickup') ) restaurant = models.ForeignKey(RestaurantDetail,on_delete=models.CASCADE,null=True) customer_name = models.CharField(max_length=30,null=True) table_no = models.IntegerField(null=True) total_price = models.FloatField(null=True,blank=True) success = models.BooleanField(default=False,blank=True,null=True) status = models.CharField(max_length=15,default='pending',null=True) ordered_menu = models.ManyToManyField(OrderedMenu) timestamp = models.DateTimeField(default=datetime.datetime.now()) order_type = models.CharField(max_length=15,default='dinein',choices=order_types) the timestamp is the saved time of the current object. is any idea about how to delete a model object automatically after the specific time? (example after 24 hrs). -
Please help me to figure out where is the actual bugs, I did correctly but didn't get to work as expected
{% extends 'main.html' %} {% load static %} {% block content %} {% if page == "register" %} <h1>Hello This is register Page!!!</h1> <form method="POST" action="{% url 'register' %}"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Register" /> </form> <p>Aready have an account <a href="{% url 'login' %}"> Login </a></p> {% else %} <div class="auth"> <div class="card"> <div class="auth__header text-center"> <a href="/"> <img src="{% static 'images/icon.svg' %}" alt="icon" /> </a> <h3>Account Login</h3> <p>Hello Developer, Welcome Back!</p> </div> <form action="{% url 'login' %}" method="POST" class="form auth__form"> {% csrf_token %} <!-- Input:Email --> <div class="form__field"> <label for="formInput#text">Username: </label> <input class="input input--text" id="formInput#text" type="text" name="username" placeholder="Enter your username..." /> </div> <!-- Input:Password --> <div class="form__field"> <label for="formInput#password">Password: </label> <input class="input input--password" id="formInput#passowrd" type="password" name="password" placeholder="••••••••" /> </div> <div class="auth__actions"> <input class="btn btn--sub btn--lg" type="submit" value="Log In" /> <a href="forgetpassword.html">Forget Password?</a> </div> </form> <div class="auth__alternative"> <p>Don’t have an Account?</p> <a href="{% url 'register' %}">Sign Up</a> </div> </div> </div> {% endif %} {% endblock content %} and here is the error I have been taking Udemy course "Learn to build awesome websites with Python & Django!" by Dennis Ivy and I have reached almost middle of the course but when I reached here I was badly … -
get more than two foreign keys from another django table and perform calculations on them
In the Django app, I have created two tables. Product Invoice I have one table called Product which contains product name and product price columns are given. Then, I have a second table named Invoice which contains a product name(foreign key), product price(foreign key), discount, and total. My concern is how can I import both the values from the Product table i.e. product name and product price and perform calculations on them. The structure is given below: myapp -> PRODUCT: *Product Name *Product Id *Product Price INVOICE: *Product Name (foreign key) *Product Id (foreign key) *Product Price (foreign key) *Discount *Total = Product Price - Discount how can I import values and perform further calculations? -
Changing the opacity of the colour on the Polar Area chart
I am using Chart.js to create a set of polar area charts, I want to change teh opacity of the colour used to display the data so it is slightly transparent. Below you will find the code: var totals = {{ class_submission_totals|safe }} {% for t in type_qs %} var labels_{{ t.pk }} = [] var backgroundColors_{{ t.pk }} = [] {% for b in behaviour_qs %} {% if b.type.pk == t.pk and not b.previous %} labels_{{ t.pk }}.push("{{ b.title }}") backgroundColors_{{ t.pk }}.push("{{ b.primarycolour }}") {% endif %} {% endfor %} {% endfor %} new Chart("chart_{{ i.pk }}_{{ t.pk }}", { type: "polarArea", data: { labels: labels_{{ t.pk }}, datasets: [{ fillOpacity: 0.3, pointRadius: 1, backgroundColor: backgroundColors_{{ t.pk }}, data: totals_{{ i.pk }}_{{ t.pk }}_arr, }] }, options: { responsive: false, maintainAspectRatio: true, plugins: { legend: { display: true, }, title: { display: false, text: 'Chart.js Polar Area Chart' } } } }); {% endfor %} {% endfor %} -
django html: copy form input data and display in another page
I am trying to develop a delivery service web where users can input pickup and delivery address in the form and get the price online. if the price is fine, the user can click "place order" button which will navigate into another new page for user to fill in additional information, and importantly the previously input piackup and delivery addresses and the price will need to automatically shown somewhere in the new page. I am new to django and html, and I have tried to created a simpler page serving the same purpose. Now I could do the first part of form filling, and the backend calculate based on the user input and return the calculation result (e.g. price). Now, I am wondering how to do the "navigation to another new page which will display the two input values and calculation result" Main html: <html> <body> <form method="POST" hx-post="{% url 'blog:post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> … -
there is a problem in the login part of my project [closed]
my form is not working for some reason. that is, it does not give the expected result my views.py def TeacherLogin(request): if request.method == 'POST': form = TeacherLogin(data = request.POST) if form.is_valid(): user = authenticate(username=username, password=password).first() # user = User.objects.filter(username=username).first() if user is not None: return redirect('home') else: form = TeacherLogin() my forms.py class TeacherLoginForm(ModelForm): class Meta: model = User fields = ('username', 'password') my urls.py #in apps from django.urls import path, include from .views import * app_name = 'teachers' urlpatterns = [ path('teacherlogin/', TeacherLogin, name='teacherlogin'), ] -
How to programmatically make a user to assign permissions on template?
As you all know django admin has a function to give "Permissions" for user on their admin panel ! How to do that programmatically ? For example lets say i have a super user and the user can create staff users under them as multiple roles. And how to allow him to assign or add roles when the super user creates a profile on custom build admin panel ( am not asking for djago admin, am asking for custom own built admin panels) -
How I get the time zone of logged user by using Django?
I want to manage(such as Change the default language) the country region details of in my Django website. Does anyone have a best way to do that? -
Prefetch_related with filter for m2m
I'm trying to build a queryset to find candidates who has apply for a job_type, knows some languages and he wants to work in some zones. I'm able to select candidates based on job_type_ an d languages but my query doesn't filter by zones. : { "jobtype_id": 15, "languages": [21,83], "zones": [1,2,4] } This is my queryset: candidates = Candidate.objects.all().prefetch_related('job_types', 'languages').filter( job_types__id=job_type_id, languages__id__in=filter_languages).prefetch_related( Prefetch('job_types__candidate_job_type_zone', queryset=CandidateJobTypeZone.objects.all().filter(zone_id__in=filter_zones)), ) This is the SQL generated (i want an inner join to candidate_job_type_zone table and filter by zone id): SELECT `candidates`.`name`, `candidates`.`firstname`, `candidates`.`lastname`, `candidates`.`phone_number`, `candidates`.`secondary_phone_number`, `candidates`.`profession`, `candidates`.`own_car`, `candidates`.`driver_licence`, `candidates`.`location`, `candidates`.`document_type`, `candidates`.`document_id`, `candidates`.`work_permit`, `candidates`.`prefer_language`, `candidates`.`is_promoted`, `candidates`.`last_promoted_payment_date`, `candidates`.`is_active_job_search`, `candidates`.`last_active_job_search_date`, `candidates`.`created_at`, `candidates`.`updated_at`, `candidates`.`extra_data`, `candidates`.`user_id`, `candidates`.`nationality_id` FROM `candidates` INNER JOIN `candidates_jobs_types` ON (`candidates`.`user_id` = `candidates_jobs_types`.`candidate_id`) INNER JOIN `candidates_languages` ON (`candidates`.`user_id` = `candidates_languages`.`candidate_id`) WHERE (`candidates_jobs_types`.`job_type_id` = 15 AND `candidates_languages`.`language_id` IN (21, 83)) These are may models: class Candidate(models.Model): ... # relations user = models.OneToOneField( User, on_delete=models.CASCADE, null=False, verbose_name="Usuario relacionado", primary_key=True) job_types = models.ManyToManyField('JobType', through="CandidateJobType") languages = models.ManyToManyField(Language, through="CandidateLanguage") class CandidateJobType(models.Model): candidate = models.ForeignKey( Candidate, verbose_name="Candidato", on_delete=models.CASCADE) job_type = models.ForeignKey( JobType, verbose_name="Puesto de trabajo", on_delete=models.CASCADE, related_name='job_types') extra_data = models.JSONField(verbose_name="Datos extras", null=True) zones = models.ManyToManyField(Zones, through="CandidateJobTypeZone") is_active = models.BooleanField(verbose_name="Is active", null=True, default=True) class Meta: db_table = "candidates_jobs_types" unique_together = ('candidate', 'job_type') class … -
Multiple FeaturedPost on HomePage Using Wagtail
I haven't seen any question like this on the site. So hopefully this question will be useful for others in the future. I have a PostPage, EditorialPage, and DocumentPage. Within the models of the three, I added a 'featured' Boolean, so that if toggled in the settings, either Post is featured onto the HomePage. However, in the HomePage/Models, I only was able to get it to work with PostPage. I'm not too keen with query/querysets, but I feel it has something to do with that. I've read the Docs multiple times, but I do not understand how to make this work. Blog/Models.py class PostPage(Page): header_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) featured = models.BooleanField(default=False) highlight = models.BooleanField(default=False) description = models.CharField(max_length=255, blank=True,) body = StreamField(BodyBlock(), blank=True) tags = ClusterTaggableManager(through="blog.PostPageTag", blank=True) post_date = models.DateTimeField( verbose_name="Post date", default=datetime.datetime.today ) content_panels = Page.content_panels + [ ImageChooserPanel("header_image"), FieldPanel("description", classname="full"), InlinePanel("blog_authors", label="author", min_num=1, max_num=4), MultiFieldPanel([ InlinePanel("categories", label="category",), FieldPanel("tags"), ], heading="Meta"), StreamFieldPanel("body"), ] settings_panels = Page.settings_panels + [ FieldPanel("post_date"), MultiFieldPanel([ FieldPanel("featured"), FieldPanel("highlight"), ], heading="Showcase") ] Home/Models.py (Method 1) class HomePage(RoutablePageMixin, Page): def get_context(self, request): featured_post = PostPage.objects.live().public().filter(featured=True) featured_editorial = EditorialPage.objects.live().public().filter(featured=True) feature_document = DocumentPage.objects.live().public().filter(featured=True) featured_select = sorted( chain(featured_post, featured_editorial, feature_document), key=lambda page: page.first_published_at, reverse=True)[0] return featured_select …