Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding Context to Class Based View Django Project
I have a problem with showing a queryset of a specific model in my Gym project. I have tried many different query's but none is working the models: class Workout(models.Model): name = models.CharField(max_length = 30,blank=True, null=True) class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True) name = models.CharField(max_length = 30, blank=True, null=True) class Breakdown(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='excercise',blank=True, null=True) repetitions = models.IntegerField() I am trying to showing the repetitions in the Breakdown model which has a ForeignKey relation with Exercise which has a ForeignKey relation with Workout views.py class home(ListView): model = Workout template_name = 'my_gym/home.html' context_object_name = 'workouts' class workout_details(ListView): model = Exercise template_name = 'my_gym/start_workout.html' context_object_name = 'exercises' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['breakdown'] = Exercise.objects.filter(breakdown=self.breakdown) return context urls.py urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), ] template: {% for e in exercises %} {{ e.name }} {{ breakdown.repetitions }} {% endfor %} My question what is my mistake here that is either getting me an error or not showing the required data set. my objective is the choose from the home page a Workout from list and next page to be the list of exercises with the repitions related to it. -
which architecture is good for my mobile Chat app in this situation?
I am developing an android app connecting to django backend. My django server in AWS already has own mysql database. (firebase is used for sns authentication) Now I have to add chat functions to this app. It includes group chatting but probably many users may use 1:1 chatting. My question is which architecture is good for mobile Chat app? Options I am thinking now .. Chat messages are stored in mysql database in AWS, and server notify message by only using FCM(Firebase cloud messaging). All text, image or voice urls would be in payload for FCM. A user can only log in on one device at a time. (If this option has no critical performance issue, I think it is a simple way, because I already have backend with database, and I don’t need to care whether user’s Mobile App is in foreground or background. If App needs to show messages when chatting room(channel) is mounted on screed, otherwise just uses notification tray) Use Firebase Realtime database only for chatting functions. It is real time, but I need to create an additional DB in Firebase, and I am not sure how to handle message when app is in background. Chat … -
Put multiple divs on same line using CSS
I'm currently working with Django, and i'm doing a view, where multiple objects from a list are displayed. Right now, each of those objects is on an own line. But i want to have e.g. 2 on one line, so the list is less long on the page. This is my Code so far: html: {% for plant in plants %} <div class="plant"> <img src="{{plant.icon}}"> <div> <label>{{plant.common_name}}</label> <input type="number" name="percentage"/> </div> </div> {% endfor %} CSS: .plant_beet_form { width: 100%; margin: 0 auto; font-size: 3rem; } .plant div { width: 70%; margin: 0 auto; } .plant input{ margin: 0 auto; width: 100%; font-size: 2.5rem; } .plant img { width: 10rem; height: 10rem; margin-bottom: 1rem; } .plant { width: 30%; margin: 0 auto; margin-bottom: 2rem; } I already tried using display:grid and grid-template-rows: 1fr 1fr, but this didn't work either. Any idea? Thank you -
Is there a way I can follow to add my other django app from my other project to my new project? [duplicate]
Please I need a help on how to attach my other app with my new django app. -
How to fix 'workout_details' object has no attribute '_state' Error
I have a problem with showing a queryset of a specific model in my Gym project. Here is the models: class Workout(models.Model): name = models.CharField(max_length = 30,blank=True, null=True) class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True) name = models.CharField(max_length = 30, blank=True, null=True) class Breakdown(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='excercise',blank=True, null=True) repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) I am trying to showing the Breakdown details of every Exercise, but I got this error after several trials. Here is the urls: urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), Here is the views: class home(ListView): model = Workout template_name = 'my_gym/home.html' context_object_name = 'workouts' class workout_details(DetailView): model = Exercise.workout template_name = 'my_gym/start_workout.html' context_object_name = 'exercises' # class workout_details(DetailView): # model = Breakdown # template_name = 'my_gym/start_workout.html' # context_object_name = 'breakdown' Here is the template: {% for excercise in excercises %} {{excercise.name}} {% for b in breakdown %} {{b.repetitions}} {% endfor %} {% endfor %} My question what is my mistake here that is either getting me an error or not showing the required data set. my objective is the choose from the home page a Workout from list and next page to be the list of exercises with the repitions related to … -
Table Buttons to Submit Changelist Form in Django
I currently have the following admin page with a set list_editable fields in my ActivityLogAdmin model. When I click "Save" on the bottom of the admin page, the request.POST data gets submitted to my form. I have the following method under my ActivityLogAdmin class: def get_changelist_form(self, request, **kwargs): return ActivityLogChangeListForm However, I'm trying to add one custom button for each entry in my change list, so when I click it, the POST data should also be passed to a view so I can handle that data. However, I can't seem to pass this request.POST data of when I click the button to the view. Here's my attempt: def approve(self, obj): url = reverse('admin:activity_log_approve', args=[str(obj.id)]) return mark_safe(f'<button name="approve_button" type="submit"><a href="{url}">Approve</a></button>') approve.short_description = 'Edit status' urlpatterns = [ url(r'^(.+)/approve/$', wrap(self.approve_view), name='events_activity_log_approve'), def approve_view(self, request, object_id, extra_context=None): print(request.POST['approve_button']) #Is None :( Tried with request.POST only as well form = ActivityLogChangeListForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/panel/events/activitylog') Do you guys know what I'm doing wrong? It's been a loong time since I worked with Django and I've wasted 2 days already on that :( Thanks a lot in advance! -
Django date timed events
I need something like this an employee get from date to date a task if date is happend go back to default like previous task or something. any ideas ? -
how can I output a variable to a django template via HttpResponse?
I need to output the correspondents variable to the django template via HttpResponse, but I can't think of how to do it correctly. views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values(u_from.pk).distinct() correspondents = User.objects.filter(pk__in=list(pk_list)) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message']) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.message -
Django form post doesn't contain any values
I have a simple unbound form: class TeamMemberMapForm(forms.Form): remote_id = forms.CharField(widget=forms.HiddenInput()) project = forms.ModelChoiceField(queryset=Project.objects.none()) Initial values are populated in the get_context_data: form.fields['remote_id'].value = remote_id form.fields['remote_id'].initial = remote_id form.fields['remote_id'].disabled = True form.fields['project'].queryset = Project.objects.\ filter(owned_by_company=self.request.user.owned_by_company, active=True) On the frontend, I can select the values, by rendering the form like so. This is fine. {% block form %} <form method="post">{% csrf_token %} <fieldset class="uk-fieldset"> <!-- {{ form.errors }} --> <!-- {{ form.non_field_errors }} --> {{ form.as_p }} </fieldset> <button class="uk-button uk-button-primary" type="submit"> {% if object %} Save {{ object }} {% else %} Create new entry {% endif %} </button> </form> {% endblock %} Next, the view. I take the request and populate the form: def post(self, request, remote_id, remote_name, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # Do whatever In the end, the form never validates. Inspecting the populated form from the POST shows that the values are never received. <tr> <th><label for="id_remote_id">Remote id:</label></th> <td> <ul class="errorlist"><li>This field is required.</li></ul> <input class="uk-input uk-text " type="text" name="remote_id" required id="id_remote_id"> </td> </tr> <tr> <th><label for="id_project">Project:</label></th> <td> <ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul> <select class="uk-select" name="project" required id="id_project"> <option value="">---------</option> </select> </td> </tr> The post object … -
Add Title or Title Tag to url path
I'm hoping somebody can help me with this issue. Im having trouble adding my page/ article title to the url path. I've tried a number of ways can't seem to get it. If anyone could help that would be great. My current Url path is "https://stackoverflow.com/article/1" Would like it to be "https://stackoverflow.com/article/1/example-question-help", or some variation of that. Below you can find how my views and url files are set up. path('article/<int:pk>/', ArticleDetailView.as_view(), name='article-detail'),' class ArticleDetailView(DetailView): model = Post template_name = 'article_detail.html' def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu context["total_likes"] = total_likes context["liked"] = liked return context -
django error foreign key Cannot assign must be a instance
I am creating a stored procedure, I need to create a user in django, I have a foreign key called cargo_empleado that causes me an error my models.py class CargoEmpleado(models.Model): nombre_cargo = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'Cargo_empleado' class Empleado(models.Model): rut = models.CharField(primary_key=True, max_length=9) nombres = models.CharField(max_length=100, blank=True, null=True) apellidos = models.CharField(max_length=100, blank=True, null=True) correo_electronico = models.CharField(max_length=100, blank=True, null=True) usuario = models.CharField(max_length=50, blank=True, null=True) contrasena = models.CharField(max_length=255, blank=True, null=True) activo = models.IntegerField() cargo_empleado = models.ForeignKey(CargoEmpleado, models.DO_NOTHING, db_column='cargo_empleado') id_empresa = models.ForeignKey('Empresa', models.DO_NOTHING, db_column='id_empresa', blank=True, null=True) id_unida = models.ForeignKey('UnidadInterna', models.DO_NOTHING, db_column='id_unida') class Meta: managed = False db_table = 'Empleado' my views.py def crearusuario(request): if request.method=="POST": if request.POST.get('rut') and request.POST.get('nombres') and request.POST.get('apellidos') and request.POST.get('correo_electronico') and request.POST.get('usuario') and request.POST.get('contrasena') and request.POST.get('activo') and request.POST.get('cargo_empleado') and request.POST.get('id_empresa') and request.POST.get('id_unida'): usersave= Empleado() usersave.rut=request.POST.get('rut') usersave.nombres=request.POST.get('nombres') usersave.apellidos=request.POST.get('apellidos') usersave.correo_electronico=request.POST.get('correo_electronico') usersave.usuario=request.POST.get('usuario') usersave.contrasena=request.POST.get('contrasena') usersave.activo=request.POST.get('activo') usersave.cargo_empleado=request.POST.get('cargo_empleado') usersave.id_empresa=request.POST.get('id_empresa') usersave.id_unida=request.POST.get('id_unida') cursor=connection.cursor() cursor.execute("call SP_crear_usuario('"+usersave.rut+"','"+usersave.nombres+"', '"+usersave.apellidos+"', '"+usersave.correo_electronico+"', '"+usersave.usuario+"', '"+usersave.contrasena+"', '"+usersave.activo+"', '"+usersave.cargo_empleado+"', '"+usersave.id_empresa+"', '"+usersave.id_unida+"')") messages.success(request, "El empleado "+usersave.nombres+" se guardo correctamente ") return render(request, 'app/crearusuario.html') else: return render(request, 'app/crearusuario.html') error: Cannot assign "'funcionario'": "Empleado.cargo_empleado" must be a "CargoEmpleado" instance. Please someone help me! -
Django template, send two arguments to template tag and return safe html value is there possible?
im passing 2 values {% checkdatainicio data.one data.two %} and my return is: '<span style="color:#bdc3c7">'+data+"</span>" i want to return it safe in html -
Django admin how to show currency numbers in comma separated format
In my models I have this: class Example(Basemodel): price = models.IntegerField(default=0) and in my admin I have this: @admin.register(Example) class ExampleAdmin(admin.ModelAdmin): list_display = ('price',) I want the price field to be shown in comma-separated format instead of the typical integer format and I want to do that on the backend side. For example: 333222111 should be 333,222,111 Any can recommend me a solution? -
Django one to many saving model is giving error
I have an exam model and I am trying to add a form to add multiple Quiz instance in the parent model. I am getting the following error raise ValueError( ValueError: Cannot assign "": "exam_quiz.quiz" must be a "Quiz" instance. class ExamQuizAdminForm(forms.ModelForm): class Meta: model = exam_quiz exclude = ['registrationDate','examdate'] quiz = forms.ModelMultipleChoiceField( queryset=Quiz.objects.all(), required=False, label=_("Quiz"), widget=FilteredSelectMultiple( verbose_name=_("Quiz"), is_stacked=False)) def __init__(self, *args, **kwargs): super(ExamQuizAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['quiz'].initial = \ self.instance.quiz def save(self, commit=True): exam_quiz = super(ExamQuizAdminForm, self).save(commit=False) exam_quiz.save() exam_quiz.quiz_set.set(self.cleaned_data['Quiz']) self.save_m2m() return exam_quiz class ExamQuizAdmin(admin.ModelAdmin): form = ExamQuizAdminForm list_display = ('examname','month','year') -
NoReverseMatch at / when trying to add href in Django
I have a list of items and I am trying to add a link to the item's title to direct the user to the item's own page. However, I am getting Reverse for 'listing' with arguments '('',)' not found. 1 pattern(s) tried: ['listing/(?P<listing_id>[0-9]+)\\Z'] error and I couldn't figure out what I did wrong. The error is in line<h2><a href="{% url 'listing' listing.id %}">{{auction.title}}</a></h2> of index.html urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create_listing, name="create"), path("listing/<int:listing_id>", views.listing, name = "listing"), ] views.py: def listing(request,listing_id): listing = AuctionItem.objects.get(id = listing_id) return render(request, "auctions/listing.html",{ "listing":listing }) index.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% for auction in auctions %} <div class = "frame"> <img src="{{auction.image}}" style= "width: 30vw;"> <h2><a href="{% url 'listing' listing.id %}">{{auction.title}}</a></h2> <div id="text"><strong>Price:</strong> ${{auction.price}}</div> <div id="text"><strong>Description:</strong> {{auction.description}}</div> <div id="text"><strong>Category:</strong> {{auction.category}}</div><br> <div id="date">Created {{auction.date}}</div> </div> {% empty %} <li>No item.</li> {% endfor %} {% endblock %} -
I have successfully deployed the django web app to heroku but it was giving application error
I have successfully deployed the Django web app to Heroku but it was giving an application error. heroku logs 2010-09-16T15:13:46.677020+00:00 app[web.1]: Processing PostController#list (for 208.39.138.12 at 2010-09-16 15:13:46) [GET] 2010-09-16T15:13:46.677023+00:00 app[web.1]: Rendering template within layouts/application 2010-09-16T15:13:46.677902+00:00 app[web.1]: Rendering post/list 2010-09-16T15:13:46.678990+00:00 app[web.1]: Rendered includes/_header (0.1ms) 2010-09-16T15:13:46.698234+00:00 app[web.1]: Completed in 74ms (View: 31, DB: 40) | 200 OK [http://myapp.heroku.com/] 2010-09-16T15:13:46.723498+00:00 heroku[router]: at=info method=GET path="/posts" host=myapp.herokuapp.com" fwd="204.204.204.204" dyno=web.1 connect=1ms service=18ms status=200 bytes=975 2010-09-16T15:13:47.893472+00:00 app[worker.1]: 2 jobs processed at 16.6761 j/s, 0 failed ... I also try to set DEBUG = True from Django's settings.py but no errors were showing. -
How can an object be deleted if another one is emty?
So, I am a begginer coding an e-commerce project on Django. I've managed to add a "delete item"function to remove items from the cart. However, when the item is removed, the order isn't. OrderItem and Order are 2 sepparate models, I'd like so that when an OrderItem i fully deleted and the cart is empty, for the order itself to be deleted too. I'll attach de code for the models and the functios. Order mode: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total OrderItem model: class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total The function for deleting the items: def eliminaritem(request, id): if request.method == "POST": item = OrderItem.objects.get(product = id) item.delete() return render(request, "store/deletecartitem.html", {'item': item}) if OrderItem.objects.all == None: customer = customer = request.user.customer order = Order.objects.all(customer = customer) order.delete() The first … -
Django ListView filter and orderby with pagination
I'm building a simple e-commerce website. I'm using ListView to represent home page of website that displays items. I want to be able to filter Items by their category and be able to order by some factor (for example price). By default it should show all items. And if there is another page of items of given kind it should keep filter. Also an explanation would be greatly appreciated. My code: views.py from django.views.generic import ListView, from .models import ShopItem class HomeView(ListView): model = ShopItem paginate_by = 2 template_name = "home-page.html" def get_queryset(self): q = self.request.GET.get('filter', '') if not q: return self.model.objects.all() return self.model.objects.filter(category=q) models.py from django.db import models class ShopItem(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=15) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) slug = models.SlugField() home-page.html <li class="nav-item active"> <a class="nav-link" href="/">All <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">Necklace</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Earrings</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Bracelets</a> </li> {% if is_paginated %} <nav class="d-flex justify-content-center wow fadeIn"> <ul class="pagination pg-blue"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for page in page_obj.paginator.page_range … -
How to I log into the admin panel in django without manually typing url into search bar [closed]
Am a newbie and am wondering how Ill login into the admin panel once am done with the website. my thought was to add redirect in the frontend buh I dont seem to see it done in other sites. What can I do? thanks -
Tag of a Django Template from a variable
I need to do a form with Django which can have both "select" or "input" tags, depending on a variable. Here's how I pass the variable to the html (file: views.py): from django.shortcuts import render, redirect from direzione.models import Jobs, JobType from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.template.defaulttags import register from login import views as lgnwv import json # Create your views here. @register.filter def get_item(dictionary,key): return dictionary.get(key) @login_required(login_url=lgnwv.login) def fattura(request): if request.method =="POST": if request.POST.get('logout') == 'logout': logout(request) return redirect(lgnwv.login) else: datas = JobType.objects.get(jobType=0) dts = json.loads(datas.inputs) job = Jobs.objects.get(id_job=1) jobName = job.nome jobHead = datas.headNome return render(request, 'fattura/fattura.html', {"dts": dts, "inputs":dts["inputs"], "jobName":jobName, "jobHead":jobHead}) So, the variable that contains the string 'input' or 'select' is into the dict inputs (the one that's looped) This is my form: <div class="form" style="height:{{ dts|get_item:'height' }}px"> <div class="title">Crea Fattura</div> <div class="subtitle">Compila tutti i campi correttamente.</div> {% for key, value in inputs.items %} <div class="input-container ic2"> <{{ value|get_item:'tag' }} id="{{ key }}" autocomplete="off" class="input" type="{{ value|get_item:'inputType' }}" placeholder=" " /> <div class="cut" style="width: {{ value|get_item:'cutWidth' }}px"></div> <label for="{{ key }}" autocomplete="off" class="placeholder">{{ value|get_item:'placeholder' }}</label> </div> {% endfor %} <button type="text" class="submit">Invia</button> </div> The line where I have the problem is the … -
I can't start my django project after some code updates. I was revert everything back, but it still not working
I don't think that error in code. I did git reset --hard <commit> to last work version, and it was still broken The error when i'm use runserver command: Traceback (most recent call last): File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 74, in execute super().execute(*args, **options) File "/usr/local/lib/python3.9/dist-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/dist-packages/django/core/management/commands/runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 92, in __getattr__ self._setup(name) File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.9/dist-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crm/crm/settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/club2/crm/manage.py", line 22, in <module> main() File "/root/club2/crm/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/dist-packages/django/core/management/__init__.py", line 440, … -
How to redirect logged-in user to a specific page in Django
Code was not written by me, I am just trying to find a way to redirect a logged-in user if he wants to access a certain page in a Python/Django script. I can actually do it in Templates but as far as I understand this logic should be implemented in Views. Example: Already logged-in user tries to access to signup page by typing the signup page url/path. In this case, I would like to redirect the user to the homepage (/). What I tried with very very basic Python and zero Django knowledge?. Inside the views/auth.py (SignUp class), I try to write a get method and check if user is already authenticated, redirect him to a specific page. And actually it worked for already logged-in users but if a guest/visitor wants to open the sign up page then it returns an error: "views.auth.SignUp didn't return an HttpResponse object. It returned None instead." class SignUp(FormView): form_class = SignUpForm template_name = "xxx/registration/signup.html" # I added def get(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('/') def form_valid(self, form): user = form.save(commit=False) user.username = form.cleaned_data.get("username").lower() user.theme = get_theme_from_cookie(self.request) user.save() send_email_confirmation(user, user.email) notifications.info( self.request, _( "confirmation message.." ), ) return redirect("login") and here is the … -
How to save screenshot to CloudinaryField in django using chromedriver on Heroku?
When I do driver.save_screenshot, even if return returns true, the file is not there. How do I save the screen_shot to the database? someone teach me... #models.py class UploadedImage(models.Model): image = CloudinaryField('image', blank=True, null=True, folder="media") author = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) token = models.CharField(max_length=256, null=True, blank=True) #views.py options = Options() options.add_argument('--disable-gpu') options.add_argument('--disable-extensions') options.add_argument('--proxy-server="direct://"') options.add_argument('--proxy-bypass-list=*') options.add_argument('--start-maximized') options.add_argument('--headless') options.add_argument('--no-sandbox') driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options) driver.get('https://weather.yahoo.co.jp/weather/') driver.set_window_size(1250, 1036) driver.save_screenshot('/app/a.png') UploadedImage.objects.create(image='/app/a.png') return HttpResponse("Success", request) -
Django model conditional default value based on other field
There is two tables Company and Template_message each company can have desired template messages for each message messages have 3 types ( invitation,rejection,Job_offer) now i want to set a default text for each template_message which the company can change it later on but i dont know how to set the default value for each template message , based on their type the model i designed is bellow : class TemplateMessage(models.Model): TEMPLATE_TYPE_CHOICES = ( ('1', 'invitation'), ('2', 'Rejecting'), ('3', 'Job_offer_acceptance'), ) type = models.CharField(max_length=4, choices=TEMPLATE_TYPE_CHOICES, default='1') def subject_initials(type): match type: case 1: return "[jobName] skills test invitation from [companyName]" case 2: return "Thank you from [companyName]" case 3: return "Job offer letter from [companyName]" subject = models.CharField(max_length=256, default=subject_initials(type)) company = models.ForeignKey('Company', on_delete=models.CASCADE) class Meta: unique_together = ("company", "type") def __str__(self): return self.type but it does not not work and when i go to admin panel the subject text is not set to any default value -
Nested Models in Serializer django
I cannot get the last measurement for each device based on the device's ID from the measurement. If someone can advise me on how to implement this? Models class Devices(models.Model): deviceid = models.AutoField(db_column='deviceId', primary_key=True) # Field name made lowercase. devicename = models.CharField(db_column='deviceName', unique=True, max_length=128) # Field name made lowercase devicestatus = models.IntegerField(db_column='deviceStatus') # Field name made lowercase. Class Meta: managed = False db_table = 'devices' class Measurements(models.Model): measurementid = models.AutoField(db_column='measurementId', primary_key=True) # Field name made lowercase. deviceid = models.ForeignKey(Devices, models.DO_NOTHING, related_name="measurment_details", db_column='deviceId') # Field name made lowercase. measurement = models.CharField(max_length=64, blank=True, null=True) class Meta: managed = False get_latest_by = 'measurementtime' db_table = 'measurements' Serializer class MeasurmentsSerializer(serializers.ModelSerializer): class Meta: model = Measurements fields = ('measurementid','measurement') class DeviceSerializer(serializers.ModelSerializer): latestmeasurment = serializers.SerializerMethodField() count = 0 def get_latestmeasurment(self, obj): qs = Measurements.objects.using('@@@').last() serializer = MeasurmentsSerializer(instance=qs, many=False) self.count = 1 + self.count print(self.count , serializer.data ) return serializer.data class Meta: model = Devices fields = ("devicename", 'latestmeasurment') Views class RetrieveAllDevicesView(viewsets.ModelViewSet): http_method_names = ['get'] permission_classes = [permissions.IsAuthenticated] serializer_class = DeviceSerializer queryset = Devices.objects.using('@@@') In serializer, you can see the count for primitive debug: 1 {'measurementid': 2942080, 'measurement': '35.0'} 2 {'measurementid': 2942080, 'measurement': '35.0'} 3 {'measurementid': 2942080, 'measurement': '35.0'} 4 {'measurementid': 2942080, 'measurement': '35.0'} 5 {'measurementid': 2942080, …