Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ManyToMany django groups and users model with save_model()
i have a model Transaction that has some tables as shown below.. models.py : class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and in the admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user super().save_model(request, obj, form, change) # def get_queryset(self, request): # qs = super().get_queryset(request) # if request.user.is_superuser: # return qs # return qs.filter(group__in=request.user.groups.all()) i know this methods are broke, but i been struggling a lot with it im trying to override the save_model() and get_queryset() functions in the admin.py but im not sure how to do it. what im trying to do is for example i have 2 groups and in each group i will add certain amount of users. lets say i have (group1) and inside it i have users 'edy' and 'tom' inside it, and (group2) inside it 'sara' and 'laura', When edy makes a Transaction i want only (group1) users to access this transaction. same goes for (group2). and i dont want to create a group table inside the Transaction model, … -
Convert nested dictionary to url encoding as outputted from encodeURIComponent
I have this url encoded string (which is produced by the jQuery datatables library and looks to be outputted from the built in JavaScript encodeURIComponent function)- draw=1&columns%5B0%5D%5Bdata%5D=&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=false&columns%5B0%5D%5Borderable%5D=false&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=supplier__name&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=ref&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=period__fy_and_period&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=date&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=due_date&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=true&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=total&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=true&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B7%5D%5Bdata%5D=paid&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=true&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B8%5D%5Bdata%5D=due&columns%5B8%5D%5Bname%5D=&columns%5B8%5D%5Bsearchable%5D=true&columns%5B8%5D%5Borderable%5D=true&columns%5B8%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B8%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=1&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false Which I convert to a nested dict using this package - https://github.com/bernii/querystring-parser. {'draw': '1', 'columns': {0: {'data': '', 'name': '', 'searchable': 'false', 'orderable': 'false', 'search': {'value': '', 'regex': 'false'}}, 1: {'data': 'supplier__name', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 2: {'data': 'ref', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 3: {'data': 'period__fy_and_period', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 4: {'data': 'date', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 5: {'data': 'due_date', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 6: {'data': 'total', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 7: {'data': 'paid', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}, 8: {'data': 'due', 'name': '', 'searchable': 'true', 'orderable': 'true', 'search': {'value': '', 'regex': 'false'}}}, 'order': {0: {'column': '1', 'dir': 'asc'}}, 'start': '0', 'length': '10', 'search': {'value': '', 'regex': 'false'}} How can I reverse this? I'm half there after managing to convert it to the decoded URL … -
Why I cannot register '.as_view()' in the Django router (using djangorestframework-simplejwt)?
I have been trying to add djangorestframework-simplejwt to my webapp and whenever I use the router to add the views (see the 2 commented routers in the code below) - I get an error (see traceback). When adding the urls as the documentation says - under the urlpatterns variable - it works without any errors. I would like to know why this isn't working through the router.register(..) and for the sake of good order (and my OCD), is it possible to move it out of the urlpatterns variable to the router. from django.urls import path, include from rest_framework import routers from . import views from django.conf.urls import url from django.contrib import admin from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) app_name = 'myapi' router = routers.DefaultRouter() router.register(r'posts', views.PostViewSet) router.register(r'user', views.UserViewSet) router.register(r'likes', views.LikesViewSet) # router.register(r'token',TokenObtainPairView.as_view()) # router.register(r'token/refresh',jwt_views.TokenRefreshView.as_view()) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/test/anaconda3/envs/ppproject/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/home/test/anaconda3/envs/ppproject/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/test/anaconda3/envs/ppproject/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/test/anaconda3/envs/ppproject/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/test/anaconda3/envs/ppproject/lib/python3.9/site-packages/django/core/management/base.py", line 392, in check all_issues = checks.run_checks( File … -
Using translate field for 'unique' rises NameError, django-parler
I've recently installed django-parler==2.2 and when I rewrite my model to inherit from TranslatableModel and then try to makemigrations I get the following error: main_menu_slug = models.SlugField(max_length=120, unique=main_menu_item) NameError: name 'main_menu_item' is not defined Everything runs fine when I inherit from models.Model. Here is the code: class MenuItem(TranslatableModel): translations = TranslatedFields ( main_menu_item = models.CharField(max_length=60), main_menu_slug = models.SlugField(max_length=120, unique=main_menu_item) ) I've just started using this module, so possibly it is something trivial but I couldn't find the solution. What I am doing wrong? -
Groups model and Users model - ManyToMany field django admin
Im hassling for weeks now, hope someone could help. i have django admin page, with some apps, im trying to make use of the groups model which has ManyToMany relation with Users model, which come with django. first let me show you my Transaction model, models.py class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) and in the admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user print(obj.user) super().save_model(request, obj, form, change) # def get_queryset(self, request): # qs = super().get_queryset(request) # if request.user.is_superuser: # return qs # return qs.filter(group__in=request.user.groups.all()) what im trying to do I want to make for example 3 groups in the admin page, each group will have certain amount of users, users are not super users. for example (Group1) will have 'edy' And 'tom' in it, (group2) have 'sara' and 'laura' in it. when edy makes a new transaction. i want this transaction whos made by edy be available and editable by (group1) members only and same goes for (group2). so what im struggling … -
Model is only updated in the Django Administration app and not in my app
I have just noticed that the model that I am displaying in my app is only showing new items that have been entered in the Django Administration app, and isn't showing anything that I enter directly from my own application. Could anyone explain what is going on? Here is my models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone class Ticket(models.Model): """ Add a ticket """ title = models.CharField(max_length=225,blank=False) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(blank=True, null=True, default=timezone.now) views = models.IntegerField(default=0) upvotes = models.IntegerField(default=0) image = models.ImageField(upload_to="img", blank=True, null=True) def __unicode__(self): return self.title and here is my admin.py in the same app: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Ticket admin.site.register(Ticket) -
Alternative to raising Http404 from within a function call, (Django FormView)?
Hear me out. I have a class based FormView which renders a form with just one field as set of radio select buttons. The select options are based on a dynamic queryset that is passed in the kwargs when the form is initialised (see full code for the view below) def get_form_kwargs(self, **kwargs): """ Provides keyword arguemnt """ kwargs = super(ConfirmTripView, self).get_form_kwargs() trips = self.get_trips_queryset(self.gte_dates, self.lt_dates) kwargs.update({"trips": trips}) return kwargs This queryset is determined in the view logic by a database query and various other filters using values stored in the session. I have quite a few methods in play so that the same queryset is formed in both request.POST and request.GET. Specifically, I call a method def get_available_trips(self, destination, passengers): The resulting queryset is returned, passed and filtered further in other methods. I am considering a situation where this initial query returns no results. The methods that follow would raise errors and ultimately the form would not be rendered and it would be quite a catastrophe. Therefore I would need to break out of the flow somehow and instead render a message that says something like 'Sorry there is no availability for this selected trip'. I have only managed … -
Python Fast and efficient string and substring matching
Say I have a list of cars mercedes, lambo, ect. Each car object has a sublist of car models, aclass, gclass, ect. Both the Car top level class and the sub Model class has an image_url_string attached to it. see below. [ { 'car': 'mercedes', picture: 'mercedes_image_url' 'model': [ { car: 'aclass', picture: 'aclass_image_url' }, { car: 'gclass', picture: 'gclass_image_url' }, ] }, { 'car': 'lambo', picture: 'lambo_image_url' 'model': [ { car: 'urus', picture: 'urus_image_url' }, { car: 'huracan', picture: 'urus_image_url' }, ] } ] Question: Given a string, I need a function say getCarOrCarModelImage, that if the string given starts with a car, => returns the car's image_url if the string given starts with a car then a hyphen - then the model eg. mercedes - aclass => returns the model's url, Else it returns false The function should accommodate excess space errors in the given string Here are some instances: // True mercedes -> returns mercedes_image_url mercedes afagasfgagasdf_random_string -> returns mercedes_image_url mercedes -aclass asdfgafadsf_random_string -> returns aclass_image_url lambo -urus dasfddsag_random_string -> returns urus_image_url // with excess space errors lambo -urus dasfddsag_random_string -> returns urus_image_url lambo dasfddsag_random_string -> returns lambo_image_url // False dasfddsag_random_string -> returns false -urus dasfddsag_random_string -> … -
Django Foreign key in hidden form field
I'd like to hide a Foreign Key field in a form created from a Model in a View. Here is the Model : class Order(models.Model): class Meta: ordering = ['unity_price'] item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(authModels.User, on_delete=models.CASCADE, default=1) order_quantity = models.IntegerField(default=0) unity_price = models.FloatField(default=0) end_validity_date = models.DateTimeField(default=timezone.now() + datetime.timedelta(days=30)) is_sell = models.BooleanField(default=True) def __str__(self): if self.is_sell: return 'sell ' + str(self.order_quantity) + ' ' + self.item.item_text + ' at ' + str(self.unity_price) return 'buy ' + str(self.order_quantity) + ' ' + self.item.item_text + ' at ' + str(self.unity_price) Here is the Form : from .models import Order class OrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['user'].widget = HiddenInput() self.fields['item'].widget = HiddenInput() class Meta: model = Order fields = ('item', 'user', 'order_quantity', 'unity_price', 'end_validity_date', 'is_sell',) And here is the View : class DetailView(FormMixin, generic.DetailView): model = Item template_name = 'bourse/detail.html' form_class = OrderForm def get_success_url(self): return reverse('bourse:detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) context['form'] = OrderForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() form.fields['item'].initial = self.get_object() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): model_instance = form.save(commit=False) model_instance.user = self.request.user model_instance.item = self.get_object() print (model_instance.item) model_instance.save() return … -
How to get choicefield selected value Django Forms
I have taken an empty Choicefield called product_attr. I get attributes for that product via Ajax Call On Change event. When I go to update the form, the Attributes field does not show the value I submitted. How can I get the existing value of product_attr field in the form while editing/updating. Please help me to get out of here. forms.py class PurchaseOrderDetailsForm(forms.ModelForm): product = forms.ModelChoiceField(label=('Product'), required=True, queryset=Product.objects.all(), widget=Select2Widget()) product_attr = forms.CharField(label=('Attributes'), required=False, widget=Select2Widget(choices=[])) Get attribute value on ajax request: def load_attrs(request): product = request.POST.get("product") attrs = ProductAttributes.objects.filter(product=product).values('product', 'size__name', 'colour__name','cupsize__name') return render(request, 'main/purchase/attr_dropdown_list_options.html', {'attrs': attrs}) views.py: (form update) class PurchaseOrderItemsUpdate(UpdateView): model = PurchaseOrder form_class = PurchaseOrderForm template_name = 'main/purchase/index.html' def get_context_data(self, **kwargs): kwargs['object_list'] = PurchaseOrder.objects.order_by('-id') data = super(PurchaseOrderItemsUpdate, self).get_context_data(**kwargs) if self.request.POST: data['order_details'] = PurchaseOrderItemsFormset(self.request.POST, instance=self.object) else: data['order_details'] = PurchaseOrderItemsFormset(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() order_details = context['order_details'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if order_details.is_valid(): order_details.instance = self.object order_details.save() return super(PurchaseOrderItemsUpdate, self).form_valid(form) -
Exception has occurred: OperationalError could not translate host name "db" to address: Unknown host
I am running locally this script. On postgres connection, I am facing "Exception has occurred: OperationalError could not translate host name "db" to address: Unknown host". Database is up, I started it with docker run --publish 8000:8000 --detach --name db remoteaddress:latest When I do the same using docker-compose, and exec to django app and run it as management command, it works. The code: conn_string = "host='db' dbname='taras' user='postgres' password='postgres'" with psycopg2.connect(conn_string) as connection: with connection.cursor() as cursor: ... my stuff -
mysql 2006 error when filtering with large list of arguments
Say I have a model like this: class Order(models.Model): code = models.CharField(max_length=90, db_index=True, unique=True) When I have a list of codes, list_of_codes, with more than 600,000 elements and I try to get a list of codes that are in my database, I get a 'MySQL server has gone away' error on the second line below - which I think makes sense because that's when the queryset get evaluated so it's probably taking a while and the connection times out(?): duplicate_codes = Order.objects.filter(code__in=list_of_codes).values_list('code', flat=True) duplicates.update([some_dict[code] for code in duplicate_codes]) ## error gets thrown here I'm trying to understand why this is happening and what would be some good ways to fix this with scalability in mind. I can't find much in the django docs about filtering with a lot of data like this. For now, I'm partitioning the list of codes and doing the filtering in chunks. -
Inline with recursive self OneToOneField in Django's admin
I'm trying to display a read-only OneToOneField (recursive self) as Inline however in my admin I see it empty. I have the following model defined: class LogEntry(models.Model): data = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) origin_request_log = models.OneToOneField( 'APILogEntry', blank=True, null=True, related_name='response', on_delete=models.SET_NULL ) And in my admin.py: class APILogEntryInline(admin.StackedInline): model = APILogEntry readonly_fields = fields = ['created_at', 'data'] class APILogEntryAdmin(admin.ModelAdmin): list_display = list_display_links = ['created_at', 'data'] readonly_fields = fields = ['created_at', 'data'] admin.site.register(APILogEntry, APILogEntryAdmin) In my admin I see it like this: -
Not able to get Login user in Django Channels using WebsocketConsumer
I am not able to get login user in Django channels. I am using AuthMiddlewareStack but still facing the issue. Django channels error. Using WebsocketConsumer but not able to get current logged in user Consumers.py class TableData(WebsocketConsumer): def connect(self): print(self.scope["user"]) self.group_name='tableData' async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() data = Game.get_games(1) self.send(text_data=json.dumps({ 'payload': data })) routing.py ws_pattern= [ path('ws/tableData/',consumers.TableData), path('ws/room/' , consumers.Room), path('ws/game/room/<room_name>' , consumers.ChatConsumer) ] application= ProtocolTypeRouter( { 'websocket':AuthMiddlewareStack(URLRouter(ws_pattern)) } ) `` -
Django: Logging to custom files every day
I'm running Django 3.1 on Docker and I want to log to different files everyday. I have a couple of crons running and also celery tasks. I don't want to log to one file because a lot of processes will be writing and debugging/reading the file will be difficult. If I have cron tasks my_cron_1, my_cron_2,my_cron_3 I want to be able to log to a file and append the date MyCron1_2020-12-14.log MyCron2_2020-12-14.log MyCron3_2020-12-14.log MyCron1_2020-12-15.log MyCron2_2020-12-15.log MyCron3_2020-12-15.log MyCron1_2020-12-16.log MyCron2_2020-12-16.log MyCron3_2020-12-16.log Basically, I want to be able to pass in a name to a function that will write to a log file. Right now I have a class MyLogger import logging class MyLogger: def __init__(self,filename): # Gets or creates a logger self._filename = filename def log(self,message): message = str(message) print(message) logger = logging.getLogger(__name__) # set log level logger.setLevel(logging.DEBUG) # define file handler and set formatter file_handler = logging.FileHandler('logs/'+self._filename+'.log') #formatter = logging.Formatter('%(asctime)s : %(levelname)s: %(message)s') formatter = logging.Formatter('%(asctime)s : %(message)s') file_handler.setFormatter(formatter) # add file handler to logger logger.addHandler(file_handler) # Logs logger.info(message) I call the class like this logger = MyLogger("FirstLogFile_2020-12-14") logger.log("ONE") logger1 = MyLogger("SecondLogFile_2020-12-14") logger1.log("TWO") FirstLogFile_2020-12-14 will have ONE TWO but it should only have ONE SecondLogFile_2020-12-14 will have TWO Why is this? … -
Unable to update individual items in Django
I am trying to update some information in my Django application but I am getting this error "Cannot assign "9": "Reservation.table" must be a "Tables" instance". I have tried so manual method also but it still same error. Error: Cannot assign "9": "Reservation.table" must be a "Tables" instance views.py @login_required def UpdateReservation(request, pk): table_exists = get_object_or_404(Reservation, id=pk) form = ReservationForm(instance=table_exists) if request.method == "POST": form = ReservationForm(request.POST, instance=table_exists) if form.is_valid(): form = ReservationForm(request.POST, instance=table_exists) if form.is_valid(): form.save() return redirect('view_reservations') messages.success(request, "successfully updated table") context = {"form": form} return render(request, "dashboard/super/landlord/update_reserve.html", context) models.py class Reservation(models.Model): status_choices = ( ("pending", "pending"), ("confirmed", "confirmed") ) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField() phone = PhoneNumberField(blank=True) people = models.IntegerField(default=1) time = models.TimeField() date_reserved = models.DateField() date_booked = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=status_choices, default="confirmed") comment = models.TextField(blank=True) table = models.ForeignKey(Tables, on_delete=models.CASCADE) def __str__(self): return self.first_name forms.py class ReservationForm(forms.ModelForm): time = forms.CharField( widget=forms.TextInput(attrs={'id': 'timepicker', 'class': 'input-group', 'placeholder': '12:00:AM'})) date_reserved = forms.DateField(widget=forms.TextInput( attrs={'placeholder': 'yyyy-mm-dd', 'id': 'datepicker'}), required=True,) comment = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Leave a message'}), required=True,) first_name = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Leave a message'}), required=False,) email = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Your Email Address'}), required=True,) phone = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Your Telephone number'}), required=True,) table = forms.IntegerField(widget=forms.TextInput( attrs={'placeholder': 'Table Number'}), … -
If radio is checked on submit jQuery
im trying to check if a radio button is checked on submit of a form. Ive researched but i didnt get it to work. It might be a silly mistake or type but ive been trying for hours now. The two different methods i tried are. $("#form").submit((e) => { e.preventDefault(); if ($("#radio").attr("checked") == "checked") { alert("checked"); } if ($("#radio").is("checked")) { alert("checked"); } }); And the html is: <form action="" method="POST" id="form"> {% csrf_token %} <label for="radio"> <input type="radio" name="" id="radio" /> </label> <button type="submit">Submit</button> </form> </div> Im doing this in django also. Thanks for any replies and sorry if im just making a silly mistake. -
If I have a separate models for an item and a separate model for the images relating to that item, how can I combine these into a query?
I am trying to display in a card view the items from my queryset. I have a model for Item and a separate model for ItemImage to allow several uploaded images for a single item. Each image also has a property is_primary to determine if it's the image that will be displayed in the dynamically generated cards. I've succeeded in displaying item details from my item model queryset. However, I am struggling to understand how I can combine the itemimage.url attribute with the all_items context I am passing into the template. How can I make sure that the images from my image queryset match the pk of the item they are assigned to and are also the primary photo for that item? views.py from django.shortcuts import render, redirect # Create your views here. from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .models import Item, ItemImage def home(request): all_items = Item.objects.all() item_images = ItemImage.objects.all() ItemImage.objects.filter(is_primary=True) context = {'items': all_items} return render(request,'items/home.html',context) models.py from django.db import models from django.utils import timezone from decimal import Decimal # Create your models here. class Item(models.Model): name = models.CharField(max_length=70) date_added = models.DateTimeField(default=timezone.now) price = models.DecimalField(max_digits=9, decimal_places=2, default=Decimal('0.00')) description = models.CharField(max_length=300) def … -
How to Change Django AbstractUser Group to String
I made some groups inside of Django Admin, but whenever I add a user to one of those groups, only the group ID displays inside of my API endpoint. Is there a way to display the string name? So instead of 1, I want the field to be "Directors". Does it have anything to do with extending the AbstractUser Model? This is all I have right now, for my User info: class User(AbstractUser): -
How to create user and then login client in django test
I am developing a web application using Django 3.1.4. My app allows register and login and now I want to write some tests. To reach this I need a logged testing-user. And here is a question: How to do it ? I found many many solutions like : self.user = User.objects.create_user(username='testuser', password='12345') self.client.login(username='testuser', password='12345') etc. etc. but I am confused where should I looking for data to pass inside create_user(....), how many args should I pass ? In register form ? In my Profile Model ? my example test: def setUp(self): User = get_user_model() user = User.objects.create_user('test12345', 'test@gmail.com', 'test12345') def test_profile_response(self): url = reverse('profile') self.client.login(username = 'test12345', password = 'test12345') response = self.client.get(url) self.assertEquals(response.status_code, 200, msg ='login request is invalid') Here are the whole code: https://github.com/Equilibrium23/Walk-For-The-Dog -
Django Channels - self.channel_layer.group_send not working
I am trying to configure my Channels application for deployment. All is good until I connect to a websocket. I'm mainly using websockets for chat and "announcements". However, when I connect and try to send a message, my consumer receives it but doesn't send anything back. asgi.py: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import re_path from . import consumers application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": (URLRouter([ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ])) }) consumers.py: import json from asgiref.sync import AsyncToSync as b from channels.generic.websocket import AsyncWebsocketConsumer, WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group b(self.channel_layer.group_add( self.room_group_name, self.channel_name )) print("connected!") self.accept() def disconnect(self, close_code): # Leave room group b(self.channel_layer.group_discard( self.room_group_name, self.channel_name )) # Receive message from WebSocket def receive(self, text_data): data = json.loads(text_data) message_type = data['body_type'] body = data['body'] send_data = { 'type': message_type, "body": body } print(send_data) # Send message to room group send = b(self.channel_layer.group_send( self.room_group_name, send_data )) print(send) # Receive message from room group def message(self, event): # Send message to WebSocket b(self.send(text_data=json.dumps({ 'message': event }))) CHANNEL_LAYERS in settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } When … -
How to automatically update model fields in Django?
So I have this simple models: class Room(models.Model): STATUS = ( ('Available', 'Available'), ('Occupied', 'Occupied'), ) status = models.CharField(choices=STATUS) name = models.CharField(max_length=200) class Reservation(models.Model): STATUS = ( ('Confirmed', 'Confirmed'), ('Pending', 'Pending') ) status = models.CharField(choices=STATUS) room = models.OneToOneField(Room, on_delete=) date_created = models.DateTimeField(auto_now_add=True) I want that whenever I create a new Reservation and assign a room to it, the status field of that particular Room is automatically changed to 'Occupied'. I think there is a way to do this with Django Signals but I haven't figured out how to implement it on my own yet. Thanks in advance. -
What kind of IntegrityError is Django raising during test?
I am running the below test: from django.db import IntegrityError def testInvalidSubAndOutcodeCombination(self): with self.assertRaises(IntegrityError): Property.objects.create( property_id=1234567, property_type='Flat', property_outcode=self.outcode, property_sub_outcode=SubOutcode(self.outcode, sub_outcode='FAIL'), bedroom_count=1, property_url='https://www.rightmove.co.uk/' ) It should pass as it should raise an IntegrityError. It raises an IntegrityError but the test fails: ERROR: testInvalidSubAndOutcodeCombination (snippets.tests.models.TestModels) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\test\testcases.py", line 282, in _setup_and_call self._post_teardown() File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\test\testcases.py", line 1005, in _post_teardown self._fixture_teardown() File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\test\testcases.py", line 1163, in _fixture_teardown connections[db_name].check_constraints() File "C:\Users\Arturka\Documents\repos\ldnRentAPI\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 343, in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'property' with primary key '1234567' has an invalid foreign key: property.property_sub_outcode_id contains a value 'FAIL' that does not have a corresponding value in sub_outcode.sub_out code. What "kind" of IntegrityError is this if it's not from django.db import IntegrityError ? I've tried django.db.backends.sqlite3.base.IntegrityError but the result is the same: ====================================================================== FAIL: testInvalidSubAndOutcodeCombination (snippets.tests.models.TestModels) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Arturka\Documents\repos\ldnRentAPI\snippets\tests\models.py", line 66, in testInvalidSubAndOutcodeCombination Property.objects.create( AssertionError: IntegrityError not raised -
imagefield.url not working, setting up media_url, media_root, and static_url
The problem: I'm trying to display Notification objects that I have assigned to each user. Each notification has an icon I want to display. I set the <img> src attribute to {{ notif.icon.url }}, but i'm seeing the icon for a bunch of unloaded images instead. I think I need to change MEDIA_ROOT and MEDIA_URL and STATIC_URL, but I'm not really sure how. notification-btn.html <div data-simplebar style="max-height: 230px;"> {% for notif in notifications %} <a href="" class="text-reset notification-item"> <div class="media"> <img class="avatar-xs mr-3 rounded-circle" src="{{ notif.icon.url }}"> From inspecting element, I see that it's trying to load the url 127.0.0.1:8000/media/user_icons/logo.png. This is almost correct, the image exists at 127.0.0.1:8000/static/media/user_icons/logo.png. I've been working on an existing django project and the person who started it wasn't very confident in their python/django abilities. I see a lot of tutorials recommend putting the static/ folder inside each project directory. Instead, this django project currently has a static/ folder in the project root directory. There is a media/ folder inside of static. Our file tree looks like lpbs_website/ lpbs_website/ settings.py urls.py wsgi.py, asgi.py, __init__.py... static/ media/ uploaded_files/ user_icons/ images/, css/, js/, ... templates/ manage.py And our settings.py... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') … -
modules cannot load in a new Django project
I made 2 projects with django so far and everything smooth. using python 3.6 and conda env with django 3.1.4 I am following the tutorial to kick off my new project as I did for my previous one : https://docs.djangoproject.com/fr/3.1/intro/tutorial01/ Start a new one using "django-admin startproject ngedemocarto" then used "django startapp sitemanager" it gives me this : but suddenly in this project I keep having error when I try to call any app module like "apps.py" or "urls.py" typical error if I add the app config in settings.py like this : INSTALLED_APPS = [ 'sitemanager.apps.SitemanagerConfig' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] resolve in this error : ModuleNotFoundError: No module named 'sitemanager.apps.SitemanagerConfigdjango'; 'sitemanager.apps' is not a package every command like manage.py runserver or manage.py migrate is failing at import because it can't resolve any names like "sitemanager.apps" or "sitemanager.urls" I checked basic things : I have a init.py at sitemanager root folder urls.py or apps.py exist if I use python in cmd at mynewproject folder and try import "sitemanager.apps" , it works. ( no error) I am in a very basic config just after starting this new project and nothing works ... I tried to build a new conda …