Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter __lte __gte strings
I would like to filter models given a user input. For example the user would like to go on a cruise that is 1-5 days long. In the template I have a selector with these values (1-5, 6-9, 10-16, 17+). In the view I create these as kwargs. def create_kwargs(from_date, nights): kwargs = {} got_nights = nights != '-' got_date = False if not from_date else True if got_nights and (not got_date): nights_kwargs(kwargs, nights) if got_nights and got_date: nights_kwargs(kwargs, nights) kwargs['start_months__contains'] = from_date if (not got_nights) and got_date: kwargs['start_months__contains'] = from_date return kwargs def nights_kwargs(kwargs, nights): if '-' in nights: c_min, c_max = nights.split('-') kwargs['cruise_duration__gte'] = c_min kwargs['cruise_duration__lte'] = c_max else: kwargs['cruise_duration__gte'] = '17' Than I feed these kwargs to the filter method: for i, area in enumerate(filter_areas): cruises = GeneralCruise.objects.filter(areas__contains=area, **kwargs) Previously I tried to check equality and it worked: kwargs['cruise_duration'] = '1' My problem is that if I write __lte or __gte it returns all the models even if they are not matching the criteria. I read other questions regarding this and I think this should be working. This is the model: class GeneralCruise(models.Model): company = models.CharField(max_length=255, null=True) ship_name = models.CharField(max_length=255, null=True) ship_img = models.CharField(max_length=255, null=True) cruise_name = … -
What should I change with the static files so they load css files and images in my django project?
I want to load a few css files (and images) in my django project, im linking them in my code and everything seems to look okay, but I think something is either wrong with the path of the static folder, or with my code where im linking it, because whatever I do they're not visible on the website. Please let me know if you have any ideas! Im trying to figure it out all day and it must be one of these small stupid mistakes css in my html code static files in settings.py -
Django RestFramework return just last result after filtered
In my django project i use DjangoRestFramework for expose some API endpoint. Now i am try to expose just the last result of a model after filtered the data. Models: class VarsResults(models.Model): id = models.AutoField(primary_key=True) id_res = models.ForeignKey(Results, related_name="mainres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) base_byte_order = models.CharField(max_length=15) var_hash = models.CharField(max_length=400) serialyzers: class VarsResultsSerializer(serializers.ModelSerializer): id_res = ResultsSerializer(read_only=True) var_id = ModvarSerializer(read_only=True) class Meta: model = VarsResults fields = ['id', 'id_res', 'var_id', 'var_val', 'var_conv', 'var_hash'] views.py class VarResultsListLast(generics.ListAPIView): queryset = VarsResults.objects.using(random.choice(replica_list)).order_by('-id')[:1] serializer_class = VarsResultsSerializer pagination_class = StandardResultsSetPagination # paginator = None filter_backends = [DjangoFilterBackend] filterset_fields = { 'id_res__id': ['exact'], 'id_res__device': ['exact'], 'id_res__unit__id': ['exact'], 'id_res__proj_code': ['exact'], 'var_id__var_group__short_name': ['exact'], 'id_res__read_date': ['gte', 'lte', 'exact', 'gt', 'lt'] } search_fields = ['id_res__id', 'id_res__unit__id', 'id_res__device', 'id_res__proj_code', 'id_res__read_date'] ordering_fields = '__all__' I create my queryset using .order_by('-id')[:1] for have just the last results but it works only if i don't use any filter (return the last result for the whole table), if i try to filter, for example using proj_code or somethin other filter i would to have in return just the last result from the filtered data, but i have: (call for example: http://127.0.0.1:8000/api/results_data_last/?id_res__proj_code=CR00069) AssertionError at /api/results_data_last/ Cannot filter … -
Python - How can I get the largest decimal of two decimals
I have two values of type decimal i.e <class 'decimal.Decimal'> and <class 'decimal.Decimal'> and the numbers are print(type(option.principal.amount), 'and', type(max_monthly_amount.amount)) Outputs 500000.00 and 500000 Getting max of the two values like this option.principal.amount.max(max_monthly_amount.amount) Returns 'decimal.Decimal' object has no attribute 'max_term' -
Django in Docker Container not working with Selenium Grid 4
I recently started trying to containerize a django app. I've been trying to get the tests work for a few days with no luck. I have no experience with Selenium Grid but it seems like the way to work with Django in a docker container, especially if I need to be able to view whats happening. # docker-compose.yml version: "3.9" services: myapp: build: . command: bash -c " npm run build && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./:/myapp env_file: - .env container_name: myapp-container ports: - "8000:8000" networks: mynetwork: ipv4_address: 171.20.0.3 selenium-hub: image: selenium/hub:4.1 container_name: selenium-hub ports: - "4442:4442" - "4443:4443" - "4444:4444" networks: mynetwork: ipv4_address: 171.20.0.4 chrome: image: selenium/node-chrome:4.1 container_name: chrome-worker shm_size: 2gb depends_on: - selenium-hub environment: - SE_EVENT_BUS_HOST=selenium-hub - SE_EVENT_BUS_PUBLISH_PORT=4442 - SE_EVENT_BUS_SUBSCRIBE_PORT=4443 networks: mynetwork: ipv4_address: 171.20.0.8 networks: mynetwork: ipam: config: - subnet: 171.20.0.0/24 gateway: 171.20.0.1 Within my code it should just be a matter of changing context.selenium = webdriver.Chrome(chrome_options=chrome_options) to below: def before_all(context): chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=3840,2160") chrome_options.add_argument("--allow-insecure-localhost") # chrome_options.add_experimental_option("detach", True) # context.selenium = webdriver.Chrome(chrome_options=chrome_options) context.selenium = webdriver.Remote(command_executor='http://localhost:4444', options=chrome_options) context.selenium.implicitly_wait(1) TransactionTestCase.serialized_rollback = True However this results in this error: HOOK-ERROR in before_all: MaxRetryError: HTTPConnectionPool(host='localhost', port=4444): Max retries exceeded with url: /session (Caused … -
AssertionError at /wel/ Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneTyp
I am trying to create an api using django rest framework but facing the above mentioned issue my models.py code from django.db import models class React(models.Model): name=models.CharField(max_length=20) details=models.CharField(max_length=500) and my views.py code from django.shortcuts import render from rest_framework.views import APIView from . models import * from rest_framework.response import Response from . serializer import * class ReactView(APIView): serializer_class = ReactSerializer def get(self,request): for detail in React.objects.all(): detail = [{'name':detail.name,'detail':detail.detail}] return Response(detail) def post(self,request): serializer=ReactSerializer(data=request.data) if serializer.is_valid(raise_exception = True): serializer.save() -
jQuery not reflecting accurate values
I have implemented a like button with jQuery into my django project. Everything is working except the like count is not being properly displayed Example: The user enters the page with the post unliked User then likes the post: API request: User then un likes post: You can see that the likes are being properly sent to the DB but the likes count is backwards. I have spent a ton of time on this but for the life of me I cant figure out why. view: class PostLikeAPIToggle(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, pk=None, format=None): # slug = self.kwargs.get("slug") obj = get_object_or_404(Post, pk=pk) url_ = obj.get_absolute_url() user = self.request.user updated = False liked = False counts=obj.likes.count() if user.is_authenticated: if user in obj.likes.all(): liked = False obj.likes.remove(user) else: liked = True obj.likes.add(user) updated = True data = { "updated": updated, "liked": liked, "likescount": counts } return Response(data) jQuery: <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: … -
Non-pip-installable python modules on Heroku
I am trying to deploy a Django Web-App that, amongst other, implements the IfcOpenShell Python module (http://ifcopenshell.org/python ). Unfortunately, this module is not available through pip install. To use it locally, I just download the files and paste them in my python environment site-packages folder. When I deploy this App on Heroku the IfcOpenShell module is missing of course. Is there a possibility to add it manually to Heroku somehow? -
ValidationError: [u'Enter valid JSON']: Can load DJANGO JSON field in my local machine but not in remote production server
I have a field of type JSONField that basically contains this structure: [{u'date': u'2021-11-24T13:51:47', text': u'todayone'}, {u'date': u'2021-11-24T13:52:38', u'query': u'todaytwo'}, {u'date': u'2021-11-24T13:53:26', u'query': u'todaythree'}] When the field has more than 600 Entries, I can't load it in production but locally I can do it without problems. In production I receive the following error: /venv/local/lib/python2.7/site-packages/django/db/models/query.pyc in __iter__(self) 61 related_populators = get_related_populators(klass_info, select, db) 62 for row in compiler.results_iter(results): ---> 63 obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) 64 if related_populators: 65 for rel_populator in related_populators: /venv/local/lib/python2.7/site-packages/django/db/models/base.pyc in from_db(cls, db, field_names, values) 581 values.reverse() 582 values = [values.pop() if f.attname in field_names else DEFERRED for f in cls._meta.concrete_fields] --> 583 new = cls(*values) 584 new._state.adding = False 585 new._state.db = db /venv/local/lib/python2.7/site-packages/django/db/models/base.pyc in __init__(self, *args, **kwargs) 500 if val is _DEFERRED: 501 continue --> 502 _setattr(self, field.attname, val) 503 else: 504 # Slower, kwargs-ready version. /venv/local/lib/python2.7/site-packages/jsonfield/subclassing.pyc in __set__(self, obj, value) 39 # we can definitively tell if a value has already been deserialized 40 # More: https://github.com/bradjasper/django-jsonfield/issues/33 ---> 41 obj.__dict__[self.field.name] = self.field.pre_init(value, obj) 42 43 /venv/local/lib/python2.7/site-packages/jsonfield/fields.pyc in pre_init(self, value, obj) 78 return json.loads(value, **self.load_kwargs) 79 except ValueError: ---> 80 raise ValidationError(_("Enter valid JSON")) 81 82 return value ValidationError: [u'Enter valid JSON'] Both environments have … -
How to pass values to modal using Django, Bootstrap4
Title, unit price, and qty in Your items field can be loaded with the syntax like {{ cart_item.timetable.movie.title_eng }}. However, when applying the same method to a modal, the value cannot be applied. On the other hand, the value of 'Your total is' can be loaded as {{total}}. How can I fill in the blanks in the Payment modal? {% for cart_item in cart_items %} <tr> <td> <a href="{{ cart_item.timetable.movie.get_absolute_url }}"> <img src="{{ cart_item.timetable.movie.poster.url }}" alt="" class="custom_image"> </a> </td> <td class="text-left receipt"> {{ cart_item.timetable.movie.title_kor }} <br> Title : {{ cart_item.timetable.movie.title_eng }} <br> Unit Price : ${{ cart_item.timetable.ticket_price }} <br> Qty : ${{ cart_item.timetable.ticket_price }} x {{ cart_item.quantity }} </td> <table class="table my_custom_table"> <thread class="my_custom_thread"> <tr> <th> Checkout </th> </tr> </thread> <tbody> <tr> <td> Please review your shopping cart items before proceeding with the order payment. </td> </tr> <tr> <td class="text-left"> Your total is : <strong>${{ total }}</strong> </td> </tr> </tbody> </table> <div class="mx-auto"> <button type="button" class="btn btn-outline-dark my_custom_button" data-toggle="modal" data-target="#myFullsizeModal" data-notifyid="${ cart_item }"> Continue Shopping </button> </div> <!-- Modal --> <div class="modal fade" id="myFullsizeModal" tabindex="-1" role="dialog" aria-labelledby="myFullsizeModalLabel"> <div class="modal-dialog modal-fullsize" role="document"> <div class="modal-content modal-fullsize"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Payment</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div> … -
How to Sum values from different objects in Django?
I want to calculate the workout volume of each user, and then append it so I can use the value in chart.js. This is calculated by multiplying the reps, series, and weight of all exercises in all workouts a user has. I have the following models: class Exercise(models.Model): exercise = models.CharField(max_length=166) series = models.IntegerField(null=True, validators=[RegexValidator(r'^[0-9]*$')]) reps = models.IntegerField(null=True, validators=[RegexValidator(r'^[0-9]*$')]) weight = models.DecimalField(max_digits=5, decimal_places=1, null=True, blank=True) class Workout(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) day = models.CharField(max_length=1, blank=True, null=True, verbose_name="Dias") exercises = models.ManyToManyField(Exercise, blank=True) To try and calculate that workout volume, I used the following in views: data = [] workout = Workout.objects.filter(member=request.user.member) for p in workout: exercise = p.exercises.aggregate(total=Sum(F('reps') * F('series') * F('weight'))).values() for d in exercise: data.append(d) This, in turn, returns the Sum of each single day. So, if a user has 2 workouts, it'll return (example) ["4350.0", "7350.0"] How can I calculate the sum of all days. So, in the case of this example, the final value would be ["11700.0"]. -
Getting KeyError: 'smth' when using validated_data.pop('smth')
I am not able to update user form on Django rest-framework with djoser. Getting KeyyError: "tutor" for validated_data.pop('tutor'), checked some solutions but didn't help Here is what I did so far serializers.py class TutorUserSerializer(serializers.ModelSerializer): class Meta: model = TutorUser fields = [ 'id', 'full_name', 'phone_number', 'web_link', ] class UserCreateSerializer(serializers.ModelSerializer): tutor = TutorUserSerializer() class Meta: model = User fields = [ 'id', 'email', 'is_tutor', 'password', 'tutor', ] extra_kwargs = { 'password': { 'write_only': True, 'style': {'input_type': 'password'} } } def create(self, validated_data): tutor_user_data = validated_data.pop('tutor') user = User( email = validated_data['email'], is_tutor = validated_data['is_tutor'], ) user.set_password(validated_data['password']) user.save() if user.is_tutor: TutorUser.objects.create(tutor_user = user, **tutor_user_data) return user class UserSerializer(serializers.ModelSerializer): tutor = TutorUserSerializer() class Meta: model = User fields = [ 'id', 'email', 'is_tutor', 'tutor' ] def update(self, instance, validated_data): tutor_user_data = validated_data.pop('tutor') tutor_user = instance.tutor tutor_user.full_name = tutor_user_data.get( "full_name", tutor_user.full_name ) tutor_user.phone_number = tutor_user_data.get( "phone_number", tutor_user.phone_number ) UserCreateSerializer works well but update gives me error -
hey i cant count my workers that have ehbo only with 'wel'
hey so i want to filter and count my workers with a ehbo 'wel' i only get 0 ..................................................... views.py def kwalificatietotaal(request, *args, **kwargs): personeel = Personeel.objects.all() kwalificaties = Kwalificaties.objects.filter(ehbo='Wel') total_personeel = personeel.count() ehbo1 = kwalificaties.count() context = {'ehbo1': ehbo1, 'total_personeel': total_personeel} return render(request, 'accounts/kwalificatieTotaal.html', context, *args, **kwargs) model.py class Personeel(models.Model): MONTEURLVL = ( ('Junior monteur', 'Junior monteur'), ('Senior monteur', 'Senior monteur'), ('Hoofd monteur', 'Hoofd monteur'), ('ATB monteur', 'ATB monteur'), ('Mtc', 'Mtc'), ('EBK', 'EBK'), ) objects = None naam = models.CharField(max_length=200, null=True) achternaam = models.CharField(max_length=200, null=True) telefoon = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) personeels_nummer = models.CharField(max_length=200, null=True) lvl = models.CharField(max_length=200, choices=MONTEURLVL) class Kwalificaties (models.Model): objects = None ) E_H_B_O = ( ('Wel', 'Wel'), ('Niet', 'Niet'), ) naam = models.ForeignKey(Personeel, null=True, on_delete=models.SET_NULL) treinen = MultiSelectField(max_length=200, choices=TREIN_SOORTEN) ehbo = MultiSelectField(max_length=200, choices=E_H_B_O) extra = MultiSelectField(max_length=200, choices=EXTRA_KENNIS) def __str__(self): return self.naam what am I doing wrong can plz someone explane me? -
autocomplete Word documents in Django
how to implement filling in a word document in django. The idea is this: we get json with the fields and document type we need, and there are several templates that are stored on the server. and depending on the type of document, fill it out -
How to extract value from Radio Button in views.py in django from request.POST method
I'm trying to get value of a Radio Button from HTML template into views.py file for storing it inside my model. The problem is that it returns "on" always, and I'm using "request.POST['btnradio']" method to get the value/label of my radio button which has name="btnradio" in views.py file. I want it to return that the value/label of that button which is checked. Like if the button with value/label "Foodie" is checked, then it should return "Foodie" so that I can store it in modal. Likewise, if the other one is selected, then it should return "Restaurant". This is my HTML template where I've written a form in which I'm trying to get value from a user signup. <form action="" method="POST" name="signUpForm"> {% csrf_token %} <input type="text" id="uname" name="userName" class="input-box" placeholder="User Name" required> <input type="email" id="uemail" name="userEmail" class="input-box" placeholder="Email" required> <input type="password" id="upass" name="userPass" class="input-box" placeholder="Password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.ucpass.pattern = this.value;" required> <input type="password" id="ucpass" name="userCpass" class="input-box" placeholder="Confirm Password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" required> <div class="radio-btn-div btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" id="btnradio1" class="btn-check" name="btnradio" autocomplete="off" checked> <!-- This part … -
Django Quiz: I want the correct answer to appear on the same page of question
I use the quiz provided here https://github.com/sswapnil2/django-quiz-app and I want the answer with an explanation to appear on the same question page instead of appearing on the next question page. I expect the error is in the view, but I could not fix it. -
Django - Return Two Attributes from a Model
How I return two attributes from a model? Vehicle Model class Vehicle(models.Model): unit = models.CharField(max_length=10, help_text="Unit number for the vehicle") vin = models.CharField(max_length=17, unique=True, validators=[MinLengthValidator(17)], help_text="VIN of the vehicle", primary_key=True) ... def __str__(self): return self.unit Appointment Model class NewAppt(models.Model): ... unit = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, null=True) vin = models.ForeignKey(Vehicle, related_name='VIN', on_delete=models.SET_NULL, null=True) ... def save(self, **kwargs): self.vin = Vehicle.objects.get(unit=self.unit) super().save(**kwargs) Whenever it gets returned, it returns just the unit number in the admin view. If I change self.vin = Vehicle.objects.get(unit=self.unit) to self.vin = self.unit.vin, I get the error: Cannot assign "'1XPTD4EXOCD128815'": "NewAppt.vin" must be a "Vehicle" instance. -
"detail": "Method \"GET\" not allowed." Django rest framework, How to solve it?
I am new to Django restframework I want to register a new student to school but it does not work. I have tried many solutions . what I got is: "detail": "Method "GET" not allowed.". I am not sure if my code in the viewset correct. Can someone help me? In my serializers.py: class StudentSerializer(serializers.Serializer): class Meta: model = Student fields = ['first_name'] class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] def create(self, **validated_data): student_data = validated_data.pop('student') school_instance = School.objects.create(**validated_data) for student_data in student_data: Student.objects.create(school_instance=school_instance, **student_data) return school_instance In my views.py: class SchoolViewSet(mixins.CreateModelMixin,GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() @action(detail=True, methods=['POST']) def school(self, request, *args, **kwargs): school = self.get_object() if serializer.is_valid(): School.create(school=school, name='name', street='street', city='city', student='student') school.save() else: return Response(status=status.HTTP_204_NO_CONTENT) In my url: router.register(r'register', SchoolViewSet) -
Order by is not working properly in django
order_by is not working when using with filter orders = OrderProduct.objects.filter(status__in=['Delivered', 'Canceled']).order_by('-updated_at') I am expecting output based on the last updated order -
reportlab use for loop to create multiple tables
I need through a for loop to create more tables, I think it works but I need to change the various coordinates, how can I do? 2) Is it possible to change the width of a single row of a table? or in any case bring its text-align to the left but which starts from where the table starts? def testPdfView(request, id): #dati init scheda = get_object_or_404(Schede, pk = id) filename = 'media/pdf/' + scheda.nome_scheda + '.pdf' titolo = scheda.utente.username + ' - ' + scheda.nome_scheda #creazione file doc = SimpleDocTemplate( filename, pagesize = A4, rightMargin = 10*mm, leftMargin = 10*mm, topMargin = 47*mm, bottomMargin = 10*mm ) #titolo doc.title = titolo #passaggio scheda alla funzione pdfCanvas doc.scheda = scheda #table gruppi gruppi = DatiGruppi.objects.filter(gruppi_scheda = id) for gruppo in gruppi: table = Table([ [str(gruppo).upper()] ], colWidths= 180*mm, repeatRows=1) #table style style = TableStyle([ ('TEXTCOLOR', (0,0),(-1,0), colors.HexColor("#9FFC0D")),# -1 significa l'ultimo elemento ('FONTNAME', (0,0), (0,0), 'bulk_bold'), ('FONTSIZE', (0,0), (0,0), 6*mm), ('BOTTOMPADDING', (0,0), (-1,0), 6*mm), ('LINEBELOW',(0,0),(-1,0), 1, colors.HexColor("#9FFC0D")), ]) table.setStyle(style) #table add to template elems = [] elems.append(table) #create doc.build(elems, onFirstPage = pdfCanvas) -
Django: Get value from html for-loop for views.py
I am stuck with getting the value from a for-loop of an html-page. This is my setup: The user has an input field that uses a autocomplete function. This function uses the shop-Model in Django. After submitting, the product will be added to the Shopping_List-Model in Django. It will be displayed in another div of the page. This is currently working without a problem. Every product is in one line of a table including a button to delete the product from the shopping list. The button as such is working. I tried to print out something when the button is clicked. But I am not able to get the value, meaning the product name, from the table row. It always returns none. With the value I would like to delete the product from the shopping list. Any suggestions are much appreciated! Here is my code: HTML <div> <!--Input field and autocomplete--> <form id="product_add" action="{% url 'shop' %}" method="post"> {% csrf_token %} <input type="text" name="shop_product" id="shop_product"> <!--Code for autocomplete--> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#shop_product").autocomplete({ source: "{% url 'shop' %}", minLength: 2 }); }); </script> <input type="submit" name="button_add" value="Add"> </form> </div> <div> <table> {% for item in items … -
Change FileField to CharField or change file location to S3
I currently have my files saved in my own server using FileField. And I want to make a migration for saving my files in S3. I was thinking in replace the FileField to a CharField keeping the file names and then, add the domain before it, to keep the track of the files. And then I'd migrate to S3. Is there a simpler way to make this in Django? Is it even possible to change a FileField to a CharField and keep the files path as a string? -
How to send weekly scheduled emails in Django
I like to send scheduled emails for my users every Fridays. I'm using Pythonanywhere so I can't use Celery because PA can work with it. I like to use PA's Task function that can't schedule weekly tasks so it should check every day if it is Friday. I started to write a function but I'm not so experienced and stuck. I don't know how to write the function if it does not have any html where I hit a button to trigger the function. I made a weekly_email_mm.py file in my project directory: import datetime from django.core.mail import send_mail from django.shortcuts import render today = datetime.date.today() weekday = today.weekday() def send_mm_email(???): subject = 'Hello' message = 'Hi there' if (weekday == 4): send_mail( subject, message, 'analytics@mypro.hu', ['ruszak.miklos@gmail.com'], fail_silently=False, ) print('Friday, mails sent') else: print('Not Friday') return render(???) Thank you in advance if you can help me out! -
Based View Class - called success_url method but redirect doesn't seem to work
I am using a based view class to update an article in my app named article. I am implementing it just like how UpdateView works however i can't seem to make it redirect it after validating the form. I called success_url method to redirect into the detail view, but it doesn't work. Am I missing something? I set get_absolute_url in models, #models.py class Article(models.Model): def get_absolute_url(self): return reverse('articles:article-detail', kwargs={"id": self.id}) and in urls #urls.py app_name = 'articles' urlpatterns = [ path('<int:id>/edit/', ArticleUpdateView.as_view(), name='article-edit'), path('<int:id>/', ArticleDetailView.as_view(), name='article-detail'), ] and on views: #views.py class ArticleUpdateView(View): template_name = 'articles/article_edit.html' def get_success_url(self): id = self.kwargs.get('id') return reverse('articles:article-detail', kwargs={'id': id}) def get_object(self): id = self.kwargs.get('id') obj = None if id is not None: obj = get_object_or_404(Article, id=id) return obj def get(self, request, id=None, *args, **kwargs): context = {} obj = self.get_object() if obj is not None: form = ArticleModelForm(instance=obj) context['article'] = obj context['form'] = form return render(request, self.template_name, context) def post(self, request, id=None, *args, **kwargs): context = {} obj = self.get_object() if obj is not None: form = ArticleModelForm(request.POST, instance=obj) if form.is_valid(): form.save() context['article'] = obj context['form'] = form return render(request, self.template_name, context) I tried using it on UpdateView class and redirect seems to work … -
Django Rest - retrive data from nested class
In my following output (below), I would like to get the value from rating field. As you can see there are two rates for that car model. The value from rating will be needed to calculate average rate for that model. { "id": 4, "make": "Citroen", "model": "C4", "rates": [ { "id": 6, "rating": 4, "car_id": 4 }, { "id": 7, "rating": 4, "car_id": 4 } ], "avg_rating": 0.0 } Here is my models.py: class Car(models.Model): make = models.CharField(max_length=15) model = models.CharField(max_length=15) avg_rating = models.FloatField(default=0) def __str__(self): # print it when Car instance is needed return self.make class CarRate(models.Model): car_id = models.ForeignKey(Car, related_name='rates', on_delete=models.CASCADE, default=0) rating = models.PositiveIntegerField(default=0)