Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Join and Aggregate in Django REST Framework
I'm quite new to Django and I'm currently stuck on the following problem. I have models as: class City(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) area = models.FloatField() class NoiseData(models.Model): location = models.CharField(max_length=100) city_id = models.ForeignKey(City, on_delete=models.CASCADE) noise_type = models.CharField(max_length=30) I would like to have data aggregations by city in my api in form like: [ { "id": 1, "name": "New York", "count": 198, # this would be count of NoiseData, "count_area_normalized": 0.198 # this would be count of NoiseData / area of City, "noise_type_metadata": "{\"Loud Music/Party\": 167, \"Banging/Pounding\": 21, \"Loud Talking\": 9, \"Loud Television\": 1}", # ideally want a JSON in which I can show count for each noise_type in the city } Thanks a lot in advance! -
Is it possible to edit HTML for Django FileResponse via template or view?
I've an application that has a video that is being served as a fileResponse. It seems that the video is displayed in an html. I would however like to customize the tag. Does anyone know how I can add an HTML-template for a FileResponse? Or add attributes for the video-tag via the view ? -
How to run a model's function with DTL?
I am fairly new to django and I am trying the following: I am making an ordering web app for a nearby business. I am trying to add all the calories in a combo. I have a model "Consumable", this represent the different food and drinks there are. Here is the code for the "Consumable" Model: class Consumable(models.Model): name = models.CharField(max_length=80, unique=True) category = models.ForeignKey(FoodCategory, null=True, on_delete=models.SET_NULL) price= models.FloatField(default=0.00) calories = models.IntegerField(blank=False) image = models.ImageField(upload_to="images/Food/") description = RichTextField(blank=True, max_length=500) restaurant = models.ForeignKey(Place, on_delete=models.CASCADE) added = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name Then, I have a model called "Meal" which has the following code: class Meal(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='images/photos/meals') consumables = models.ManyToManyField(Consumable, related_name="consumable") restaurant = models.ForeignKey(Place, on_delete=models.CASCADE) price = models.FloatField() def add_cals(meal_consumables): total_calories = 0 for x in meal_consumables.values(): global total_calories += float(x.calories) return total_calories I am trying to call this model's function, add_cals from my HTML file using the DTL (Django Template Language). For example, if you have a model stored with the variable x in your view, and it is in the view's context dictionary, you could simply call the model by using <p>{{x}}</p>, for example. And if the model has a variable x1, … -
How to display a dict of lists as values in template
So I have a field in my model called free_times which contains days of the week and some random times. This is an example of it: free_times = {'Saturday': ['10:00:00', '09:00:00'], 'Sunday': ['12:00:00', '11:00:00'], 'Monday': ['14:00:00', '13:00:00'], 'Tuesday': ['16:00:00', '15:00:00'], 'Wednesday': ['16:00:00', '15:00:00', '14:00:00']} How am I supposed to get Saturday's first or all values as a context and display them in my template? I want to display '10:00:00', for instance. -
why link not displaying content after click on the link?
it is displaying content in home.html. but it is not displaying the content(T1.name and T1.address) in index_detail.html after click on T1.name. Django version 4.0.6. The code is below please have a look into it. please solve the issue. Thank you for your time. Settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR=os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d4@4fwcpkk$6a8ylqjmyhp-9%22t^aizetygwkxzw9s_wu5$&2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'g6app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'g6.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py from django.contrib import admin from django.urls import path from g6app.views import V1,V2 urlpatterns = [ path('admin/', admin.site.urls), path("",V1.as_view(),name="v11"), path("index/<int:pk>",V2.as_view(),name="index_detail"), ] admin.py from django.contrib import admin from . models import T1 # Register your models here. admin.site.register(T1) models.py from django.db import models from … -
DRF and PostgreSQL: ArrayField is returned as an array of chars
I have a Contact model with a field like this: #models.py address = ArrayField(models.CharField(max_length=255, null=True), default=list) This stores an array of email addresses. I'm creating an api and wanted this to be returned as an array of email addresses as strings but I get an array of chars instead (as in the screenshot). Can someone hint me what to do? My serializer: class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' Output: -
Rendering average rating on a single product - probably an easy solve, but cannot find the problem
I am trying to show display the average rating for a given single product from every ratings made by users on this single product. Which I managed to do. However my code seems to render all products and relating reviews and not just the specific product. Clearly, I am telling the code, somewhere, to render all products instead of one. But I am not too sure where. I think it's coming form the code in my views.py. Something to specify also, in the same page, I am trying to display: Average review per product (that's what I am working on) All reviews from different user on the specific product (that works) Is it 2. that creates a problem? Should I also make a reference to the product_id in the second line of the views too? (if so, where?) Models class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) class Meta: db_table='Product' def __str__(self): return str(self.name) class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True,on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) rating_1 = models.IntegerField(choices=RATING1,default=0) def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) Views from django.db.models import Avg def Notes (request, product_id): product = Product.objects.get(pk=product_id) data = Product.objects.order_by('name').annotate( avg_rating_1 =Avg('champcomments__rating_1 '), return render(request, 'main/notes.html',{'product':product, 'data':data}) Template {% for ReviewRatingin … -
Best way to handle DecimalField with NaNs in Django 4?
Django issue 33033 says that DecimalField has never supported handling NaNs. However, until recent Django, those were permitted, so I have a database full of them from Django 3.2.13. What's the easiest way to support a DecimalField with NaN in Django now that the official DecimalField prevents them (with an exception)? I could make another custom field that has an extra field saying whether the value is a NaN or not. Seems terribly awkward. -
Blocking INVALID_HOST + Bad Request attempts in AWS
I have a Django app running in Elastic Beanstalk. Every day, I am seeing a ton of seemingly malicious attempts to get into my app. Here are the most common type of events: Invalid HTTP_HOST header: '52.33.#.#'. You may need to add '52.33.#.#' to ALLOWED_HOSTS. or Bad Request: /sitemap.xml (many different URL patterns beyond sitemap.xml) I saw a post here about deploying WAF rules as a potential solution. I would rather go this route if there is a predefined path. Looking for some collective wisdom on how to block this junk traffic. Thanks. -
How can i solve syntax error during making webapp?
im working with django and making webapp now this has occurred def Notes(generic.DetailView): ^ Error invalid syntax Function name:NotesDetaiView -
How to get the selected value from html select with django
I would like to know if it's possible to get the selected value from a select HTML without using a submit input? Because when I hit the submit, the value selected is returned but it reloads the web page and the select goes back to it's intial state. Here is my code to visualize better: views.py def index(request): id_desi = request.POST.get('drop_desi') return render(request, 'index.html', {'designation_liste': df.designation_liste}) index.html <form action="{% url 'DataMat-index' %}" method="POST">{% csrf_token %} <select name="drop_desi"> <option disabled selected value> -- select value -- </option> {% for i in designation_liste %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> <input type="submit" value="valider"> </form> -
Custom Django 'delete' action not firing from admin list view
I have a 'notes' model in my Django app where I've built some custom delete actions: class Note(models.Model): [MODEL FIELDS HERE] def delete(self, *args, **kwargs): [STUFF HEPPENS HERE] super(Note, self).delete() If I click into the individual note from the Django admin and hit the 'Delete' button, the custom delete actions work just fine, but if I check the box next to the note in the list view and choose 'Delete selected notes' from the dropdown, they do not. What am I missing here? -
I can't use Tiny Mce in django properly
My models.py from django.db import models from tinymce.models import HTMLField # Create your models here. class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) content = HTMLField() author = models.CharField(max_length=50) slug = models.CharField(max_length=130) date_and_time = models.DateTimeField(blank=True) def __str__(self): return self.title I got this output using Tinymce I think models.py is use for this question's answer. I hope any devloper answer -
How to log to a new file in every route handler function?
In my flask api, I have a function like this: @app.route('/sample_route') def my_func(): # log something... # doing something... # log the processing results to a new .log file I want to create a new .log file every time a new request comes to my_func function. I've tried some ways but none of them works correctly. Does anyone have an idea? -
django send mail on update password
I have a ChangePasswordView for my User: class ChangePasswordView(PasswordChangeView): form_class = ChangePasswordForm success_url = reverse_lazy('password_success') I've been using the send_mail function to notify Users when they update their information, however, in this case, I'm having some trouble. I added this to my ChangePasswordView: def form_valid(self, form): form.update_password_email() return redirect(self.success_url) And this to my ChangePasswordForm: def update_password_email(self): email = self.cleaned_data.get('email', None) if email and self.is_valid(): send_mail( 'Password changed', 'Message', NOTIFICATION_EMAIL, [self.cleaned_data['email']], fail_silently=True ) But it doesn't work. I go to django's change password page, enter my old password, new password and confirm it, but the logic isn't running. Instead I get redirected to my success_url with no password change and no email notification. Is the issue happening because of my view or my form? And what issue is happening. Also do I need form_valid(): and if self.is_valid(): or is one of those extra? I assume they're doing the same thing. -
heroku logs is giving an error, after uploading it on heroku
enter image description here enter image description here I uploaded a django project in heroku, but getting an application error, am i missing something in procfile?? , what changes should I make -
How to manage two user roles in flutter?
I am building an MVP for a two-user type flutter mobile app,(eg: Like a delivery app with a driver and a rider). Since is an MVP is it efficient to keep both user types in one application and switch app states depending on the type of the user and their role? -
Django Unique Constraint for Three fields Not working
I have the following model. class ModelAnswer(BaseModel): questions = models.ForeignKey( to=ModelQuestions, on_delete=models.CASCADE ) answer = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.questions} - by {self.user}' class Meta: constraints = [ models.UniqueConstraint(fields=['created_at','user', 'questions' ], name='unique questions per user') ] plan is to have one answer per question by user per day ie on next day new answer can be added for new question but only once. I tried adding unique constraint but it does not work My question model is as class ModelQuestions(BaseModel): MODEL_CATEGORY_CHOICES = ( ('Circumstances', 'Circumstances'), ('Thoughts', 'Thoughts'), ('Feelings', 'Feelings'), ('Action', 'Action'), ('Result', 'Result')) model_subcategory = models.CharField(max_length=50, choices=MODEL_CATEGORY_CHOICES) questions = models.CharField(max_length=200) def __str__(self): return self.model_subcategory How do I allow the unique answers to questions by users each day? Although I tried filtering method with exists() soln but I want to implement with unique constraint. -
How to solve users' lazy time input method in python DateTimeField? [closed]
In my Django application, there is a field that accepts User/ Admin's input time. The expect outcomes would be: Input 7 indicates 7:00 Input 715, then it would be recognized at 7:15. The same 2011 -->20:11 015 -->0015 Any comments? P.S. I don't have code because I would like to know the apprach first. Thank you! -
why I receive 'Duplicate entry' error in django testing?
I had some unit tests in Django that worked fine. I added some lines to send queries to MySQL. After that every unit test that includes authentication is raising exceptions, even I remove those lines. what is the problem? Django error report: _mysql.connection.query(self, query) django.db.utils.IntegrityError: (1062, "Duplicate entry 'myuser' for key 'auth_user.username'") My Tests: class AnnotationPage(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='myuser', password='12345678') def test_labeling(self): ajaxData = {'testing': 'True', 'direction': 'forward'} request = self.factory.post('/annotation', ajaxData) request.user = self.user response = AnnotationView(request) assert response.content == b'{"image": "image.png", "id": 1}' My Tests with queries: class AnnotationPage(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='myuser', password='12345678') self.cursor = connection.cursor() query = "TRUNCATE TABLE homepage_imagelabel" self.cursor.execute(query) def test_labeling(self): self.cursor = connection.cursor() query = "INSERT INTO homepage_imagelabel (ImageFile) VALUES ('image.png')" self.cursor.execute(query) ajaxData = {'testing': 'True', 'direction': 'forward'} request = self.factory.post('/annotation', ajaxData) request.user = self.user response = AnnotationView(request) assert response.content == b'{"image": "image.png", "id": 1}' -
Why does Stripe's webhook send the same event twice at about the same time?
I'm building a payment system using Stripe. After making a payment with Stripe, we use the 'invoice.paid' event to authorize the user. I've tried it several times and noticed that the webhook sends the same event twice at about the same time. This reproduced the same problem both when I made a payment in test mode from a web page and when I ran the following command from the terminal. stripe events resend evt_xxxxxxxxxxxxxxx However, this is a phenomenon confirmed only in the development environment by executing the following command. stripe listen --forward-to http://0.0.0.0:8080/webhook/ I haven't tried it in production yet. I get the same event twice, so I saved the event ID and set it to return 200 status when I received the second event. def webhook_view (request): payload = json.loads(request.body) event_id = payload.get('id') event_type = payload.get('type','') logger.info (f'type: {event_type} event_id: {event_id}') if Event.objects.filter (id = event_id).exists (): logger.info (f'{event_id} already exists') return HttpResponse (status = 200) Event (id = event_id, created_at = timezone.now(), data = json.dumps(payload)).save() However, the interval between the two requests is so short that the second event passes the check. [2022-07-24 22:28:53,677] [webhook_view: 60] type: invoice.paid event_id: evt_1LP4n0BB5Q5Dr2x7QDEfWFak [2022-07-24 22:28:53,682] [webhook_view: 60] type: invoice.paid event_id: … -
Django | Can't render out user specific content
I am trying to render out model objects that are unique to a user. All methods I've found haven't worked and I've been trying to figure this out for a while now. What is supposed to happen is that you can see the jobs you've posted in the manage-jobs.html template. Also I've removed all of my failed attempts to render out user specific content, it's not that I haven't tried to do this by myself. Thanks. models.py class Job(models.Model): company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer") description = models.TextField(null=True) role = models.CharField(max_length=25) area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="") contact_email = models.EmailField(verbose_name='Contact Email', max_length=60, default='') created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Account, default='', null=True, on_delete=models.CASCADE) def __str__(self): return self.company class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) name = models.CharField(max_length=45, unique=False) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employee = models.BooleanField(default=True, verbose_name='Are you using FilmLink as an employee?') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'is_employee'] objects = MyAccountManager() class Meta: permissions = [ ("post_jobs", "Can post jobs"), ] def __str__(self): return self.name def has_perm(self, perm, obj=None): return True def has_perms(self, perm): return True def has_module_perms(self, app_label): return True @property … -
How to access External url link in django
I want to access External web link On my django website,but i dont access it so how to access it on button click action. -
django could not be resolved from source Pylance
I just begun performing crud operations using Django. I have installed Django using pip install django. I then set the environment: venv\Scripts\activate but when i run python3 manage.py makemigrations, i get "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?". Any help kindly -
Why is my django web-app login form not working?
I've tried to add login form to my tasks web-app, but something goes wrong and I can't login to my created admin user. After click on the login button page just clearing up and my url changes to that. I have no idea how to fix it, help me please. urls.py urlpatterns = [ path('', TaskList.as_view(), name='tasks'), path('login/', CustomLoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(next_page='login'), name='logout'), path('task/<int:pk>', TaskDetail.as_view(), name='task'), path('task-create/', TaskCreate.as_view(), name='task-create'), path('task-edit/<int:pk>', TaskUpdate.as_view(), name='task-edit'), path('task-delete/<int:pk>', TaskDelete.as_view(), name='task-delete'), ] views.py class CustomLoginView(LoginView): template_name = 'base/login.html' fields = '__all__' redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('tasks') login.html <h1>Login</h1> <form metrhod="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form>