Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django tasks done associated with a project
I want to obtain the percentage of tasks performed associated with a project my model class Srv(models.Model): srv_year = models.CharField(max_length=4) slug = AutoSlugField(populate_from = 'srv_year', always_update = True) class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null = True, blank = True) project_title = models.CharField(max_length=200, unique = True) slug = AutoSlugField(populate_from = 'project_title', always_update = True) class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null = True, blank = True) todo_title = models.CharField(max_length=200) slug = AutoSlugField(populate_from = 'todo_title', always_update = True, null = True) My view class index(ListView): model = Srv template_name = 'srv_list.html' ordering = ['srv_year'] def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['get_percentage_done'] = Todo.objects.filter(state = True).count() * 100 / Todo.objects.all().count() return context But with this context['get_percentage_done'] = Todo.objects.filter(state = True).count() * 100 / Todo.objects.all().count() I get all the system tasks -
django.db.models has no attribute "PublishedManager"
I'm following along in a book and came across an error I can't seem to solve on my own. Im trying to add a model manager so I can search only published blog posts. In my blog app, I first added the custom manager class as shown below: class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') I then added the following lines to my Post model. class Post(models.Model): objects = models.Manager() #default manager published = PublishedManager() #new manager The error I am getting is: AttributeError: module 'django.db.models' has no attribute 'PublishedManager' Any help greatly appreciated, I have struggling trying to figure out what is wrong for quite a while now! -
Is it possible to use the same Django models/views/etc with two different databases?
I have a Django application and I want to host it using 2 databases - one for test data and the other with real data, with the database path defined by the url accessing the site - ie test.mysite.com versus mysite.com. I looked through the Django docs at using multiple databases and routers, but those examples and others use the databases to split up the apps. For example, all data from the Customer model goes in the customer db, and all data from the User model goes in the user db as defined in settings.py. Is there a way to use one django app and configure two databases, with the db selection based on the url? Perhaps the best solution is to set up 2 virtual environments, one for mysite.com, and the other for test.mysite.com, and let apache's virtual hosts be the "router". As the app(s) evolve, I can clone the sites from the master git repo. Thanks for your thoughts! Mark -
Django Query across multiple model relationships
I'm trying to make a query for a set of instances in the ActivityPartsModel filtered by a group. When I try to run the following. I am left with an Attribute Error: "'QuerySet' object has no attribute 'activity'" activities = GroupActivityModel.objects.filter(group=id) parts = ActivityPartModel.objects.filter(activity=activities.activity.all()) print(parts) How would I go about filtering ActivityPartModel with a GroupModel ID/instance class ActivityModel(models.Model): activityName = models.CharField(max_length=100) description = models.CharField(max_length=200) workCenter = models.ForeignKey(Group, on_delete=models.PROTECT) history = HistoricalRecords() class ActivityPartModel(models.Model): activity = models.ForeignKey(ActivityModel, on_delete=models.PROTECT) part = models.ForeignKey(PartModel, on_delete=models.PROTECT) quantity = models.IntegerField(default=1) increment = models.BooleanField(default=False) # TRUE/FALSE used to represent parts ActivityPartModel/produced order = models.IntegerField(blank=False, default=100_000) location = models.TextField(max_length=50, null=True) history = HistoricalRecords() class GroupModel(models.Model): groupName = models.CharField(max_length=50) class GroupActivityModel(models.Model): group = models.ForeignKey(GroupModel, on_delete=models.PROTECT) activity = models.ForeignKey(ActivityModel, on_delete=models.PROTECT) order = models.IntegerField(blank=False, default=100_000) groupName = models.CharField(max_length=50) -
Django: checking is_null in values() queryset
I have this queryset: output = self.filter(parent=task, user=user).values( 'label', 'minutes_allotted', 'days_to_complete', 'pk', number_of_children=Count('children') ) It does the job. But I'm really only using it to check if an object has children (I don't really care about how many it has). Is there a way to use isnull here? I've tried: output = self.filter(parent=task, user=user).values( 'label', 'minutes_allotted', 'days_to_complete', 'pk', 'children__isnull' ) and: output = self.filter(parent=task, user=user).values( 'label', 'minutes_allotted', 'days_to_complete', 'pk', is_not_parent='children_isnull' ) but neither were correct. -
JSON API - Passing an iterable object from Python file to Java Script File (Django)
Project3 CS50's Web Programming with Python and JavaScript Harvard EDX It was supposed to give me back a nested loop, however, it doesn't happen. It was also supposed to show a stack of divs in the html file. Each one containing sender, subjet and button 'archive' for each element in the loop. One email per div. What happened ??? -
How to restart Dramatiq in Windows on code update or server restart?
I am using Django-Dramatiq with Dramatiq and RabbitMQ. I have it all working, but I am not sure the proper way to deploy to a Windows Server. If the server restarts, how do I make sure that the workers start again? If I deploy new code changes, what is the best way to stop and start the workers again to get the changes? -
adding a new field age in admin page
i have a family_member model in django that has a set of attributes, i want to calculate age based on date_of_birth, so basically i want to add a column next to date_of_birth with age, and what i've done models.py class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) relationship = models.ForeignKey(Relationship, on_delete=models.PROTECT) dependant_child_age_range = models.ForeignKey(DependantChildAgeRange, null=True, blank=True, on_delete=models.PROTECT) care_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) income = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True, help_text='''Excluding: 1. Maintenance 2. FTB-A & FTB-B 3. CRA but incl. ES(1) for all payments and FTB-A & FTB-B''') rent_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) @property def age(self): from math import floor return floor( (datetime.today().date() - self.date_of_birth).days / 365.25) admin.py class FamilyMemberInline(admin.TabularInline): def formfield_for_foreignkey(self, db_field, request, **kwargs): action = request.META['PATH_INFO'].strip('/').split('/')[-1] if action == 'change': transaction_id = request.META['PATH_INFO'].strip('/').split('/')[-2] if db_field.name == "family_group": kwargs["queryset"] = FamilyGroup.objects.filter(transaction=transaction_id) return super(FamilyMemberInline, self).formfield_for_foreignkey(db_field, request, **kwargs) model = FamilyMember extra = 0 def sufficient_info_provided (self, obj): return obj.sufficient_information_provided sufficient_info_provided.boolean = True def get_age(self, obj): return obj.age readonly_fields = ['sufficient_info_provided','get_age', ] but now i get this error :`unsupported operand type(s) for -: 'datetime.date' and 'NoneType' i've tried to include If statment in … -
How do I fix bad credential error in django
I have created a contact form that is suppose to send that message via email as well as maintain those messages in database. I have added the following in settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') And the following code in views.py from django.core.mail import send_mail from django.conf import settings def contact(request): if request.method == 'POST': name = request.POST.get("name") email = request.POST.get("email") desc = request.POST.get("desc") instance = Contact(name=name, email=email, desc=desc) instance.save() desc = request.POST['desc'] send_mail('Contact Form', desc, settings.EMAIL_HOST_USER, ['********@gmail.com'], fail_silently=False) Its not giving any errors in command prompt. However its giving the following error when I am submitting the form SMTPAuthenticationError at /contact/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials s1sm259896wrv.97 - gsmtp') -
Can a MERN stack developer pentest a website using django or java in its backend?
Lets say there is a professional MERN stack developer who knows pentesting too. Can he hack a website which uses django or java in its backend using his general understanding of website working ? Or should he learn python or java to understand it and hack it ? -
Nginx Bad Request (400) using upstream server in proxy_pass
I am really confused... On IP4 123.456.789.123 I have a django app running. On my local computer I create a simple nginx image with docker: FROM nginx COPY default.conf /etc/nginx/conf.d/default.conf and run it. In default.conf I use: server { listen 80; location /api { proxy_pass http://123.456.789.123; } } This version works just fine. Entering 127.0.0.1/api will lead me to my django app online.. But using: upstream djangpapp { server 123.456.789.123; } server { listen 80; location /api { proxy_pass http://djangpapp; } } will give me a bad request 400. I dont understand why. this: proxy_set_header Host $http_host; does not work, even thou it seem'd to be the solution for some people.. it even gives me a 400 in the otherwise working 1st version. -
users to own ther data in django
i want users to own their data but this is the error i keep getting " Cannot resolve keyword 'merchant' into field. Choices are: date_added, id, order, order_id, product, product_id, quantity" models.py class Merchant(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True) class Product(models.Model): merchant=models.ForeignKey(Merchant, on_delete=models.CASCADE) class OrderItem(models.Model): product=models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) views.py def users_homepage(request): itemsordered=OrderItem.objects.filter(merchant=request.user.merchant).order_by('date_added') thanks beforehand. -
Create Django model at runtime for testing purposes
The idea is to be able to write tests for my abstract models, since they cannot be instantiated or mapped to a table on the (test) database. I'm trying to create the table dynamically from a model, ideally enclosed in a with block. To do that, I dynamically create a model that inherits from the abstract model and execute the SQL to create the associated table (on __enter__), and delete the table when I'm done (on __exit__). I've tried several options: This, which fails with the error AttributeError: 'DatabaseCreation' object has no attribute 'sql_create_model'. It appears that sql_create_model is probably from an older version of Django. Doesn't look viable. This, which fails with the error django.db.utils.NotSupportedError: SQLite schema editor cannot be used while foreign key constraint checks are enabled. Make sure to disable them before entering a transaction.atomic() context because SQLite does not support disabling them in the middle of a multi-statement transaction. It actually looks like a valid solution, but fails with SQLite3. As you can see here, the implementation is trying to disable constraint checking, but failing, for some reason. This option appears as if it could be viable if I could figure out why disabling constraints checking … -
How to access data across M2M tables in Django?
What is the 'best practice' way of accessing data across a 1 (or more) many-to-many tables? This is incredibly difficult for me as I am not sure what I shuld be googling/looking up. I have attached a diagram of my data model. I am able to query data for 'C' related ot a user, by utilizing serializers. there has to be a simpler way of doing this (I'm hoping). Doing it with serializers seems incredibly limiting. I'd like to access a user's 'B' and 'C' and transform the object to only have a custom structure and possible unique values. Any direction is much appreciated. Pretty new to Django, so I apologize for this newb type of question. -
AttributeError: 'list' object has no attribute 'all' when connecting my model to admin
Getting an 'list' object has no attribute all error based on my function in my admin class. def get_stocks(self, obj): return "\n".join([s.stock_list for s in obj.stock_list.all()]) The error seems very trivial, in fact I know what the problem is, but I don't get why Im getting the error for this specific function and not the one above, aka def get_users() Here is my admin.py file @admin.register(models.Bucket) class BucketAdmin(admin.ModelAdmin): list_display = ('id','owner','category', 'get_users', 'name', 'created', 'slug','stock_count','get_stocks', 'about') prepopulated_fields = {'slug': ('name',), } def get_users(self, obj): return "\n".join([u.user_name for u in obj.users.all()]) print(u) def get_stocks(self, obj): return "\n".join([s.stock_list for s in obj.stock_list.all()]) Here is the model in question class Bucket(models.Model): options = ( ('personal', 'Personal'), ('social', 'Social'), ) class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(Bucket.owner) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') users = models.ManyToManyField(settings.AUTH_USER_MODEL) category = models.CharField(max_length=30, choices=options) name = models.CharField(max_length=35) created = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, blank=True, null=True) stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True) about = models.CharField(max_length=75) objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def total_stocks_calc(self): self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True)) self.save() def get_absolute_url(self): return reverse("bucket:bucket-view", kwargs={"slug": self.slug}) def __unicode__(self): return self.stock_list Full TraceBack: File "/home/andres/stockbuckets.io/venv/lib/python3.8/site-packages/django/db/models/options.py", line 575, in get_field return self.fields_map[field_name] KeyError: 'get_stocks' During handling of the above … -
ModuleNotFoundError: No module named 'jinja2' during deployment of django project on heroku
Well Here I am trying to deploy my first django app and getting error :ModuleNotFoundError: No module named 'jinja2'. I don't know where jinja came from. In my requirement file there is no jinja. Tell me if you know how to fix it. I shall be very thankful to you. trackback: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 991, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 783, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/app/.heroku/python/lib/python3.8/site-packages/knox/__init__.py", line 2, in <module> remote: from … -
Model doesn't show up in admin
I am currently working on a science django blog. I've finished coding it all and I realized that the models items overview and content don't appear in my django.admin. Here's an image so you can see. I know there are other threads related to it. However, I couldn't find the solution in those. Models.py: class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey( 'self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey( 'self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) Admin.py: from django.contrib import admin from .models import Author, Category, Post, Comment, PostView # Register your models here. admin.site.register(Author) admin.site.register(Category) admin.site.register(Post) admin.site.register(Comment) admin.site.register(PostView) Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms', 'tinymce', 'marketing', 'posts' ] And urls.py: urlpatterns = [ path('admin/', admin.site.urls), By the way, the models.py is in the app Posts. Just in case somebody needs this information. -
Getting a foreign key value to edit a post
I have got 2 tables in my models: class Post(models.Model): title = models.CharField(max_length=100) content = HTMLField() class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to = 'post') What I am trying to do is display information about the post, including the images to be able to edit them. Here's my views: def edit_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) form2 = ImageForm(request.POST, instance=?) try: if form.is_valid(): form.save() messages.success(request, 'Ok') except Exception as e: messages.warning(request, "No") else: form = PostForm(instance=post) form2 = ImageForm(request.POST, instance=?) context = { 'form':form, 'post': post, } return render(request, "update.html", context) What would be my instance to populate the ImageForm? I have tried: image = get_object_or_404(ImagePost, pk=pk) form2 = ImageForm(request.POST, instance=image) But I was getting this error: No PostImage matches the given query. -
Having problems dockerizing my django project
I am following along in the Django for Professionals book and I am stuck at the first chapter where you create a django project and app using pipenv and then Dockerizing it when running docker build . I get the following error => ERROR [4/5] RUN pip install pipenv && pipenv install --system I ignored that, made a docker-compose.yml file and ran docker-compose build and got this error: ERROR: Exception: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 438, in _error_catcher yield File "/usr/local/lib/python3.8/site-packages/pip/_vendor/urllib3/response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "/usr/local/lib/python3.8/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 62, in read data = self.__fp.read(amt) File "/usr/local/lib/python3.8/http/client.py", line 458, in read n = self.readinto(b) File "/usr/local/lib/python3.8/http/client.py", line 502, in readinto n = self.fp.readinto(b) File "/usr/local/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) File "/usr/local/lib/python3.8/ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "/usr/local/lib/python3.8/ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 224, in _main status = self.run(options, args) File "/usr/local/lib/python3.8/site-packages/pip/_internal/cli/req_command.py", line 180, in wrapper return func(self, options, args) File "/usr/local/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 320, in run requirement_set = resolver.resolve( File "/usr/local/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/resolver.py", … -
DJANGO OPENCENSUS url field in request data too long
I am having a similar issue to this question since adding App Insights to my application. It may be related to this other question also, but neither of them are directly related to App Insights and neither have solutions. This is the error from the django-tasks.log Data drop 400: 100: Field 'url' on type 'RequestData' is too long. Expected: 2048 characters, Actual: 3701 {'iKey': <uuid>, 'tags': {'ai.cloud.role': 'manage.py', 'ai.cloud.roleInstance': <instance>, 'ai.device.id': <device>, 'ai.device.locale': 'en_US', 'ai.device.osVersion': '#1 SMP Tue Aug 25 17:23:54 UTC 2020', 'ai.device.type': 'Other', 'ai.internal.sdkVersion': 'py3.6.12:oc0.7.11:ext1.0.4', 'ai.operation.id': 'fcbe18bf6ca9036aa4546af171f3e877', 'ai.operation.name': 'GET /<my_url>/'}, 'time': '2020-12-15T17:58:36.498868Z', 'name': 'Microsoft.ApplicationInsights.Request', 'data': {'baseData': {'id': '116a0658b513bdb9', 'duration': '0.00:00:00.096', 'responseCode': '200', 'success': True, 'properties': {'request.name': 'GET /<my_url>/', 'request.url': 'https://<my host>/<my_url>/?<my very long query string>', 'django.user.id': '90', 'django.user.name': '100044505'}, 'ver': 2, 'name': 'GET /<my_url>/', 'url': 'https://<my host>/<my_url>/?<my very long query string>', 'source': None, 'measurements': None}, 'baseType': 'RequestData'}, 'ver': 1, 'sampleRate': None, 'seq': None, 'flags': None}. I could rewrite the app to use shorter queries, but that seems like the wrong answer. Is there a way to configure djang to support long URLs. -
Django suggestions / autocomplete - remote API (geocoding, forward address, map)
in my spare time I am learning django. I'm making a site and currently I'm stuck, already for two days. In "search module" I try to parse address input from user and provide suggestions on city/town based on that input. Currently I am using ajax, jquery and selectize plugin in my html template. I know that this is not a long term solution as API key (google maps api key) is open to public and probably not the safest way to transfer lat/long data into backend. The reason that I am using API is that I get latitude and longitude for certain address and I need to get it into backend. I've tried to search on github for correct repo, nevertheless most of them are not up to date with django 3.1. What other solution can be used with django to call ajax? tldr: suggestion/autocomplete based on user query; remote api> reverse lookup address to latitude and longitude> latitude and longitude to backend -
Django model - hours calculator
Good evening ! I have a question. I can not find over the internet how to solve my problem. I want to have database row in which i can put hours - not datetime or time but for example 01:34 ( 1 hour 34 minutes). I don't know how to deal with it can someone help ? Regards -
Django - How do I render a parent object in template?
I need to display some product's supplier, next to {{product.description}} but I can't get it to show on my table. models.py class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Product(models.Model): sku = models.IntegerField(null=True) description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField(null=True, max_length=99, unique=True) image = models.ImageField(null=True, blank=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True) def __str__(self): return self.description views.py def products(request): products = Product.objects.all() suppliers = Supplier.objects.all() context = {'products': products, 'suppliers': suppliers} return render(request, 'crmapp/products.html', context) products.html <tr> {% for product in products %} <td>{{product.id}}</td> <td><h6><strong>{{product.description}}</strong></h6></td> <td >{{products.supplier}}</td> <td>£{{product.costprice |floatformat:2}}</td> <td>£{{product.retailprice |floatformat:2}}</td> <td>{{product.barcode}}</td> </tr> {% endfor %} -
(Django) UpdateView query only working sometimes
I have a school management app that has a feature to drop a student or teacher from a particular course. The problem is it only works with some users and not others. In my urls.py, I have the following: path('profile/<int:pk>/drop_session/<int:pk2>', user_views.DropStudentFromSession.as_view(), name='drop_student_session'), Then in my views.py, this is my CBV for dropping a student: class DropStudentFromSession(UserPassesTestMixin, UpdateView): model = Session template_name = 'users/drop_student_session.html' fields = [] def test_func(self): return True if self.request.user.groups.filter(name='Admin').count() > 0 else False def handle_no_permission(self): return redirect('denied') def form_valid(self, form): course = get_object_or_404(Session, pk=self.kwargs.get('pk2')) user = get_object_or_404(User, pk=self.kwargs.get('pk')) user.student.enrolled_courses.remove(course) user.save() return super().form_valid(form) def get_success_url(self): user = get_object_or_404(User, pk=self.kwargs.get('pk')) messages.success(self.request, 'Student withdrawn from session.') return reverse('user_profile', kwargs={'pk': user.id}) So the in the form_valid method, it grabs the user's PK and the session's PK so it can successfully remove it from the student's enrolled courses. But it seemed to only work with my one test user that has a PK=2, but not the others. What am I missing here? -
Windows 10 with firewall: Django developement Server: not able to access on Lan
I have a django server with python manage.py runserver 0.0.0.0:8000 ALLOWED_HOSTS=['*'] CORS_ALLOW_ALL_ORIGINS = True Its running in windows. I have my ip as 192.168.0.5 where the django server is running i can access 192.168.0.5:8000/admin from my pc (i.e where server is running, same as the ip) but then when i try to access from a pc on lan it says CONNECTION TIMEDOUT on that pc on lan i tried to ping the ip 192.168.0.5, ping working fine Later i found that its the firewall. When I disable the firewall DJango project is accessible in LAN, else not. I havent touched the firewall at all. But in the contrary i have a reactjs app running in development mode. but its accessible on lan, SO what can i do with windows firewall to enable the django accessible on lan