Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Resetting Django Migrations in a Production System
I have been through a lot of posts/articles/trial-and-error involving Django Migrations since I started working with the framework a few years ago, so I decided I would post a self-answered question notating the proper way to accomplish the clean reset of migrations in a Production Database leaving you with the same database structure you left with, but a fresh start with initial migrations. Overall the issue is this: When you have a larger project you start to accumulate a large number of migrations for a system built with Django. This isn't normally an issue, but when you start accumulating upwards of 50-100 migration files (where a lot of them are the addition and removal of the same fields) it is nice to have a "cleaning" option as it should be well understood that if you alter migration history incorrectly, you will be left with a system that is more-or-less frozen in a previous database state where the only way to fix the issue is manual sql-based migration changes. -
Django Login_Required decoration using If condition
I have multiple links on my page which redirects user to take quiz. Some quiz requires user to login or create an account and some does not. If I use method decorator all quiz requires login and works as expected def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied try: self.logged_in_user = self.request.user.is_authenticated() except TypeError: self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: if self.logged_in_user: return render(request, self.single_complete_template_name) else: return redirect(settings.LOGIN_URL) return super(QuizTake, self).dispatch(request, *args, **kwargs) However, I would like user to redirect like how method decorator does login/?next=/quiz/f506cb92-ccca-49ff-b2e5-730bbfea6a5a/take/ but instead I get /login/ how can I use method decorator here ? Also, I would like my user to come back to the page instead of going to "/dashboard" which is my LOGIN_REDIRECT_URL. My Third requirement is that I am creating a session for anonymous quiz takers and storing all their activities in session which expires in 3 days. Incase the anonymous user decides to create an account, I would like to map his session data. Is this feasible ? Please suggest/advice. -
Reason for overflow error when saving form input to model?
I'm trying to save input from a simple form to create a new "Post" object. Models.py: class Post(models.Model): Author = models.ForeignKey(User, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, on_delete=models.CASCADE, blank=True, null=True, default=uuid.uuid1, related_name="Topic") Group = models.ForeignKey(User_Groups, on_delete=models.CASCADE, blank=True, null=True, default=uuid.uuid1, related_name="User_Groups") Content = models.TextField(max_length=100) Created = models.DateTimeField(default=timezone.now) def __str__(self): return self.Content Views.py: form = PostForm(request.POST) if request.method == 'POST': if form.is_valid(): new = form.save(commit=False) new.Topic = form.cleaned_data.get('Topic') new.Content = form.cleaned_data.get('Content') new.save() The code I have now which gives me the error: Python int too large to convert to SQLite INTEGER Other variations I have tried: form = PostForm(request.POST) if request.method == 'POST': if form.is_valid(): new = form.save(commit=False) new.Topic = form.cleaned_data.get("Topic") new.Content = form.cleaned_data.get("Content") new.save() form = PostForm(request.POST) if request.method == 'POST': if form.is_valid(): new = form.save(commit=False) new.Topic = form.cleaned_data('Topic') new.Content = form.cleaned_data('Content') new.save() After searching for similar questions, it seems that I may not be correctly creating a new instance of the form, but I am not entirely sure that is the only issue here. I am very new to Django forms, so I apologize for my lack of understanding. Any nudge in the right direction would be greatly appreciated, thanks. -
WebSocket for django rest framework
i am starting learning about web sockets with django and found Django-Channels to create a chat application, but i want to create a chat app with django Rest, wich other alternatives is there to make this? i would apreciate a guide to start learning -
How to check if the current user is the same as the foreign key in a model,
I'm trying to create a link that allows updating a model called tribe but the only person who is allowed to update the model is a foreign key called a chieftain. I'm trying to get a link to appear only when the chieftain or a superuser is currently logged in and looking at the tribe page. But I'm getting a "could not parse the remainder error" and I can't see what's wrong. models.py class Tribe(TimeStamped): name = models.CharField(max_length=200,unique=True) chieftain = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) tribe_members = models.ManyToManyField(Member) def __str__(self): return self.name[:80] def is_chieftain(self,request): if (self.chieftain == request.user): return True else: return False tribe.html {% block content %} <div class="row"> <div class="col-md-10"> {% if tribe.is_chieftan() %} <p><a href="{% url 'app:update-tribe' %}">Update tribe</a></p> {%endif%} </div> </div> ... views.py def tribeview(request, tribe_id): tribe = get_object_or_404(Tribe,pk=tribe_id) playlist = tribe.playlist_set.all() context = { 'tribe': tribe, 'playlists':playlist } return render(request, 'app/tribe.html', context) class update_tribe(UpdateView): template_name='app/update_tribe.html' form_class = UpdateTribeForm model = Tribe def get_object(self, queryset=None): return Tribe.objects.filter(chieftain=self.request.user).first() def form_valid(self, form): instance = form.instance instance.cheiftain = self.request.user instance.save() return super(update_tribe, self).form_valid(form) def get_success_url(self): return reverse('app:tribe-view', args={self.object.id}) urls.py app_name = 'app' urlpatterns = [ path('', views.index, name='index'), path('tribe/<int:tribe_id>',views.tribeview,name='tribe-view'), path('tribe/<int:tribe_id>/playlist/<int:playlist_id>',views.playlistview,name='playlist-view'), path('new_tribe', login_required(create_tribe.as_view()), name="new-tribe"), path('update_tribe', login_required(update_tribe.as_view()), name="update-tribe"), ] -
Django registration form not changing and saving to database
I'm trying to create a custom form where the user can also enter his name for instance but I am facing an issue, when the registration is done the name is not saved and I can't show it on the template. here is the code: views.py def sign_up(request): form = forms.SignUpForm() if request.method == 'POST': form = forms.SignUpForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email').lower() user = form.save(commit=False) user.username = email user.save() login(request, user) return redirect('/') return render(request, 'sign_up.html', { 'form': form }) forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=250) first_name = forms.CharField(max_length=150) last_name = forms.CharField(max_length=150) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'password1', 'password2') def clean_email(self): email = self.cleaned_data['email'].lower() if User.objects.filter(email=email): raise ValidationError("This email address already exists.") return email sign_up.html <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-warning btn-block">Sign Up</button> <p class="text-center mt-3" > Already have an account? <a href="/sign-in/?next={{ request.GET.next }}"><b>Sign In</b></a> </p> </form> The html is showing me also the username, which i wanted to remove and login with email address. But nothing gets saved in database... -
How can I create an object in another model based off parent model?
I'm having trouble trying to implement (and really map out) a new model object based off a parent model. The Bucket model below has a category field based off two category_options. class Bucket(models.Model): category_options = ( ('personal', 'Personal'), ('social', 'Social'), ) class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') admin_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='admin_user') guest_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='guest_user', blank=True) category = models.CharField(max_length=30, choices=category_options) ... objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def save(self, *args, **kwargs): if self.stock_list: self.stock_count = len(self.stock_list) super().save(*args, **kwargs) else: super().save(*args, **kwargs) I would like to create a new object in a completely different model, SocialBucket, when the Bucket model instance is selected as a social category based off the category field above: class SocialBucket(models.Model): bucket = models.ForeignKey(Bucket.objects.id, on_delete=models.CASCADE, related_name='social_buckets) How can I go about populating my SocialBucket model with new objects based off it's parent, Bucket, model? -
How to use python-socketio with django and reactjs?
I am getting this error Not Found: /socket.io/ HTTP GET /socket.io/?EIO=4&transport=polling&t=NSwqecY 404 [0.02, 127.0.0.1:51874] What should I do? Or any other library/method recommended. Thanks in advance.. -
Creating view with foreign key model django restframework
I'm fairly new with the django restframework. I am trying to create a serializer and a view for a model that has a foreignKey. Models.py class Job(models.Model): """A Job used to create a job posting""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) description = models.TextField() job_type = models.CharField(max_length=12, choices=JOB_TYPE_CHOICES, default='Full-Time') city = models.CharField(max_length=255) state = models.CharField(max_length=255) created_date = models.DateField(auto_now=False, auto_now_add=True) salary = models.CharField(max_length=255) position = models.CharField(max_length=255) employer = models.CharField(max_length=255) is_active = models.BooleanField(default=True) def __str__(self): return self.description[:50] class Applicant(models.Model): """A applicant that can apply to a job""" job = models.ForeignKey(Job, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=254) phone_number = PhoneNumberField() resume = models.FileField(upload_to=resume_file_path, validators=[validate_file_extension]) def __str__(self): return self.first_name The idea is that Applicant will be able to apply to Job. I can't seem to figure out how to get the Job id when a Applicant is applying to job. serializers.py class JobSerializer(serializers.ModelSerializer): """Serializer for tag objects""" class Meta: model = Job fields = ('id', 'description', 'job_type', 'city', 'state', 'salary', 'position', 'employer', 'created_date', 'is_active') read_only_fields = ('id',) def create(self, validated_data): """Create a job posting with user and return it""" return Job.objects.create(**validated_data) class ApplyJobSerializer(serializers.ModelSerializer): """Serializer for applying to jobs""" class Meta: model = Applicant fields = ('id', 'first_name', 'last_name', 'email', 'phone_number', … -
Access the object created with Creatiview
I need to access a newly created object with CreateView to be able to display it in a pdf. The user must complete a form and that form after being created must be shown in pdf. I need to know how to pass the data of the newly created form to be able to pass it to pdf. This is the code to generate the pdf def render_presupuesto_pdf(request,*args, **kwargs): template_path = 'systemapp/x.html' context = {'myvar': 'pdf content'} # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') #if donwnliad: # response['Content-Disposition'] = 'attachment; filename="report.pdf"' #if show pdf response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF(html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response And this is my code to create the form class AddPresupuestoCreateView(CreateView): '''Formulario para agregar presupuesto''' model = Presupuesto fields = ('cliente','vehiculo','fecha_entrada','fecha_entrega','precio', 'descuento','iva_porcentaje','total','sub_total','obs','comision',) template_name = 'systemapp/content/add_presupuesto.html' def get_context_data(self, **kwargs): # Sobreescribimos get_context_data para asegurarnos de que nuestro # formset sea renderizado data = super().get_context_data(**kwargs) if self.request.POST: data["add_trabajo"] = AddJobFormset(self.request.POST) data["add_material"] = AddMaterialesFormset(self.request.POST) else: data["add_trabajo"] … -
Python: errno2 no such file or directory in google colab
pip install django !django-admin startproject PyShop !python manage.py runserver ----:In the last line of code, I should be getting some kind of a web link as an output but i get this location error. Is there any syntax error -
How to filter REST API urls via date range?
How can I filter dates by selecting buttons on my frontend(vue.js), like if I select January 2020, it will display it january. or else if I select June 2020, it will display my data from June 2020. How to query it on django.objects.filter and call it on the rest api? Thanks! @views.py class RainfallView(generics.ListCreateAPIView): current_year = datetime.now().year serializer_class = RainfallSerializer queryset = Rainfall.objects.filter(date_year=current_year, date_month='01') def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = RainfallSerializer(queryset, many=True) return Response(serializer.data) @models.py class Rainfall(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) -
How to store data and display them in another view? Django
I have a simple sport events app. I log in as an user and I have a list of events I can join. When i join event, member value current_member is incremented. I have another view which contain list of events created by currently logged user. What I want to do more in this view is display also joined events. In my_events.hmtl (code below) i want to display in loop those events. How can I do it? models.py class Event(models.Model): SPORT = ( ('Football', 'Football'), ('Volleyball', 'Volleyball'), ('Basketball', 'Basketball'), ('Futsal', 'Futsal'), ('Tennis', 'Tennis'), ('Handball', 'Handball'), ('Ice Hockey', 'Ice Hockey'), ('Paintball', 'Paintball') ) creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) sport = models.CharField(max_length=20, null=True, choices=SPORT) event_name = models.CharField(max_length=30) event_date = models.DateTimeField(default=date.today()) end_event_date = models.DateTimeField(default=date.today()) current_members = models.IntegerField(default=1) total_members = models.IntegerField(default=0) event_location = models.CharField(max_length=50) cost = models.FloatField(default=0, max_length=5) description = models.CharField(max_length=300, blank=True) views.py @login_required(login_url='login') def join_event(request, pk): event = Event.objects.get(id=pk) if request.method == "POST": event.current_members += 1 if event.current_members <= event.total_members: event.save() return redirect('/') else: messages.error(request, 'Event is full!') context = {'event': event} return render(request, 'events/join_event.html', context) @login_required(login_url='login') def my_events(request): events = request.user.event_set.all() print('EVENTS', events) context = {'events': events} return render(request, 'events/my_events.html', context) my_events.html {% extends 'events/main.html' %} {% block content %} <div class="row"> … -
How can i redirect to next url via POST method with Django generic.CreateView?
Pseudocode: 1.User Signup via following class-based view. 2.If signup success,then auto login and redirect to next url(enrollment) via GET method. My problem is here. how can i redirect to next url(enrollment) via POST method? class StudentRegisterView(generic.CreateView): form_class = StudentRegisterForm template_name = 'attendance_system/register.html' success_url = reverse_lazy("enrollment") def form_valid(self,form): valid = super(StudentRegisterView,self).form_valid(form) username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username,password=password) login(self.request,user) return valid -
Django - joining a nested group_by
I want to aggregate data from 2 tables (A, B) which are linked via a 3rd table (KeyModel). I know about the use of Django's queryset methods 'values' and 'annotate', and managed to create complex queries with it, but this one I got stuck with: model A key = ForeignKey(KeyModel) value_1 = IntegerField() model B key = ForeignKey(KeyModel) value_2 = IntegerField() model KeyModel <some irrelevant fields> data - model/ table A key_id | value_1 4711 | 100 data - model/ table B key_id | value_2 4711 | 100 4711 | 100 4711 | 100 I like to achieve this result: -- key_id | sum_value_1 | sum_value_2 -- 4711 | 100 | 300 The following django/ python code generates the wrong SQL: qs = table_a.objects.filter(key_id=4711) qs = qs.values('key_id') qs = qs.annotate(sum_value_1=SUM(value_1)) qs = qs.annotate(sum_value_2=SUM(KeyModel__table_b__value_2)) will generate SELECT A.key_id, SUM(A.value_1) AS sum_value_1, SUM(B.value_2) AS sum_value_2 FROM table_a A JOIN table_b B ON B.key_id=A.key_id WHERE A.key_id=4711 GROUP BY A.key_id; But this is not what I need. The join triples the rows from table A, so the result is key_id | sum_value_1 | sum_value_2 4711 | 300 | 300 A 'slightly' changed SQL is doing what I want: SELECT A.key_id, SUM(A.value_1) AS sum_value_1, V.sum_value_2 … -
Django get data on a condition in django Admin
I'm working on a project using Django(3) in which I have created a model that has various ForeignKey fields. Now in the admin, I want to check if these ForeignKey fields are None or not, How can I do that? Here's what I have tried: From models.py: class ReportsModel(models.Model): cdr_report = models.OneToOneField(CurrencyDistributionModel, on_delete=models.CASCADE, null=True, default=None) cme_report = models.OneToOneField(CurrencyManagementExpenditureModel, on_delete=models.CASCADE, null=True, default=None) cps_report = models.OneToOneField(CurrencyProcessingStorageModel, on_delete=models.CASCADE, null=True, default=None) cma_report = models.OneToOneField(CurrencyManagementAssetsModel, on_delete=models.CASCADE, null=True, default=None) def __str__(self): if self.cdr_report is not None: return self.cdr_report.RequestId elif self.cme_report is not None: return self.cme_report.RequestId elif self.cps_report is not None: return self.cps_report.RequestId elif self.cma_report is not None: return self.cma_report.RequestId From admin.py: class ReportAdmin(ReverseModelAdmin): report = None if ReportsModel.cdr_report is not None: report = 'cdr_report' elif ReportsModel.cme_report is not None: report = 'cme_report' elif ReportsModel.cps_report is not None: report = 'cps_report' elif ReportsModel.cma_report is not None: report = 'cma_report' search_fields = ['name'] inline_reverse = [report] # inline_reverse = ['cdr_report', 'cme_report', # 'cps_report', 'cma_report'] inline_type = 'stacked' admin.site.register(ReportsModel, ReportAdmin) But in admin, it didn't work, it only shows the correct value for cdr_report not for others. I want to display only the report which is not None. How can I achieve that? -
Django: how to increase object value
I'm trying to implement a simple 'like' button, however, the value of the object is not changing. I have only a week of experience with django, any help is appreciated! model> class Mainnews(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to = 'photos/%Y/%m/%d/') is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) views_counter = models.IntegerField(default=0) likes = models.IntegerField(default=0) def __str__(self): return self.title html> <form action = "{% url 'like' %}" method = "POST"> {% csrf_token %} <input name = 'like' type = 'number'> <button type ='submit'>submit</button> </form> view> def like(request): if request.method == 'POST': likes = request.POST['like'] likes += 1 theLike= Mainnews.likes(likes = likes) theLike.save() url> on like redirect to homepage path('', like, name = 'like'), -
Cart matching query does not exist
I'm creating a ecommerce website with python Django. Mean While raised this error " Cart matching query does not exist ". What can I do to solve this error. views.py class AddToCartView(TemplateView): template_name = "add_to_cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) product_id = self.kwargs['pk'] produc_obj = Product.objects.get(id=product_id) cart_id = self.request.session.get("cart_id", None) # Old Cart if cart_id: cart_obj = Cart.objects.get(id=cart_id) prd_in_this_cart = cart_obj.cartitem_set.filter(product=produc_obj) # Item already exist in cart if prd_in_this_cart.exists(): cartproduct = prd_in_this_cart.last() # first() prd_in_this_cart.quantity += 1 cartproduct.total += produc_obj.amazon_rate cartproduct.save() cart_obj.total += produc_obj.amazon_rate cart_obj.save() # Item already exist in cart else: cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() # New Cart else: cart_obj = Cart.objects.create(total=0) self.request.session["cart_id"] = cart_obj.id cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() return context -
get results from one view to another view in django
I have two views. 1 gets results from search, 2 shows results in html file. I know I can combine 2 views to 1, after getting results and showing it. I need to separate two function because after getting results from 1, I can show it, using it with pagination and using it with next/back function I try to use request.session to get data from view 1 to view 2 but It fails View 1 def list_contract_test(request): results = {} if request.method == 'GET': query1= request.GET.get('search1') query2= request.GET.get('search2') submitbutton= request.GET.get('submit') if query1 is not None: lookups_contract= Q(contract__icontains=query1) lookups_name = (Q(name__icontains=query2.upper())|Q(name__icontains=query2.lower())) results= Contracts.objects.filter(lookups_contract,lookups_name).distinct() #context['contract_posts'] = contract_posts request.session['results'] = results return render(request, "customer2.html",results) else: results= Contracts.objects.all() #context['contract_posts'] = contract_posts self.request.session['results'] = results #global val1 #def val1(): # return results return render(request, 'customer2.html',results) else: return render(request, 'customer2.html') View 2 def get_data(request): contract_posts_test = request.session['results'] #contract_posts_test = val1() context['contract_posts_test'] = contract_posts_test return render(request, 'customer2.html', context) In my template customer2.html {% for contract in contract_posts_test %} <tr> <td><a href="{% url 'contract_detail' contract_id=contract.contract %}">{{contract.contract}}</a></td> <td>{{ contract.name }}</td> <td>{{ contract.debt }}</td> <td>{{ contract.created_at}} </tr> {% endfor %} In my url path("customer2/",get_data,name="get_data"), The error shows: ...\views.py, line 196, in get_data return render(request, 'customer2.html',results) else: return render(request, 'customer2.html') #request.session['list'] … -
How do I make a model fields into a dropdown choice in another model?
I want to create a form which has the fields of another model.The dropdown items will be the fileds not the data in that fields Is it possible? and how? -
Export all list_display fields to csv in django admin
I'm using the recipe at https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field_names]) return response export_as_csv.short_description = "Export Selected" which works great except it doesn't export all the columns I see in the admin panel. I have added some extra columns like this class MeetingAdmin(admin.ModelAdmin, ExportCsvMixin): actions = ["export_as_csv"] list_display = ( "__str__", "expert_network", ) def expert_network(self, obj): if obj.expert: return obj.expert.network.name else: return "-" is it possible to improve the ExportCsvMixin to also export the callable list_display fields? -
Reverse for 'signup_view' with arguments '(None,)' not found. 1 pattern(s) tried: ['accounts/signup_view/(?P<user_id>[0-9]+)/$']
I am building a BlogApp AND build a Signup view BUT when i open browser then it shows me :- Reverse for 'signup_view' with arguments '(None,)' not found. 1 pattern(s) tried: ['accounts/signup_view/(?P<user_id>[0-9]+)/$'] views.py def signup_view(request,user_id): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('mains:profile',user_id=user_id) else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) urls.py path('signup_view/<int:user_id>',views.signup_view, name='signup_view'), login.html <a href="{% url 'users:signup_view' user.id %}">Register Here.</a> Problem When i open browser then it is keep showing me Reverse for 'signup_view' with arguments '(None,)' not found. 1 pattern(s) tried: ['accounts/signup_view/(?P<user_id>[0-9]+)/$']. I don't know what am i missing. Any help would be appreciated. Thank You in Advance -
Django Channels - WebSockets: Cannot find websocket_accept method defined anywhere
Might be a silly one, but I really can't figure this out. I am going through the source code of Django Channels in order to understand which is the best way to manually terminate an open web socket connection from the server. Then I noticed that the accept method of the WebsocketConsumer sends a message of type websocket.accept: https://github.com/django/channels/blob/master/channels/generic/websocket.py#L52 According to Django Channel docs, that means there is somewhere a method named websocket_accept that will be invoked on the consumer: Consumers are structured around a series of named methods corresponding to the type value of the messages they are going to receive, with any . replaced by _. But I cannot find a websocket_accept method anywhere in the repository (I even cloned it and grep'ed to it). So I am wondering how does this work. Have I interpreted wrong or the docs mean something different (eg. some other method should be called instead of the one I think it will)? Thanks -
Invalid Syntax error while installing Django in linux
I am trying to install Django in linux.I have already installed python. Error I am getting when executed "pip install Django" or "pip3 install Django" pip install django Traceback (most recent call last): File "/home/mandar/.local/bin/pip", line 7, in <module> from pip._internal.cli.main import main File "/home/mandar/.local/lib/python3.5/site-packages/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax -
Pagination Based on Queryset
I'm trying to implement pagination on my Django app that is based on the filtered queries, but the pagination shows all the objects even the ones not filtered, any insight on what I'm doing wrong? Any assistance would be appreciated. def searchPropertyListView(request): city = City.objects.all().annotate( num_property=Count("property")).order_by("-num_property") categories = Category.objects.all() purposes = Purpose.objects.all() featured = list(Property.objects.filter(featured=True)) shuffle(featured) querySet = Property.objects.all() city_or_neighborhood = request.GET.get('city_or_neighborhood') category = request.GET.get('category') purpose = request.GET.get('purpose') if city_or_neighborhood != '' and city_or_neighborhood is not None: querySet = querySet.filter(Q(city__title__icontains=city_or_neighborhood) | Q(neighborhood__title__icontains=city_or_neighborhood) ).distinct() if category != '' and category is not None: querySet = querySet.filter(category__title=category) if purpose != '' and purpose is not None: querySet = querySet.filter(purpose__title=purpose) paginator = Paginator(querySet, 1) page = request.GET.get('page') try: querySet = paginator.page(page) except PageNotAnInteger: querySet = paginator.page(1) except EmptyPage: querySet = paginator.page(paginator.num_pages)