Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Find users of security group with django-python3-ldap
Very new to LDAP and AD. I'm using django-python3-ldap to authenticate users of my django app. We want to make it so that only a subset of our users can access our django app, so yesterday they added the security group 'MyAppGroup.' Only problem is, I don't seem able to add this to the search base. User lookup always fails. Working search base (returns ALL users): "ou=Basic Users, ou=BIGAPP Users,dc=subd,dc=domain,dc=com" When I asked, they said that MyAppGroup was a security group, and that "Basic Users" and "BIGAPP Users" were "AD Members." dsquery group -name "MyAppGroup" returns: CN=MyAppGroup,OU=BIGAPP Groups,dc=subd,dc=domain,dc=com This result does not work as the search base. Do I need to add a custom search filter for this to work? Any help is appreciated. -
Django - how to dynamicaly create models in tests? (Django 2.x)
I would like to test my custom subclassed Django model field. I could use existing models from my project but they are quite complicated and hard to setup. I have found two SO question but the are quite old (2009 and 2012). #1 #2 So I wanted to ask if anyone knows a better way to achieve this. Django wiki has a dedicated page for custom fields, but there I haven't found anything about testing there. Thanks for any tip or suggestion. -
Empty Serialised Response in Django Rest Framework
I have a model, a view and a serializer which produce the following response representing a medical test: { "name": "electrocardiogram", "cost": "180.00", "results": [ { "id": "bff25813-5846-4eac-812f-7e57d8fbb496", "lots more things" : "were here, but I hid them for brevity's sake" "video": [] } ] } As you can see, it is a nested object which is put together by some nested DRF serializers. This is great, but I want to put a couple of custom database calls into my view logic as I want to keep track of which tests a user runs. To do this I have written. class RunTestView(generics.RetrieveAPIView): serializer_class = TestSerializer def get_object(self): if 'test' not in self.request.query_params: return Response({'Error': 'test not in request'}, status=status.HTTP_400_BAD_REQUEST) test = get_object_or_404(Test, id=self.request.query_params['test']) return test def get(self, request, *args, **kwargs): if 'case_attempt' not in request.query_params: return Response({'Error': 'case_attempt not in request'}, status=status.HTTP_400_BAD_REQUEST) case_attempt = get_object_or_404(CaseAttempt, id=request.query_params['case_attempt']) # get the test object which we will later serialise and return test = self.get_object() # if we've gotten this far, both case_attempt and test are valid objects # let's record this in the TestsRunTracking model if it is not already there if not TestsRunTracking.objects.all().filter(case_attempt=case_attempt, test=test, user=request.user).exists(): tracking = TestsRunTracking(case_attempt=case_attempt, test=test, user=request.user) tracking.save() # … -
How to edit object in forms if the form has __init__ method?
I have a form that have choice field and must be filtered by request.user and for this I use the init method. When it is initialized, the data is ready to be selected which is good but when I want to edit that object, it doesn't show the data stored in selected choice instead shows an empty select field. Is important that in both cases (create and edit) that object in choice field to be filtered by request.user. How can I edit the object if the form uses a init method? class EditarePereche(forms.ModelForm): boxa = forms.IntegerField(label="Boxa", min_value=1) sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year) mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul") femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela") serie_pui_1 = forms.TextInput() serie_pui_2 = forms.TextInput() culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea", required=False) culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea", required=False) data_imperechere = forms.DateInput() primul_ou = forms.DateInput() data_ecloziune = forms.DateInput() data_inelare = forms.DateInput() comentarii = forms.TextInput() # Functie pentru filtrarea rezultatelor dupa crescator def __init__(self, *args, crescator=None, **kwargs): super(EditarePereche, self).__init__(*args, **kwargs) self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul", perechi_masculi__isnull=True) self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă", perechi_femele__isnull=True) self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) class Meta: model = Perechi fields = "__all__" -
Serve to docker service with nginx in different endpoint
I'm building a multiservice webapp with two different services. The webfront and the API. I've manage to server the front, and make it communicate with the api internally, but i'm new to nginx and I've no idea how to do it. This is my actual ninx.conf for a django front. upstream webapp{ server front:8000; } server { listen 80; location / { proxy_pass http://webapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/webapp/web/staticfiles/; } } The front is running with gunicorn in port 8000, and its served in http://localhost/. The api is running with gunicorn in port 5000 and I would like to access it like http://localhost/api This is how i define the service in the docker-compose file: api: build: context: ./API dockerfile: Dockerfile command: gunicorn -b 0.0.0.0:5000 api:api --limit-request-line 0 ports: - 5000:5000 -
Unresolved Imports in VS Code Django Project
I want to open a folder at the level above a Django project directory (project_parent below) in VS Code and have the linter correctly resolve the Django project imports: | project_parent | -- | django_project_dir | -- | -- | manage.py If I do this, the linter is confused and I get a bunch of warnings on imports from the Django modules in the project: unresolved import 'module.models' Python(unresolved-import) If I open VS Code at the the Django project folder level, the linter resolves all of the imports. This isn't ideal though because I have to close and re-open VS Code at the level above to see other related code (Ansible, bash scripts, etc.) My question is how to update VS Code settings to add the Django project directory to the linter path? Env: VS Code: 1.40.1 Python: 3.7.2 Django: 2.2.1 Related question: Pylint "unresolved import" error in visual studio code the solution here is just to open the project at the level of the Django project dir which I don't want to do. my issue is not related to "python.pythonPath" setting, the python path is fine and all of the package level imports are resolved by the linter. -
Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[^/]+)/$']
I am Django newbie and learner, just follow the tutorial and got stuck. When I add a SlugField in django models.py and make a get_absolute_url but the reverse error is coming in navbar. Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P[^/]+)/$'] models.py from django.db import models from django.urls import reverse from django.conf import settings # Create your models here. # Choices CATEGORY_CHOICES = ( ('S','Shirt'), ('P','Pants'), ('J','Jacket'), ('W','Watches'), ('E','Electronics'), ('SO', 'Shoes'), ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger'), ) class Item(models.Model): title = models.CharField(max_length=200) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES,max_length=3) image = models.ImageField(upload_to='images/') slug = models.SlugField() label = models.CharField(choices=LABEL_CHOICES, max_length=1) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:product', kwargs={"slug": self.slug}) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) def __str__(self): return self.item class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() orderd = models.BooleanField(default=False) def __str__(self): return self.user.username -
Django Edit Profile - 'bool' object is not callable
So I just followed this tutorial to create a profile for a user and allow them to edit it but I get this error when I go and visit the edit page 'bool' object is not callable File "C:\Users\...\account\userprofile\views.py", line 64, in profile_edit_view if request.user.is_authenticated() and request.user.id == user.id: TypeError: 'bool' object is not callable models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings class UserProfile(models.Model): user = models.OneToOneField(User, related_name="user", on_delete=models.CASCADE) photo = models.ImageField(upload_to = "account/userprofile/photos", verbose_name="Profile Picture", max_length=255, null=True, blank=True) location = models.CharField(max_length=100, default='', blank=True) website = models.URLField(default='', blank=True) bio = models.TextField(default='', blank=True) @receiver(post_save, sender=User) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm class ProfileEditForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] views.py def profile_edit_view(request, pk): # querying the User object with pk from url user = User.objects.get(pk=pk) # prepopulate UserProfileForm with retrieved user values from above. user_form = ProfileEditForm(instance=user) # The sorcery begins from here, see explanation below ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('location', 'website', 'bio')) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: … -
how can I remove hyphen from confirmation links in django?
I am new with django , but I am trying to remove - from the confirmation links however when I tried to apply over models it doesnt work as I want to do it, on the other side the links keeps the same every link. I also tried to save token instead of saving the instance , but the same views def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): with transaction.atomic(): user = form.save(commit=False) user.is_active = False user.save() email_subject = 'Next Step: Activate Your Account' current_site = get_current_site(request) html_message = render_to_string('email/activate.html', { 'user': user, 'domain': current_site.domain, 'token': account_activation_token.make_token(user), }) mail = EmailMessage(email_subject, html_message, to=[form.cleaned_data.get('email')]) mail.content_subtype = "html" mail.send() return JsonResponse({'message': 'success'}) else: return JsonResponse({"message":form.errors}) models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(post_save, sender=User) def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') instance.save() tokens from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() urls http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 13 min http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 20 min http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 45 min http://127.0.0.1:8000/account/activate/5bn-755ea8cee1faa6a91c2b/ # one hour ago -
Bulk insert to mongo DB using threadpool inside a celery task
When I tried bulk insert to mongoDB collection inside threadpool mongoDB memory goes on increase. What is the best way to implement this in a celery task? -
debugging django apps and printing values
Being new to django , I am trying to debug few things and print their values . This is my views.py for the app and here is the code .I tried to print the customers but I get some response which i couldn't understand . class CustomerViewSet(viewsets.ModelViewSet): serializer_class=CustomerSerializer def get_queryset(self): active_customers=Customer.objects.filter(active=True) import pdb; pdb.set_trace() print('active_customers',active_customers) return active_customers I tried the method of importing pdb and printing active_customers in the terminal and here is the response . <QuerySet [<Customer: >, <Customer: >, <Customer: nsxns xn dsnc d>]> Where can I print the values that is sent as response .What are some good ways to trace the flow of data in the django rest framework ? -
Eclipse error 'Tcl_WaitForEvent: Notifier not initialized' Django server stops after hitting a breakpoint 2nd time
Use Eclipse to start django webserver in debug mode, and set a break point. The following sequence with cause Eclipse to unload (webserver stop) the server. Eclipse version: Eclipse Java EE IDE for Web Developers. Version: Neon Release (4.6.0) Build id: 20160613-1800 Sequence: 1) Load a page to hit break point. The page is loaded. 2) Load same page and server will stop. Error in Eclipse console: Tcl_WaitForEvent: Notifier not initialized If not setting breakpoint, all works fine. How to solve the problem? -
Basic tag system using ManyToManyField
I'm writing a simple Django powered notetaking app, and currently I'm implementing basic tagging system for my notes. The requirement is to have a Tag model with added_by field on it as a ForeignKey to User. First I have tried to modify django-taggit source, as well as extend its Tag model, however haven't had any success. So, I decided to implement my own tagging system from scratch. For this purpose I'm using a ManyToManyField: class Note(models.Model): slug = models.SlugField() title = models.CharField(max_length=255) [...] tags = models.ManyToManyField(Tag) This is my form: class NoteForm(forms.ModelForm): class Meta: model = Note fields = [ 'title', 'description', 'notebook', 'tags' ] widgets = { 'tags': forms.TextInput() } Everything renders nicely, but when I try to submit the create form, I get an error: So, inside that TextInput is a comma separated string. I assume that's not what Django expects, but I don't know how to convert that into something Django would accept. I have tried to debug this, but it seems that my form_valid isn't getting executed at all. I have also tried to put some debug statements in clean_tags in my ModelForm, which is also not getting executed. How can I overcome the issue? -
I want help in creating a function for adding items in cart without logging in
I am trying to make a website like any other eCommerce sites and I want add if any user is not logged in then also he/she should be able to add items to the cart. Any help regarding this will be grateful! thank-you very much... -
one more stupid question about django, django templates and django-stars-ratings module
i'm trying to implement a rating system for my Django project I have two models rn, Article and Comment. I'm using Django-stars-rating app (here's the docs: https://django-star-ratings.readthedocs.io/en/latest/) Currently i print ratings for each instance of Article without any issue via {% rating article 10 10 True %} In the docs they say that we can override template via template_name argument in {%%} command, but i don't have any idea how to do this. I've tried this {% rating article 10 10 True widget_custom.html %} but it's now working. By the way, i have comments form for Articles. i want to have opportunity for users to rate article right in comment form, but when i simple add {% ratings e %} to form, user can vote, but score immediately recounts. I'm stucked there for a three days. Help, please. P.S. If anybody knows any solution for creating such a system, please give links, i'll be very grateful. Thanks in advance. -
Include field in form but not model django
In Django I have a modelForm with several text fields and a checkbox field for front-end only use. However, I do not want to add the checkbox field's value to the database with the text field's values when I submit the form. Is there a way to "ignore" a field in a model? -
Django 2.2 Breaking Change with runserver command
Somewhere in the upgrade from 2.1.0 to 2.2.0, the Django command: manage.py runserver begins to require the notebook module, which is a part of the jupyter package. It's unknown why it is needed, and very little documentation exists to justify its inclusion. To move past this issue, we've added jupyter to the requirements, but it is suggested that we find a way to not install jupyter on our production and staging servers. Note: This breaks when upgrading from Django 2.1.14 to 2.2.0 Note: This does not affect the operation of openscout_uwsgi or supervisor Note: This seems to be linked directly with the runserver manage.py command, and by association or inheritance, the runsslserver command Note: This can also be corrected by pip installing the jupyter package, and immediately uninstalling the jupyter package. Uninstalling the jupyter package leaves behind some directories, and a binary executable Note: Our assumption is that it is a django issue, between 2.1 and 2.2, howevver, we can't be certain. It may be an issue buried in dependency list. I.e., Django 2.2 requires package X version Y, which does not correctly require jupyter. The following is the error produced by the ./manage.py runserver command: Traceback (most recent call … -
Foreign key reference disappears on save
In a simple model structure like that: class News(models.Model): name = models.CharField(max_length=50) class Book(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('News', on_delete=models.CASCADE) I'm having a problem when assigning ForeignKey "parent" field. Its value disappears when I'm trying to save an object: >>> news = News(name='TestNews') >>> book = Book(name='TestBook', parent=news) >>> news.save() >>> str(book.parent) 'News object (2)' >>> book.save() Traceback (most recent call last): File "...\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "...\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: sample_book.parent_id It's there right before saving, but it's gone on save. It works fine when (re)assigning parent after saving the first object, but in the actual project I need to call bulk_save or at least use transaction.atomic >>> news = News(name='TestNews') >>> news.save() >>> book = Book(name='TestBook', parent=news) >>> book.save() >>> book.parent <News: News object (3)> The strangest thing is that I'm sure that it worked the other day with the bulk_save and there is a lot of similar examples in the docs. -
Django prefetch_related
I have a relational model set that has 5 tables each with a one to many relationship. I'm having trouble accessing model information after the 2nd table. ex. class TableA(models.Model): pass class TableB(models.Model): tablea = models.ForeignKey(TableA, oncascade...) class TableC(models.Model): tableb = models.ForeignKey(TableB, oncas...) class TableD(models.Model): tablec = models.ForeignKey(TableC, ...) class TableE(models.Model): tabled = models.ForeignKey(TableE, ...) In my views.py i'm using the prefetch related method on TableA: from . models import * data = TableA.objects.all().prefetch_related('tableb_set__tablec_set__tabled_set') I can't seem to access information from TableC, TableD or TableE. for a in data: print(a.id) for b in a.tableb_set.values(): print(b['id]) for c in b.tablec_set.values(): #This is where I get an error message stating the model doesn't have a relatedmanager How can I access model information 2+ tables deep into the prefetch_related relationship? Thanks in advance -
Can you run a raw MySQL query in Django without a model?
I am still learning Django and I'm just now getting into connectors to MySQL. What I'm trying to figure out is how I would go about querying a db/table that I am not creating with a model in Django. Do I have to recreate the table as a model in order to have it talk to Django? If so, would that basically mean just recreating my structure with a model then importing my data to the new table? Sorry if this is a goofy question, I appreciate any help you can give! -
Are Django Sessions Completely Unique?
I am using Django Sessions to store price for Stripe based on a form input (if this is bad please advise). if form.is_valid(): srv = form.cleaned_data['service'] if srv == 'Silver': request.session['price'] = 999999 else: request.session['price'] = 100000 return redirect('pay-now') Now, obviously, the price is going to be variable, I want to know if sessions are completely unique to each individual, and I won't encounter any errors in terms of people being charged the wrong price based on a previous session store etc. Thanks in advance! -
i am trying to send data through postman and it takes one field null. So anyone can help me in that. And also i am beginner to django
this is the error django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (6, MBBS, Orenburg University, 2019, null). My models is: class Educations(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='edu_user') doctor_degree = models.CharField(max_length=25) university = models.CharField(max_length=25) passing_year = models.IntegerField() def str(self): return self.doctor_degree here the user is for doctor and i'am taking its foreign key in education model and its viewset is: class EducationViewSet(viewsets.ViewSet): def list(self,request): eduss=Educations.objects.all() edu_data_list=[] for edu in eduss: edu_data_list.append({ "doctor_degree" : edu.doctor_degree, "university" : edu.university, "passing_year" : edu.passing.year, "doctor_name" : edu.user.full_name, "doctor_mobile_number": edu.user.mobile_number, "doctor_date_of_birth": edu.user.date_of_birth, "doctor_blood_group": edu.user.blood_group, "doctor_email": edu.user.email }) return Response({"eduss":edu_data_list}) def create(self,request): doctor_degree = request.data.get('doctor_degree') university = request.data.get('university') passing_year = request.data.get('passing_year') user = request.user education = Educations() education.doctor = user education.doctor_degree = doctor_degree education.university = university education.passing_year = passing_year education.save() return Response("successfully saved") -
Django / FactoryBoy - Overriding lazy_attributes
I'm working on a Django project for which I've created the following factory: class PurchaseFactory(factory.DjangoModelFactory): class Meta: model = 'core.Purchase' amount = decimal.Decimal(random.randrange(100, 100000) / 100) ( .... ) user = factory.SubFactory(UserFactory) @factory.lazy_attribute def date(self): if not self.date: return timezone.now() else: return self.date For which I'm running the following test: class TestGetBalanceForPeriod(TestCase): def setUp(self) -> None: self.user: User = UserFactory() self.purchase_1: Purchase = PurchaseFactory( user=self.user, date=timezone.datetime(2019, 11, 1), amount=10 ) def test_test_setup(self) -> None: self.assertEqual(self.purchase_1.date, timezone.datetime(2019, 11, 1)) As you can see I've overridden the date field on the PurchaseFactory with an lazy_attribute. However, in this specific test I'm attempting to set the date myself. I imagined factoryboy would override all values with the values provided by the users, but the test fails with the following error: AssertionError: datetime.datetime(2019, 11, 22, 16, 15, 56, 311882, tzinfo=<UTC>) != datetime.datetime(2019, 11, 1, 0, 0) The first date is the results of the timezone.now() call and not the date that I provided as an input. So far I've been able to override all values on the many factories in our project without problems - but I'm unable to solve this problem. Does anyone know what I am doing wrong? -
using AWS Elastic search with VPC endpoint django haystack
I want to use AWS Elastic-search service with my django application which is running on EC2 instance. For that I use the settings - HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch5_backend.Elasticsearch5SearchEngine', 'URL': 'https://vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com:9200/', 'INDEX_NAME': 'haystack', 'INCLUDE_SPELLING':True, }, } I am not even able to set the connection. Here I am getting this error - raise ConnectionError('N/A', str(e), e) elasticsearch.exceptions.ConnectionError: ConnectionError((, 'Connection to vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com timed out. (connect timeout=10)')) caused by: ConnectTimeoutError((, 'Connection to vpc-ES-CLUSTER.ap-south-1.es.amazonaws.com timed out. (connect timeout=10)')) I have updated the access policy to allow the user for edit and list, also in security group add the port 9200 TCP rule. How to connect ec2 with elastic search using VPC. -
Various issues running gunicorn with django app
I'm new to Django. Trying to get my app running under Nginx+gunicorn but running into a few issues. If someone has some insight, I'd appreciate it. I've found a few things to try on google, but gunicorn still seems hosed. 1) I've rsync'd my Django project from my dev box to the Nginx host. If I try launch using the dev server, it doesn't work unless I use Python 3. What have I got messed up? I've googled the ...from exec error below and found I could get it working if prefixed with python3. Seems like a workaround for a larger issue though since this way of starting it isn't mentioned in any of the tutorials I've been following. This bombs: (venv) $ python manage.py runserver 127.0.0.1:8777 File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax This works: (venv) $ python3 manage.py runserver 127.0.0.1:8777 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 22, 2019 - 15:46:59 Django version 2.2.7, using settings 'auth.settings' Starting development server at http://127.0.0.1:8777/ Quit the server with CONTROL-C. [22/Nov/2019 15:47:27] "GET /accounts/login/ HTTP/1.0" 200 1229 ^C(venv) $ 2) Above, I can run the app fine …