Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail Pagination issue with Waypoint Infinite Scroll
I've implemented Waypoint Infinite Scroll just fine on a regular Page model for art gallery items. Those items can be added to a shop with a checkbox. I then use a Shop page to filter the gallery items that are marked as on sale. For some reason, when the infinite scroll feature seems to trigger just fine on the shop page but no new items are rendered. I get a 200 response from the server and no errors are logged to the console: [12/Dec/2020 11:40:46] "GET /shop/?page=2 HTTP/1.1" 200 26 The page it works with: class Gallery(Page): intro = RichTextField(blank=True, help_text="Text for the top of your gallery page. (Optional - recommended to leave empty for a more simplistic look.)") content_panels = Page.content_panels + [FieldPanel('intro', classname="full")] subpage_types = ['InstallationPage'] # parent_page_types = [] def get_context(self, request): context = super().get_context(request) filtered_medium = request.GET.get('medium', None) if filtered_medium: context['filtered'] = True mediums = InstallationMedium.objects.filter(name=filtered_medium) installations = InstallationPage.objects.child_of(self).order_by('-date').live().filter(mediums__in=mediums) else: mediums = InstallationMedium.objects.filter(installationpage__in=InstallationPage.objects.all()).distinct() installations = InstallationPage.objects.child_of(self).order_by('-date').live() paginator = Paginator(installations, 12) page = request.GET.get('page') try: pagin = paginator.get_page(page) except PageNotAnInteger: pagin = paginator.get_page(1) context['installations'] = pagin context['mediums'] = mediums return context Shop page where it doesn't work: class Shop(RoutablePageMixin, Page): ajax_template = "shop/shop_item_ajax.html" def get_context(self, request): context … -
How to render image which is in other folder and not in static folder in Django?
My matplotlib analysis images are saving in other folder instead of static folder "images". I need to give a path to that folder where my analysis images are being saved. this is the folder where my analysis images are saving. -
How to organize a multiple users roles project with Django?
i am a doubt regarding the organization of my code. I am starting a new project with Django 3.1 that should work with different users types. First step was extending the User model with the AbstractUser (from django.contrib.auth.models import AbstractUser), adding a new field called role: class User(AbstractUser): ADMINISTRATOR = 1 AGENT = 2 EDITOR = 3 REPRESENTATIVE = 4 ROLES = [ (ADMINISTRATOR, _('Amministratore')), (AGENT, _('Agente')), (EDITOR, _('Editore')), (REPRESENTATIVE, _('Commerciale')) ] role = models.PositiveSmallIntegerField( choices=ROLES, default=AGENT, ) ... As you can see i have (for the moment) 4 roles to manage. Each role has its own control panel where can manage its things. With control panel i am not referring to the Admin control panel, I need to create 4 backends where the users can manage their things. For this reason i thought to create 4 applications: administrator agent company representative and a fifth called backend that is basically the theme i would like to use as base for the users panels. (Being a theme it it only has templates/ templatestags/ and static/) Then, I am creating an app for each thing to manage, with "thing" i mean something like Invoice management, Quote management, Article management and so on... … -
How to query another Django model in template view based on the relation to another model
I have these models class Protocol(models.Model): name = models.CharField(max_length=200) class Description(models.Model): name = models.CharField(max_length=200) protocol = models.ForeignKey(Protocol) class Trait(models.Model): desc = models.CharField(max_length=200) protocol = models.ForeignKey(Protocol) class State(models.Model): desc = models.CharField(max_length=200) trait = models.ForeignKey(Trait) class Expression(models.Model): state = models.ForeignKey(State) description = models.ForeignKey(Description) So a Protocol (e.g. protocol "A") consist of a certain amount of Traits (e.g. height, weight, color). Each Trait can have multiple States (e.g. low, medium, high). Then, a Description is a collection of Expressions related to a specific Protocol. For example Description #1 is made with Protocol "A" and consist of two Expressions: height -> low, weight -> high; but Trait color is not specified. Basically, what i want to do is display in a template view all the Traits linked to the specific Protocol of the selected Description, and then the corresponding Expression which can also be empty for some Trait. Like this: | Trait | Expression | |--------+------------| | height | | | weight | high | | color | blue | Using the shell i can easily return what i need # Select a Description desc = Description.objects.first() # Get the protocol protocol = desc.protocol # Get all traits in the selected protocol all_traits = … -
Django wait notify mechanism for webhooks
I have the below function which calls an API: def verify(request): if request.method=='POST': url=some_url data={some data} r=requests.post(url, data=json.dumps(data)) else: return render(request,'users/verify.html') Now I get a webhook callback on an endpoint which is handled by another view function: @csrf_exempt def onFetchMode(request): response=json.loads(request.body) Now how do I notify my initial function about the result of my webhook so that I can proceed with the flow of my application? -
Letsencrypt SSL certificate on staging and production servers
Suppose my domain is example.com being managed by AWS Route53. I have an EC2 instance serving a Wordpress site (production) at www.example.com and example.com. I also have a staging server for a Django app at development.example.com. Once I have done my testing for the Django app, I will be taking down the Wordpress site and replace it with my Django site. In the end, I will have one production server for Django and another for internal testing on the staging server. Will I need a separate LetsEncrpyt certificates for the two servers? I don't want to bring down my current Wordpress site as my app is not really ready yet. -
How to make Direct Message with django
Please be generous in finding my rude expressions, if any . I don't mean such . It's simply because I'm poor at English . I want to make DM. It's like Twitter. It doesn't have to be rial time. but, I don't know how communicate only two people. Please tell me what I need, I want sample. -
How to update __str__ and slug everytime after Django's model update?
I have created this model in Django which also saves date and slug. But even if I am making these changes again the str and the slug still remains the same and not updating as per the new data. How to fix this ? class EntranceExamination(models.Model): course = models.CharField(max_length=100, blank=True, default='') year = models.PositiveIntegerField(choices=year_choices(),default=current_year(), validators=[MinValueValidator(1984), max_value_current_year]) month = models.PositiveIntegerField(choices=month_choices(),validators=[MinValueValidator(1), MaxValueValidator(12)]) day = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(31)]) start_time = models.TimeField(blank=True) end_time = models.TimeField(blank=True) slug = models.SlugField(editable=False,max_length=100) class Meta: ordering = ['month'] def __str__(self): return f"{self.course}'s exam on {self.slug}" def save(self): if not self.slug: self.slug = f'{self.day}-{self.month}-{self.year}' super(EntranceExamination, self).save() -
400 (Bad Request) when I try to upload images to AWS S3 from browser
I've been struggling with this for weeks now. I am trying to upload images to AWS S3 directly from the browser using boto3's generate_presigned_post(). The server side code seems to be working well, I do get a signed URL but when I try to upload using javascript I get a 400 bad request error. Server code: @csrf_protect def file_upload_view(request): if request.method == 'POST': file_names = request.POST.getlist('img_names') #extracts a list of all file names for files selected by the user. dataList = [] session = boto3.Session() #create an s3 object for uploads. s3 = session.client( 's3', region_name=settings.AWS_S3_REGION_NAME, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, config = Config(signature_version = 's3v4') ) print(settings.AWS_ACCESS_KEY_ID) S3BUCKET = settings.AWS_STORAGE_BUCKET_NAME for fileName in file_names: fname = randomString(30) fname = "media/Ad_images/{}.webp".format(fname) presigned_post = s3.generate_presigned_post( Bucket=S3BUCKET, Key= fileName, Fields={"acl": "public-read", "Content-Type": 'image/jpg'}, Conditions=[ {"acl": "public-read"}, {"Content-Type": 'image/jpg'}, ["content-length-range", 2, 5] ], ExpiresIn=3600 ) dataList.append( { 'original_fname': fileName, 'data': presigned_post, 'url': 'https://{}.s3.eu-west-2.amazonaws.com/{}'.format(settings.AWS_STORAGE_BUCKET_NAME, fname) } ) return JsonResponse(dataList, safe=False) Javascript code (Client-side): async function upload(input) { var form = document.querySelector("form#imgsForm"); var form_data = new FormData(form); var fdata = new FormData(); images = $("#adImgs")[0].files; emptyDisplayDivs = $('*[data-loaded="false"]'); if (images.length > 10 || images.length > emptyDisplayDivs.length) { alert( "Only 10 pictures are allowed. You have selected more than … -
why does JSON dump doesn't work in my code?
I'm trying to put python objects into a JSON file by getting the API from one of the sites but somehow when I run the code nothing has been put in the JSON file. API is working well, as well when I print out the code by json.load I get the output but I have no idea why does dump doesn't work. here is my code: from django.shortcuts import render import requests import json import datetime import re def index(request): now = datetime.datetime.now() format = "{}-{}-{}".format(now.year, now.month, now.day) source = [] author = [] title = [] date = [] url = "http://newsapi.org/v2/everything" params = { 'q': 'bitcoin', 'from': format, 'sortBy': 'publishedAt', 'apiKey': '1186d3b0ccf24e6a91ab9816de603b90' } response = requests.request("GET", url, params=params) for news in response.json()['articles']: matching = re.match("\d+-\d+-\d+", news['publishedAt']) if format == matching.group(): source.append(news['source']) author.append(news['author']) title.append(news['title']) date.append(news['publishedAt']) data = \ { 'source': source, 'author': author, 'title': title, 'date': date } with open('data.json', "a+") as fp: x = json.dump(data, fp, indent=4) return render(request, 'news/news.html', {'response': response}) -
How do I render a form multiple times and allow a single choice?
I have a quiz app and I have a choices model that contains a free text box that allows the user to type in their answer and an is_answer boolean. I want to be able to render a form that has N choices and to allow the user to specify which of the choices is the answer as a radio box. This is my choices form class ChoiceAddForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text', "is_answer"] widgets = { 'choice_text': forms.TextInput(attrs={'class': 'form-control', }) } I am currently only able to display one instance of the form and am unsure how to allow multiple copies of the form as part of a radio button group. Any help/insight would be appreciated :) -
how to verify and send otp in single foem using django
class RegistrationForm(forms.Form): otp = forms.CharField(max_length=4,min_length=4,required=True,widget=forms.TextInput(attrs={'type':'number','class': 'form-control'}) ) about_company = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': "About Company"}, )) address = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control','placeholder': "Address"}, )) #industry = forms.ModelChoiceField(label="Industry",queryset=Industry.objects.filter(is_deleted=False, is_active=True, counter__gte=3),required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Select Industry"}))#neha gst gstin_no = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'True', 'placeholder': "Enter GST Number",'size': '10'}, )) company_type = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Company_type"}, )) contact_person_name = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Contact Person Name"}, )) company = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Company"}, )) email = forms.EmailField(required=True, widget=forms.EmailInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Email"}, )) designation = forms.CharField(max_length=255,widget=forms.TextInput(attrs={'class': 'form-control','placeholder': "Designation"}) ) industry = forms.ModelChoiceField(label="Select location", queryset=Industry.objects.filter(is_deleted=False, is_active=True, ).order_by("name"), required=True, widget=forms.Select(attrs={'class': 'form-control select2','placeholder': "Select Industry"},)) #location = forms.ChoiceField(required=True, choices=[('', 'Select City (First Select State)')], #widget=forms.Select(attrs={'class': 'form-control'})) #state = forms.ChoiceField(required=True, choices=[('', 'Select State')] + [(i.id, unicode(i.name)) for i in #State.objects.filter(is_active=True, #is_deleted=False)], #widget=forms.Select(attrs={'class': 'form-control'})) contact_number = forms.CharField(required=True, widget=forms.TextInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Mobile"}, )) password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Password"}, )) confirm_password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={'class': 'form-control', 'required': 'required', 'placeholder': "Confirm password"}, )) #registering_as = forms.ChoiceField(required=True, choices=corporate_choices, #widget=forms.Select(attrs={'class': 'form-control'})) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) #self.fields['location'].empty_label = "Select City" #self.fields['state'].empty_label = "Select State" def clean(self): try: del self._errors['location'] … -
Import "users" could not be resolved Pylance(reportMissingImports)
I wanted to import my views.py file from my app "users" ind the urls.py of the project. However, I'm getting an error that the "Import "users" could not be resolved". Picture of the problem The urls.py file: from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from users import views as user_views # Why is there an error? urlpatterns = [ # Admin Page path('admin/', admin.site.urls), # Homepage path('', include('blog.urls')), path('register/', user_views.register, name = 'register'), path('profile/', user_views.profile, name = 'profile'), path('login/', auth_views.LoginView.as_view(template_name = 'users/login.html'), name = 'login'), path('logout/', auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name = 'logout'), ] The app is also in "INSTALLED_APPS" in the settings.py file: INSTALLED_APPS = [ 'crispy_forms', 'users.apps.UsersConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Folder structure This is probably an easy to solve problem, however I'm fairly new to Django and don't really understand why it says this is an error. In a similar project everything works fine. No error in a similar project, where I did everything the same way as far as I remember. -
DRF serialize through related models data
I've got a problem with DRF serialization. My main goal is to create an instance which has a related field but instead of providing the related models id i want to use it's other unique field. At the same time when I will serialize my model to present it (not create) i would like to get the default related fields value. Here's an example class Comment(models.Model): description = models.TextField() creator = models.ForeignKey(User, ...) x = Creator.objects.get(pk=1) print(x.unique_field) > 'some data' client.post('comment-detail', data={ 'description': 'some description', 'creator_unique_field': 'some data' }) # this should create a comment while using some unique creators field # which is not pk or id print(client.get('comment-detail', data={'pk':1})) { 'description' 'some description', 'creator': 1, } I don't know If i should change models Serializer of ViewSet's create() and retrieve(). Im starting with DRF and can't get my head around it -
ModuleNotFoundError: No module named 'django' in django project
i have anaconda python 3.7 installed on my system. i am creating a django project called learning log in a virtual environment(active at the time when problem appeared) in G drive on my computer. i have defined and migrated the entry model but when i try to register entry with the admin site through file admin.py in the project folder with following code ... from django.contrib import admin from models import Topic Register your models here admin.site.register(Topic) ... and try to run it in my spyder editor it shows -- enter code hereModuleNotFoundError: No module named 'django' -
django-background-tasks management command not running on AWS elasticbeanstalk
Greetings fellow programmers, I am currently using django-background-tasks(https://django-background-tasks.readthedocs.io/en/latest/) to run some background tasks on AWS elasticbeanstalk. I initially use this command in the main .config container commands but I get timeout error in deployment because this management command will never finish(it continues to run on). Now, I am trying using the approach suggested for running cron job on elasticbeanstalk(https://aws.amazon.com/premiumsupport/knowledge-center/cron-job-elastic-beanstalk/). Please take a look at my code, it is not running the command. what is wrong pls? I just need the command python manage.py process_tasks to keep running on. This is working properly on my local machine since i can easily open another terminal to fire up the python manage.py process_tasks command files: "/etc/cron.d/process_tasks_cron": mode: "000644" owner: root group: root content: | * * * * * root /usr/local/bin/99_process_tasks.sh "/usr/local/bin/99_process_tasks.sh": mode: "000755" owner: root group: root content: | #!/bin/bash date > /tmp/date # Your actual script content source /var/app/venv/*/bin/activate python manage.py process_tasks commands: remove_old_cron: command: "rm -f /etc/cron.d/*.bak" -
How do i deploy Django application on 3 tier server architecture ? UI , APP, DB server. already have 2tier app running
I have hosted Django application server 2 tier architecture APP & DB server. I need to deploy Django application on 3 tier architecture, UI-APP-DB server. Please help how to do it ? -
How can I stop post method to run by default in Django class based view
I've noticed that both the GET method and the POST method in running. I wanted to run only the GET method when I'm not performing any POST request to that URL. Class Profile(View): template_name = 'profile.html' def get(self, request): # some code... return render(request, self.template_name, context_dict) def post(self, request): # some code... return render(request, self.template_name, context_dict) I don't want to run the POST method if I'm not performing any POST request. I'm new to django. So sorry if it is a dumb question. -
How to set connection-timeout in django channel?
Django channels disconnect the client if it doesn't respond for few seconds. But I can't find where to set that time limit. i checked this issue. It says it will be configurable.But I can't find where to set that limit. thank you -
sending a safe html with django emailmessage
Good day, I'm trying to send a html in django email, pls what more can I added to the code. the email sending is functioning well but it still shows the html tags. from celery import task from django.template.loader import render_to_string, get_template from django.core.mail import EmailMessage from orders.models import Order @task def payment_completed(order_id): order = Order.objects.get(id=order_id) subject = f'Testing html sending' message = render_to_string('orders/order/pdf.html', {'order':order}) email = EmailMessage( subject, message, 'youremai@gmail.com', [order.email, 'youremai@gmail.com'] ) email.content_subtype = 'html' email.send() I've tried render_to_string and get_template same result -
How to increment a serial number in Django model with order by created_at
I'm developing a hospital project! People can apply online appointment for a specific doctor and the people will get a serial number once done the process of online appointment. Here is my model: class Appointment(models.Model): doctor = models.ForeignKey( DoctApp, on_delete=models.CASCADE, related_name="appointments") fee = models.IntegerField(default=1000, validators=[ MaxValueValidator(2000)]) name = models.CharField(max_length=220) phone = models.CharField(max_length=12, default="01700000000") age = models.IntegerField(validators=[MaxValueValidator(200)]) gender = models.CharField(max_length=10, choices=gen_choises) address = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) pat_pic_date = models.DateField() serial_number = models.IntegerField() def __str__(self) -> str: return f"""ID: {self.doctor.id} - {self.doctor.name} - Pat Name: {self.name}""" Can you consider to share the auto-increment fields system to get serial the number fields? -
foreign key serialization drf
i created a model named 'Post'. here is the code: class Post(models.Model): body = models.TextField(max_length=10000) date = models.DateTimeField(default=datetime.now, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-date'] i want to get all objects of Post model with users firstname and lastname. in views.py: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def allPost(request): allpost = Post.objects.all() serializer = PostSerializers(allpost, many=True) return Response(serializer.data) in serialisers.py: class UserSerializers(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class PostSerializers(serializers.ModelSerializer): user = serializers.RelatedField(many=True,source='user.username') class Meta: model = Post fields = ('body','date','user') -
django mongoDB insert dynamic keys
how to Insert Dynamic keys in django mongodb . settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'seartzDB' } } model.py class DynamicForm(models.Model): name = models.CharField(max_length=250) email = models.EmailField(max_length=250) ... view.py @api_view(['POST', ]) def create_form_view(request): DynamicForm(**request.data).save() return Response({'message': "Successfully Created"}, status=200) urls.py urlpatterns = [path('create/', create_form_view, name="create_form"),] I am using Donjo for mongodb. and Ihave create a model and want to insert multiple undefined fields in DB collection. right now i just use simply DynamicForm(**request.data).save() for insert query. but this query not able to insert undefined fields. -
Define filter parameters dynamically in django queryset
Suppose we have such a model: class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) Can we put x as a variable inside the filter so that we can have different querysets by giving different args when calling the get_queryset function? def get_queryset(x, y): queryset = Membership.objects.filter(x=y) return queryset -
Django: Sum of regrouped items on template
Provided our models are: Project Payment (foreign key to Project) View is a ListView for Payment on template {% regroup payments by project as project_list %} {% for project in project_list %} {{project}} {{<-- HOW TO OUTPUT THE SUM OF PAYMENTS FOR EACH PROJECT -->}} {% for payment in project.list %} {{payment}} {% endfor %} {% endfor %} How to output the sum of payments for each project? I can do Payment.objects.filter(payer=self.request.user).order_by('-date_created').annotate(total_per_project=Sum('project__donation__amount')) but total_per_project can be used only in the second for loop as {{payment.total_per_project}} while I need to have it in the first one, i.e. {{project.total_per_project}}