Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Views.py If else statement not working
This is my html page <div class="col-md-4 col-sm-12 col-xs-12"> <input type="radio" class="avg radioalign" id="DocDetails1" name="DocDetails" value="1" checked> <span class="RadioSpan">New Documents</span> <input type="radio" class="avg radioalign" id="DocDetails2" name="DocDetails" value="2"> <span class="RadioSpan">New Versions</span> <div id="AverageHours" class="col-md-12 box borderFrame make-it-slow"></div> </div> This is my ajax $(".avg").click(function() { var x = $(this).val() alert(x); $.ajax({ url : "{% url 'AverageHours' %}", data : { Id : x }, success : function(response) { alert("hy"); } }); }) This is my views.py def AverageHours(request): ID = request.GET.get('Id'); if ID == '1': AgeingCheckOutQuery = connection.cursor() AgeingCheckOutQuery.execute("""select 10,20,30,40""") Results = AgeingCheckOutQuery.fetchall() return render(request,"Dashboard/Documents/AverageHours.html",{'values': Results}) else : NewVersion = connection.cursor() NewVersion.execute("""select 10,80,20,10""") Results1 = NewVersion.fetchall() return render(request,"Dashboard/Documents/AverageHours.html",{'values': Results1}) When I Click the radio button ajax value is passed but the if condition directly goes to else part it does get the value when i return back the getting value to html page it return null value -
How to set multiple values with additional field in django models?
I have a model with represents a many to many table. class WasteFacilityMaterialType(models.Model): waste_facility = models.ForeignKey( WasteFacility, on_delete=models.CASCADE, related_name="waste_facility_material_type", ) material_type = models.ForeignKey( MaterialType, on_delete=models.CASCADE, related_name="material_type_waste_facility", ) cost_per_ton = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) class Meta: db_table = "waste_facility_material_type" unique_together = [["waste_facility", "material_type"]] How can I add records to this table when inserting/updating with additional field cost_per_ton so that when a object of material_type is removed from the request the records should be also removed from the table. Basically how to achieve sync of many many to records with additional fields. My request looks something like this: { "name":"Dade Waste Facility", "email":"pritamk@gobiggi.com", "mobile":"3054014181", "street":"Street 1", "city":"Miami", "zipcode":"33161", "state":"Florida", "material_types": [{ "name": "Metal", "cost_per_ton": 20 }, { "cost_per_ton": 50, "name": "Food" }] } -
STATIC files problem during heroku deployment of Django web app
I am trying to deploy my Django web app but I'm getting some errors. I followed some tutorials but they did not help. Also, I have all the necessary files like Procfile, requirements.txt. Even I tried to change STATIC_ROOT to staticfiles and static it did not make sense FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_4dca6fca/static' Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets Push rejected, failed to compile Python app. Push failed settings.py DEBUG = False MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # added whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Procfile web: gunicorn portfolio.wsgi --log-file - -
Django Azure Active Directory Authentication
I am developing in Django and I'm trying to authenticate with Azure Active Directory. I've been trying for several days to get it to work, but have had a lot of problems. The package that I'm using is: django_microsoft_auth (https://django-microsoft-auth.readthedocs.io/en/latest/index.html). Operating system: Windows 10 64 bits. Django version: 3.1 Python version: 3.7.9 The problems that I have in this moment are: I have already done all the configuration in Azure and I think that it is correct. I looked at the audit logs in Azure and I can see that the connection was successful. The problem is that when I log into Azure Active Directory, I don't see any response in Django. When I try to execute the package test site I have the error 404, after having run: python -m tests.site runserver I saw the project and I can't see the file views.py. Could it be because it was done in an old version of Django? Anyway I tried to run it in django 2.2 I got the same problem. Can someone make a detailed explanation (Por example a video en Youtube or a good explication here) of how to use all the functionalities such as login, logout, user … -
Is there an HTML sanitizer library for django to block injection attacks?
I'm trying to find something that will return an exception upon finding anything that even remotely looks like HTML or Javascript. I've figured out how to do it for individual views, but it's not a scalable solution, and ultimately I need to prevent code from being saved to the database no matter what view gets targeted by the injection attack. Here is the functionality I'm looking for. ILLEGAL_CHARS = '<>[]{}():;,'.split() # bunch of code in between for value in [company_name, url, status, information, lt_type, company_source]: if any(char in value for char in ILLEGAL_CHARS): raise Exception(f"You passed one of several illegal characters: {ILLEGAL_CHARS}") I'm using django rest framework so I have to handle it on the backend. Thanks. -
Attribute Error when running Django DetailView
class results(DetailView): model = Location template_name = 'results.html' def get_object(self, **kwargs): context = super(results, self).get_context_data(**kwargs) query = self.request.GET.get('q') context.update({ 'location': Location.objects.filter(name__icontains=query) }) return context The above function aims at getting the user's input string and display it in DetailView after filtering. However, when I run it, the following error message is generated: AttributeError at /collector/results/ 'results' object has no attribute 'object' Request Method: GET Request URL: http://127.0.0.1:8000/collector/results/?q=Hong+Kong Django Version: 3.1.7 Exception Type: AttributeError Exception Value: 'results' object has no attribute 'object' Do anyone know what causes the error, and how to fix the code. Thanks! -
In django-rest-framework what is the best and secure auth library
I am working on a web app which needs auth. I know that django-rest-knox supports multiple devices at the same time but is it secure? If not which is the most secure library. Also: Is JWT secure? -
Serializer is displaying id instead of field names with Foreignkey
I'm building a Django app which uses django rest framework and it shows the lists of buses in between two stops given by the user. For this purpose, I wanted to produce a json output as shown below. [ { "id": 1, "start_time": "09:48:52", "end_time": "09:48:53", "start_stop": "A", "end_stop": "B", "bus_in_route": "Bus1" }, { "id": 2, "start_time": "10:00:00", "end_time": "10:10:00", "start_stop": "B", "end_stop": "C", "bus_in_route": "Bus2" } ] But I'm getting the output in the form of IDs. The field values in the child models (Bus, BusStop) are replaced with their IDs. [ { "id": 1, "start_time": "09:48:52", "end_time": "09:48:53", "start_stop": 1, "end_stop": 2, "bus_in_route": 1 }, { "id": 2, "start_time": "10:00:00", "end_time": "10:10:00", "start_stop": 2, "end_stop": 3, "bus_in_route": 1 } ] Code: models.py class BusStop(models.Model): # model to store several bus stops stop_name=models.CharField(max_length=255) def __str__(self): return str(self.stop_name) class Bus(models.Model): # model to store names of several buses bus_name=models.CharField(max_length=255) def __str__(self): return self.bus_name class Meta: verbose_name = 'Bus' verbose_name_plural = 'Buses' class BusRoute(models.Model): # lists out routes with start and end stops with the bus running between the stops start_stop = models.ForeignKey(BusStop, related_name='start_stop', on_delete=models.CASCADE) end_stop = models.ForeignKey(BusStop, related_name='end_stop', on_delete=models.CASCADE) bus_in_route = models.ForeignKey(Bus, related_name='bus_in_route', on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() … -
how to make Mutation by graphene-django when there are no input, output?
when user click button, I want to update A(Stock) DB by using data from B(Account) DB. when user click button, django get data(company_id and company_secret) From Account DB. and then web scraping with data. it makes new data. i want to just save new data to Stock DB. I don't want to give data to web. below code show error "GetStockMutation fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping." import graphene from .types import AccountType, StockType from .models import * from .crypt import AESCipher from graphql_jwt.decorators import login_required from .views import getStockNamu class GetStockMutation(graphene.Mutation): @login_required def mutate(self, info, **kwargs): if info.context.user.is_authenticated: user_id = info.context.user.id #data from Account DB account = Account.objects.get(user_id=user_id, company=1) #decrypt company_id = AESCipher().decrypt_str(account.company_id) company_secret = AESCipher().decrypt_str(account.company_secret) # web scraping code, amount = getStockNamu(company_id, company_secret) #save it to Stock DB stock = Stock.objects.create(user_id=user_id, code=code, amount=amount, company=1) stock.save() print(stock) else: raise PermissionError("로그인이 필요합니다.") class Query(object): pass class Mutation(graphene.ObjectType): get_account = GetaccountMutation.Field() get_stock = GetStockMutation.Field() -
Django Rest Framework: Use URL parameter in serializer
My goal is to use a URL parameter as a variable in a function and output it in the serializer. But the following solution doesnt work. Anybody know why? The URL looks like this: http://127.0.0.1:8000/v1/water-bodies/?from=2013-02-17&to=2013-02-18 models.py class Application(models.Model): """Database models for application information""" name = models.CharField(max_length=255) machine_name = models.SlugField(max_length=255, allow_unicode=True) description = models.TextField(blank=True, null=True) indice_to_use = models.ForeignKey('Indice', on_delete=models.PROTECT, blank=True, null=True) def __str__(self): return self.name views.py class DetailView(APIView): def get_serializer_context(self): context = super().get_serializer_context() context["date_from"] = self.kwargs['from'] return context def get(self, request, machine_name): application = Application.objects.get(machine_name=machine_name) serializer = OsdSerializer(application) return Response({"Everything you need to analyzing "+application.name: serializer.data}) serializer.py class OsdSerializer(serializers.ModelSerializer): bands = BandSerializer(source='indice_to_use.needed_bands', many=True) satellite = SatelliteSerializer(source='indice_to_use.satellite_to_use') indice = IndiceSerializer(source='indice_to_use') def get_alternate_name(self, obj): date_from = self.context["date_from"] '''make some additional voodoo with the date_from''' class Meta: model = Application fields = ['machine_name', 'name', 'description', 'indice', 'satellite', 'bands', 'date_from', ] -
Django - creating model instance when user is created
First of all I found some previous solutions but they are pretty outdated and not really recommended for current version of Django. What I want to do is I have a watchlist model which is bound to user by foreign key relation, what I would like to is to create a watchlist every time a user is created so it is automatically bound to the said user. I have some models and model managers but I really don't know how to connect them and would appreciate some help. I've tried a few things already but all ended up creating users but not watchlists. class UserMananger(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """create and save new user""" if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self.db) return user class User(AbstractBaseUser, PermissionsMixin): """User model""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserMananger() USERNAME_FIELD = 'email' class WatchlistManager(models.Manager): """manage creating watchlists""" def create_watchlist(self, user): watchlist = self.create(user=user) watchlist.save() return watchlist class Watchlist(models.Model): """Watchlist model""" watchlist_id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) products = models.ManyToManyField('Product') def __str__(self): return f'{self.watchlist_id} {self.user}' -
Django - page not found with Vue urls
I'm trying to create a SPA with Vue in my Django project, so that Django handles only authentication templates and the rest of the frontend is entirely Vue. I have the following: urlpatterns = [ # Some standard django templates url here for authentication.. # ... # The Vue app: path('app/', views.vueApp, name='vueApp'), ] So when the user navigates to mysite.com/app, Vue will handle the whole frontend as a SPA with its routes: //main.js const router = new VueRouter({ base: '/app', mode: 'history', routes: [ { path: '/', component: Home }, { path: '/test1', component: testcomponent }, { path: '/test2', component: test2component } ] }) The problem with my code, is that if i click on a link to test1 or to test2 from inside the Vue app, i will get redirected to testcomponent (mysite.com/app/test1) and test2component (mysite.com/app/test2); instead, if i open my browser and i navigate directly to mysite.com/app/test1 or mysite.com/app/test2 i will get a Page Not Found error by Django, i think because Django thinks i'm trying to reach a standard Django url, while instead i'm trying to reach an URL handled by my Vue app. Is there any way to solve this? Thanks in advance! -
join two table and show combined result in Django with pre defined tables in MySQL database
I have pre defined tables- functions and resources in MySQL database. I am able to connect to these individual tables separately in django but I want to join these tables based on function_id and show the combined result. [python functions defined under models.py in app][1] [python function defined under views.py in app][2] [html defined for GUI in app][3] I tried with foreign key but getting error as shown below. [enter image description here][4] PLEASE PROVIDE SOLUTION FOR JOINING TABLES AND VIEWING THE COMBINED TABLE RESULT [1]: https://i.stack.imgur.com/BDul4.png [2]: https://i.stack.imgur.com/jHfdA.png [3]: https://i.stack.imgur.com/z3Td0.png [4]: https://i.stack.imgur.com/mc9IZ.png -
Fetch all instances which have same foreign key (Migrating from Foreign Key to OneToOne)
I have two models as mentioned below: class ModelA: parent_type = CharField() # This tells us which parent is not Null parent_b = ForeignKey(to=ModelB, null=True, blank=True, related_name="child") parent_c = ForeignKey(to=ModelC, null=True, blank=True, related_name="child") parent_d = ForeignKey(to=ModelD, null=True, blank=True, related_name="child") class ModelB: data = CharField() class ModelC: data = CharField() class ModelD: data = CharField() So, recently what happend was I was trying to fetch ModelA instance where parent_b was equal to instance_b: ModelA.objects.get(parent_b=instance_b) But there were multiple instances present and hence the error (get returned 2!) So, I decided to make all parent field as OneToOne field but for that I would need to remove all the duplicate instances in ModelA. How can I achieve that, just give an example for a single parent, I can replicate it for others. Iterating through all instances will not be possible with amount of data I have. -
How do I create a child within a value in key value pair in pyrebase?
I want my data in the database to look like this >key -val1 -val2 -val3 > val_key - val4.1 - val4.2 I have added the values val1, val2,val3 using the set() but I cannot seem to figure out a way to create a key val_key as a child to the key. Please help. -
Custom decorator on class based views in django rest framework
I have the following models in my application class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) employee_name = models.CharField(max_length=500, default=0) employee_email = models.EmailField(max_length=500, default=0) employee_phone = models.CharField(max_length=500, default=0) employee_city = models.CharField(max_length=500, default=0) employee_role = models.CharField(max_length=100, default='View') class GroupModels(models.Model): model_coices = (('Product', 'Product'), ('Kit', 'Kit'), ('Vendor', 'Vendor'), ('Warehouse', 'Warehouse') , ('Flow', 'Flow'), ('ReceiverClient', 'ReceiverClient')) models = models.CharField(max_length=500, default=0, choices=model_coices) class Group(models.Model): name = models.CharField(max_length=500, default=0) emp = models.ForeignKey(Employee, on_delete=models.CASCADE) models = models.ManyToManyField(GroupModels) This is an attempt to create custom permissions for every Employee to do something Now I have the following View to create Product class ProductCreateAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer def post(self, request, *args, **kwargs): owner = request.user.pk d = request.data.copy() d['owner'] = owner serializer = ProductSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) o = Product.objects.get(id=serializer.data['id']) ow = User.objects.get(id=owner) Inventory.objects.create(product=o, quantity=0, owner=ow) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) How do I create a decorator to give access of this function to only those employees who have Product in the Group model? -
Django model field through linked relationship
Is there a way to create a "virtual" field in a model linked to a field in a relationship? e.g. I have: class User(models.Model): organization = models.ForeignKey( "Organization", ... ) Organization model have a field name so I want to add a virtual field in User model (e.g organization_name) to be able to do user.organization_name instead of user.organization.name is it possible? -
Disaply Django Fieldset values according to previously selected option?
I'm using Django's built-in Admin functionality to support a web app's admin users. So far I'm also using mixins and "rest_framework - viewsets" library to have automated a generic CRUD API. In my admin.py files, I've used fieldsets to easily create a nice form to add new records with automatically included dropdowns, checkboxes, dateboxes etc. Great. A recent concern is that some of these some item selections should dictate the available options of other items. For example, if a person selects a state/province, the list of available cities should be restricted to those in just that state/province, instead of all the cities in the database. Is there any way to implement this behavior within the fieldsets syntax / without having to abandon viewsets and revert to manually coding this behaviour? -
Direct assignment to the forward side of a many-to-many set is prohibited. Use variants.set() instead
I am trying to create an api where a user can add a product with many variants. However, when I am sending raw json data from the postman I am getting above error. As you can see, a single variants can have multiple variants so the variants ids are sent at a same time from front end. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Brand(models.Model): brand_category = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Brands" def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Collections" def __str__(self): return self.name class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) product_id = models.CharField(max_length=70,default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Meta: verbose_name_plural = "Variants" def __str__(self): return self.product_id … -
Django REST Framework token login also works with less fields than I have determined
So I have a Django REST Framework login, and I determindes, that the user need the phone_number, username and password user/serializers.py [...] class Meta: model = Account fields = ['phone_number', 'username', 'first_name', 'country', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, 'username': {'required': True}, 'phone_number': {'required': True} } [...] But with postman, I can make a post request without the phone_number field and nevertheless I get the token from the Token authentication :/ Postman: -
Django: models.BooleanField(default=False) always save value as 1(True)
I have one Boolean model field payment_received which as default value set to False. From the frontend dropdown it as coming as 0 or 1 form.No matter what value from the dropdown I select it is always saved as 1(True) in the table. I am trying to debug it & I can verify that proper value is coming from the HTML form but after cleaning is done by Django form it is always results in True value. My Model class InvoiceHeader(models.Model): class Meta: db_table = 'invoice_hdr' invoice_no = models.CharField(max_length=50) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) campaign = models.ForeignKey(CampaignHeader, on_delete=models.DO_NOTHING, null=True) invoice_date = models.DateField() invoice_amount = models.DecimalField(max_digits=11, decimal_places=2) cgst = models.DecimalField(max_digits=11, decimal_places=2) sgst = models.DecimalField(max_digits=11, decimal_places=2) igst = models.DecimalField(max_digits=11, decimal_places=2) total_amount = models.DecimalField(max_digits=11, decimal_places=2) payment_received = models.BooleanField(default=False) def __str__(self): return self.invoice_no My Form class InvoiceHeaderForm(forms.ModelForm): class Meta: fields = ('invoice_no','invoice_date','campaign','client', 'invoice_amount','cgst','sgst','igst','total_amount','payment_received') model = InvoiceHeader invoice_no = forms.CharField(max_length=50) invoice_date = forms.DateField() client = forms.ModelChoiceField(queryset=Client.objects.all()) campaign = forms.ModelChoiceField(queryset=CampaignHeader.objects.all()) invoice_amount = forms.DecimalField(max_digits=11, decimal_places=2) cgst = forms.DecimalField(max_digits=11, decimal_places=2) igst = forms.DecimalField(max_digits=11, decimal_places=2) sgst = forms.DecimalField(max_digits=11, decimal_places=2) total_amount = forms.DecimalField(max_digits=11, decimal_places=2) payment_received = forms.BooleanField() def clean_payment_received(self): val = self.cleaned_data['payment_received'] print('TEST1', val) #<---- always True return val def clean_invoice_no(self): invoice_no = self.cleaned_data.get('invoice_no') if InvoiceHeader.objects.filter(invoice_no=invoice_no).exists() and not str(self.instance): raise forms.ValidationError('Invoice … -
This page isn’t working right now If the problem continues, contact the site owner. HTTP ERROR 405. trying to fix this problem? In Django Python
I have two types of users in my AbstractUser model. One gripe is registered as KORISNIK and the second as MAJSTORI. When users under KORISNIK login, they will be available to like profiles from users MAJSTORI. Like button also have to show a number of LIKE from that profile page. But when a user clicks on the like button he is getting an error: This page isn’t working right now If the problem continues, contact the site owner. HTTP ERROR 405 I am trying to find an error but still no progress. Need some suggestions. model.py: class CustomKorisnici(AbstractUser): MAJSTOR = '1' KORISNIK = '2' USER_TYPE_CHOICE = ( (MAJSTOR, 'majstor'), (KORISNIK, 'korisnik') ) user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) class LikeButton(models.Model): user = models.ForeignKey(CustomKorisnici, on_delete=models.CASCADE) likes = models.ManyToManyField(CustomKorisnici,related_name='profile_like') def total_likes(self): return self.likes.count() view.py def LikeProfile(request,pk): like = get_object_or_404(LikeButton, id=request.POST.get('majstori_id')) like.likes.add(request.user) return HttpResponseRedirect(reverse('majstori_profile', args=[str(pk)])) class LikeMajstoriProfile(DetailView): model = LikeButton context_object_name = 'like_button' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(LikeMajstoriProfile, self).get_context_data(*args, **kwargs) stuff= get_object_or_404(LikeButton, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return context class MajstoriProfile(DetailView): model = CustomKorisnici context_object_name = 'majstori' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(MajstoriProfile, self).get_context_data(*args, **kwargs) majstori= get_object_or_404(CustomKorisnici, id=self.kwargs['pk']) context['majstori'] … -
Django ValueError: No route found for path 'ws/chat//'
I'm working on making a simple chat app using this tutorial from youtube (github link here: LINK). One potential issue is that the tutorial uses 2.x version of django but i have 3.1.7, but I had it working pretty well and was close, but then started getting this error: ValueError: No route found for path 'ws/chat//' When looking at my terminal, it keeps trying to reconnect over and over, possible becaues I'm using the ReconnectingWebSocket github javascript code. When I run redis-cli and type 'ping', I get 'PONG' in return so I think that is working properly. Below is my code: routing.py (I believe this seems most likely where the issue is) from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), #new django ] wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings') application = get_wsgi_application() settings.py: WSGI_APPLICATION = 'django_project.wsgi.application' ASGI_APPLICATION = 'django_project.asgi.application' # older version of django: 'django_project.routing.application' # Channels redis config: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } views.py: chat/views.py from django.shortcuts import render import json from django.contrib.auth.decorators import login_required from django.utils.safestring import mark_safe def index(request): return render(request, 'chat/index.html') @login_required def room(request, room_name): return render(request, 'chat/room.html', … -
Redirect a form in same URL in Django
this is my first question so if i had made any mistakes excuse me. I have a template like below : I have and Object model and for that model i am making queries and returning to template. What i am trying to is when user select one of the objects and submits, I would like to redirect to the same page so based on the object that has been choosen i will have different result for the queries because this Object model related with different models. I am trying to do this in TemplateView. So far I have override the get_context_data() method and return all the Object records for select form and I can return queries results but for just one record which I specify in view. But I couldn't find a way to submit the form and depending on that record return the queries and redirect it to the same url. I am not sure the TemplateView is the best way to do it. Because of the privacy policy of my company i can not share any files for code. I just need a guidance or a clue about my view. Any help will be so appreciated. -
Grouping user in database by category object
I have experienced issues with this code and I truly need assistance. I need to allocate client to another client in a similar category or in the class category like a line or queue. There will be a sending clients and an accepting client the sending client will demand for an installment of the sum in my class or category (for instance $5, $10, $15) at that point the framework will naturally dole out the client to another client mentioning to get an installment in that classification. Lets say it will be a line or queue and it will be the first come and first serve or first assignment. client to client payment and a class or category to classification client matching or allotting to pay every others. kindly investigate my code and tell me what to do. from django.db import models from django.contrib.auth.models import User from collections import deque d = deque('receiving') m = deque('sending') class PaymentCategory(models.Model): price = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, ) class Senders(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Receivers(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Payment(models.Model): senders = models.ForeignKey(Senders, on_delete=models.CASCADE) receivers = models.ForeignKey(Receivers, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE) def __init__(self, request, receivers=None, senders=None, *args, **kwargs): super(Payment).__init__(*args, …