Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth - Template include in base.html causes RecursionEror
I am using allauth to handle all my authentication. Using that app each piece of authentication functionality is given its own template. However, I want to include the registration form in all other templates. i.e. the registration form is present in /account/login/, /account/password/change ... etc... I decided to achieve that by including signup.html in base.html which is extended in all other templates. Like this: base.html ... <h4 class="card-title text-center">Register</h4> {% include "account/signup.html" %} ... account/base.html {% extends "base.html" %} account/signup.html {% extends "account/base.html" %} {% load i18n %} <p>{% blocktrans %}Already have an account? Then please <a href="{{ login_url }}">sign in</a>.{% endblocktrans %}</p> {% for message in messages %} <span style="color:red;">{{ message }}</span> {% endfor %} <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {% for field in form %} <div id="input-group"> {{ field }} </div> {% endfor %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <div class="card-footer text-center"> <input type="submit" class="btn" value='{% trans "Get started" %}'> </div> </form> account/login.html {% extends "account/base.html" %} {% load static %} {% load i18n %} {% load account socialaccount %} {% get_providers as socialaccount_providers %} {% block general_notice_modal %} {% endblock … -
ValueError: Cannot alter field Schedule.Swimming.player into Schedule.Swimming.player (you cannot alter to or from M2M fields)
class Match(models.Model): date = models.DateField('my date') time = models.TimeField() duration = models.DurationField(null = True) category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default=CATEGORY_CHOICES[0][0]) place = models.CharField(max_length=256, null=True) game_status = models.CharField(max_length=256, null=True) #completed or not # Foreign Keys event = models.ForeignKey(Event, on_delete=models.CASCADE) # teams = models.ManyToManyField(Team) class Meta: abstract = True class Swimming(Match): time = models.TimeField(null=True) player = models.ManyToManyField(Player, related_name='player_swimming') game_level = models.CharField(max_length=256, null=True, choices=LEVEL_CHOICES) # like semi-final, final etc game_specific = models.CharField(max_length=256,null=True, choices=EVENT_CHOICES) #like Men's Shot Put or Men's Triple Jump etc def __str__(self): return str(self.game_level) This is my initial model Swimming which is extended from base class Match. Now i want to add one intermediate model PlayerSwimming to Swimming model.Now it is stuck during the makemigration phase. I have tried all the possibilities like first deleting the migration and adding again ,commenting and migrate and then uncommenting it and migrate again. Help me! The new model is: class Swimming(Match): player = models.ManyToManyField(Player, through='PlayerSwimming') game_level = models.CharField(max_length=256, null=True, choices=LEVEL_CHOICES) # like semi-final, final etc game_specific = models.CharField(max_length=256,null=True, choices=EVENT_CHOICES) #like Men's Shot Put or Men's Triple Jump etc def __str__(self): return str(str(self.category) + " " + str(self.date)) class PlayerSwimming(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) # swimming = models.ForeignKey(Swimming, on_delete=models.CASCADE, default='') time = models.IntegerField(default=-1) medal = models.CharField(max_length=256,blank=True, … -
django formset - dont submit a single form if a checkbox is not true?
I have a formset displayed as a table, and I do not want to validate any of the forms that do not have a specific checkbox ticked. However when the formset is submitted they are getting validated. Do I need to handle this at the clean_field() method level? If so how do I stop the form at that point, without rendering the whole formset invalid?? class HILISForm(forms.ModelForm): summary = forms.CharField( widget=forms.Textarea(attrs={'rows':3, 'cols':70}), label='', required=False) class Meta: model = Report fields = ('reported', 'summary', ) def clean_reported(self): reported = self.cleaned_data['hilis'] if reported: return(hilis_reported) else: raise(forms.ValidationError('Not checked...')) if I 'pass' instead of raising the error- then this form still appears in my cleaned_dict which I do not want. -
Django: disable binary logs for delete() method
I have a MySQL master-slave configuration and I want to delete some old records on master only and keep them on slave: class MonitorQuerySet(models.QuerySet): def delete(self, *args, **kwargs): with connection.cursor() as cur: cur.execute('SET @@session.sql_log_bin = 0') ret = super().delete(*args, **kwargs) cur.execute('SET @@session.sql_log_bin = 1') return ret class Monitor(models.Model): ... objects = models.Manager() nobinlog = SitePingerQuerySet.as_manager() The problem with this approach is that now one can do Monitor.nobinlog.delete() and this will wipe out the whole table. I though about pre_delete and post_delete signals but that will run on each call to delete(). Is there a better solution for this? -
Import whole module to Python/Django project
I need to import whole custom module (config.py) to settings.py file. Both on the same folder. It works fine when I use from .config import var BUT import config or import .config gives no module or invalid syntax error. Is there way to import whole module to Django files? -
range slider in leflet
hello every one I hope you are all fine actually, I want user change range slider of(population) and then leflet will ganarate cluster or draw circle based one the value of slider of population Ex: if user slide to 1 Milon and assuem the ragen have 4Milon so there are 4 cluster leflet shoud draw can any one guide me, thanks ! -
how can i use arabic or french date format on my form widget in django
class QuittanceRegister(forms.Form): du=forms.DateField(required =True,widget=forms.widgets.DateInput(attrs= {'type': 'date'})) au=forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) -
Optimising number of queries within a DRF ModelSerializer
Within Django Rest Framework's serialiser it is possible to add more data to the serialised object than in the original Model. This is useful for when calculating statistical information, on the server-side, and adding this extra information when responding to an API call. As I understand, adding extra data is done using a SerializerMethodField, where each field is implemented by a get_... function. However, if you have a number of these SerializerMethodFields, each one can be querying the Model/database separately, for what might be essentially the same data. Is it possible to query the database once, store the list/result as a data member of the ModelSerializer object, and use the result of the queryset in many functions? Here's a very simple example, just for illustration: ############## Model class Employee(Model): SALARY_TYPE_CHOICES = (('HR', 'Hourly Rate'), ('YR', 'Annual Salary')) salary_type = CharField(max_length=2, choices=SALARY_TYPE_CHOICES, blank=False) salary = PositiveIntegerField(blank=True, null=True, default=0) company = ForeignKey(Company, related_name='employees') class Company(Model): name = CharField(verbose_name='company name', max_length=100) ############## View class CompanyView(RetrieveAPIView): queryset = Company.objects.all() lookup_field='id' serializer_class = CompanySerialiser class CompanyListView(ListAPIView): queryset = Company.objects.all() serializer_class = CompanySerialiser ############## Serializer class CompanySerialiser(ModelSerializer): number_employees = SerializerMethodField() total_salaries_estimate = SerializerMethodField() class Meta: model = Company fields = ['id', 'name', 'number_employees', 'total_salaries_estimate', ] def … -
Django: dictionary to HTML table, when values are generators
I have a dictionary containing scraped Airbnb listings data: all_data = { 'name' : self.detail('listing', 'name'), 'city' : self.detail('listing', 'city'), 'id' : self.detail('listing', 'id'), 'latitude' : self.detail('listing', 'lat'), 'longitude' : self.detail('listing', 'lng'), 'picture' : self.detail('listing', 'picture_url'), 'pictures' : self.detail('listing', 'picture_urls'), 'price' : self.detail('pricing_quote', 'rate', 'amount'), 'currency' : self.detail('pricing_quote', 'rate', 'currency') } That I am passing from Django view to template like this: context = {'all_data':all_data} return render(request, 'javascript/testjson.html', context) The values in this dictionary are generators, yielding a specific listing detail. How do I present this data in a HTML table form in the template? So far I have the following for displaying the headers, but I don't know how to extract the data from generators into columns below those headers: <table> <tr> {% for key, value in scraped_data.items %} <th>{{key}}</th> {% endfor %} </tr> </table> -
How to create form in Django based on Models data?
I want to display form based on Questions in database and its options in Option table. My problem is that I want to display question in normal text and its options as form. I can be able to do that but it seems highly inefficient and difficult to manage. So, i wanted to improve this. I didn't posted my code here because it is little long. models.py view.py index.html -
django login via postman
what I have done is entered a json in request { "username":"nimish", "password":"mypassword" } and in the view @csrf_exempt def LoginView(request): if request.method == "GET": return HttpResponse(json.dumps({"status": "ERROR", "errors": ["GET Request not allowed"] })) request_json = json.loads(request.body.decode("utf-8")) login(request,authenticate(request,User.objects.get(username=request_json["username"]),request_json["password"])) But this created error Forbidden (CSRF cookie not set.) So how should I proceed to log in by postman. When I checked authenticate did his work but login function failed -
connect to ejabberd through strophe in django
I am trying to connect to ejabberd. Version of ejabberd is 18. i changed ejabberd.yml module: ejabberd_http request_handlers: "/ws": ejabberd_http_ws "/bosh": mod_bosh "/api": mod_http_api ## "/pub/archive": mod_http_fileserver web_admin: true http_bind: true http_poll: true ## register: true captcha: true when i am using strophe to connect by var conn = new Strophe.Connection('http://localhost:5280/http-bind'); it says connection attempt failed and connection timeout. Any solutions please ?? -
Django Rest Framework:RecursionError at /profile/ maximum recursion depth exceeded while calling a Python object
I have completed my project on social networking and setting an option for logout MeanWhile I came across django-rest-auth app and tried to use it but later choose to do it by myself so, deleted it from settings.py and urls.py and used "pip uninstall django-rest-auth" to clear out things. Now when i try to create a new user It gives me this error: RecursionError at /profile/ maximum recursion depth exceeded while calling a Python object models.py class Profile(models.Model): user = models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE) location = models.CharField(max_length=30,blank=True) friends_count = models.PositiveIntegerField(default=0) profile_pic = models.FileField(upload_to='profile_pics/',blank=False,null=True) def natural_key(self): return (self.user.username,) views.py: class UserCreateAPIViewSet(viewsets.ModelViewSet): """"A View which handles Creating and Updating User Profile""" serializer_class = UserProfileCreateSerializer queryset = User.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) filter_backends = (filters.SearchFilter,) search_fields = ('username','email',) urls.py: router.register(r'profile',views.UserCreateAPIViewSet) serializers.py: class UserProfileCreateSerializer(serializers.ModelSerializer): """"A serializer for user data request""" location = serializers.CharField(source='profile.location') friends_count = serializers.IntegerField(source='profile.friends_count',read_only=True) profile_pic = serializers.FileField(source='profile.profile_pic',allow_empty_file=True,allow_null=True) class Meta: model = User fields = ( 'pk', 'username', 'email', 'password', 'location', 'friends_count', 'profile_pic', ) extra_kwargs = { 'password':{'write_only':True}, 'friends_count':{'read_only':True}, } def create(self, validated_data): """"Create and return a new User""" user = User( email = validated_data['email'], username = validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user -
Salt generating algorithm in pbkdf2_sha256 hashing algorithm in django
I have my Django web app. I have implemented the login and password using Django's django.contrib.auth library and hashed the passwords using its pbkdf2_sha256 algorithm, class PBKDF2PasswordHasher(BasePasswordHasher): Password hash format <algorithm>$<iterations>$<salt>$<hash> Sample Password <pbkdf2_sha256>$<36000>$<azQKqHiQnL3V>$<SsVFGaW5+NYP0mDBjmSmhM70A/8mN8X2Pth0R7idgII=> where, I know algorithm = pbkdf2_sha256,iterations = 36000,salt = azQKqHiQnL3V and hash = SsVFGaW5+NYP0mDBjmSmhM70A/8mN8X2Pth0R7idgII=.But, I Don't know how this salt is generated For my mobile app, I have created APIs in PHP for which I need to make the login and sign up API. So, I want to generate the hashed password using the same pbkdf2_sha256 algorithm in php. For that, I need to know how the salt is being generated. Code from django.contrib.auth.hashers.py def make_password(password, salt=None, hasher='default'): """ Turn a plain-text password into a hash for database storage Same as encode() but generates a new random salt. If password is None then a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string will be returned which disallows logins. Additional random string reduces chances of gaining access to staff or superuser accounts. See ticket #20079 for more info. """ if password is None: return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNUSABLE_PASSWORD_SUFFIX_LENGTH) hasher = get_hasher(hasher) if not salt: salt = hasher.salt() return hasher.encode(password, salt) pbkdf2_sha256 algorithm in django.contrib.auth.hashers.py class PBKDF2PasswordHasher(BasePasswordHasher): """ Secure password … -
Docker build pytest :Failed to establish a new connection: [Errno 111] Connection refused
I am facing a serious issue while docker build. The pytest is not working but after build(remove the pytest part) the same pytest work from inside container Here is my docker file: FROM phusion/baseimage:0.9.22 RUN apt-get update && apt-get install -y build-essential git libaio1 libffi-dev libjpeg-dev libssl-dev libxml2-dev python-wand libmagickwand-dev\ libxslt-dev libz-dev python3-pip python3-setuptools unzip ADD requirements.pip / RUN pip3 install -r /requirements.pip VOLUME ["/app"] WORKDIR /app ADD . . EXPOSE 8000 RUN python3 manage.py runserver 0.0.0.0:8000 & RUN python3 -m pytest tests/test_demo.py Here is my test file: import requests def test_demo(): response = requests.get('http://0.0.0.0:8000/' + "demo") assert (response.status_code == 200) Please help. -
Unable to connect Django 2.0.7 with oracle 12c using cx_oracle 6.4 in python 3.7
I am facing a problem in connecting Orace 12c with Django 2 command used: python manage.py migrate below is the error message i m getting Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0002_remove_content_type_name...Traceback (most recent call last): File "C:\Users\Administrator.IP22\Envs\dell\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Administrator.IP22\Envs\dell\lib\site- packages\django\db\backends\oracle\base.py", line 497, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.ProgrammingError: positional and named binds cannot be intermixed` click here to see error screenshot Following code is used in settings.py for database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'orcl', 'USER': 'C##', 'PASSWORD': 'Oracle_1', 'HOST': '', 'PORT': '', } } -
Django group objects with same key into one key after filtering
I have the following result after a filter: [{SV2: "2*3"},{SV2: "3*4"},{SV2: "50"},{RV2: "10"},{RV2: "7*5"},{RV2: "50"}] But I would like to have all the objects with the same keys as one array: [{SV2: ["2*3","3*4","50"]},{RV2: ["10","7*5","50"]}] How can I do this in my view/serializer before sending the information through to my front end? Model: class ProcessedStockAmounts(models.Model): prodName = models.ForeignKey(Productlist, on_delete=models.CASCADE, blank=False, unique=False, related_name='prod') amount = models.CharField(unique=True, max_length=255) time = models.ForeignKey(StockTakingTimes, on_delete=models.CASCADE, blank=False, unique=False, default=1) Serializer: class ProcessedStockSerializer(serializers.ModelSerializer): slug_field='productid', required=False) name = serializers.CharField(source='prodName') class Meta: model = ProcessedStockAmounts fields = '__all__' def to_representation(self, instance): result = super(ProcessedStockSerializer, self).to_representation(instance) new_result = {result['name']: result['amount']} return new_result View: class ProcessedStockTimeView(generics.ListCreateAPIView): serializer_class = ProcessedStockSerializer def get_queryset(self): time = self.kwargs['stock'] value = ProcessedStockAmounts.objects.filter(time__times__icontains=time) return value -
selenium.common.exceptions.WebDriverException error
I use the Ubuntu app on Windows 10 I ran python3 functional_tests.py but I have a provelm the traceback raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist (Driver info: chromedriver=2.40.565383 (76257d1ab79276b2d53ee976b2c3e3b9f335cde7),platform=Linux 4.4.0-17134-Microsoft x86_64) this is functional_tests.py from selenium import webdriver browser = webdriver.Chrome() browser.get('http://localhost:8000') assert 'Django' in browser.title -
Django admin url filter won't work
I've constructed the url http://localhost:8000/admin/myapp/rnaextracts/?biosamples__biosamplesetid__in=[57,52,51,50,49] to link another admin page. The link points to a list view and the list is filtered by the expression passed in the url. However, Django redirects to the proper admin list view but the query changes to ?e=1 (I think that this indicates some sort of error) and the unfiltered list is displayed. I've tried the filter expression in Django shell and it works: qs = RnaExtracts.objects.filter(biosamples__biosamplesetid__in=[57,52,51,50,49]. It returns a queryset with 52 objects out of 416. -
Django: using a form as the input and result of a calculation
I'm trying to present a table of data that uses data from some django models combined with user inputted data to help make some calculations and present the results - these calculations will be ad hoc and not based on a single django model. I was thinking the best way to do this would be to create a formset (displayed as an html table) with disabled form fields and initial data for the data from the model, other fields for the users to enter bits of the calculation that we don't have the data for and finally including an extra disabled form field for the result of the calculation which I would populate when the form was submitted. I haven't been able to update the form data after it has been submitted though so feel like I've got the wrong approach. Does anyone have a better suggestion? Update: I found this in the docs so now I'm wondering if I should create a new formset somehow based on the old formset. If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another … -
want to get User.username from User model in django
from django.contrib.auth.models import User class User(User): def __str__(self): return self.username what should I do to get the username from the User model? username1 = User.username i want username1 to store the active username value. -
Use different serializer for request and reply
I can use different serializers for POST / GET requests as follows: class CommandViewSet(DynamicModelViewSet): queryset = Command.objects.all() serializer_class_post = CommandSerializerPost serializer_class_get = CommandSerializerGet permission_classes = (AllowAny,) def get_serializer_class(self): if self.request.method == 'POST': return self.serializer_class_post elif self.request.method == 'GET': return self.serializer_class_get Now I would like to use a different serializer for the request and the reply of a POST request. How can this be accomplished? -
Query django JSONField for nested value in list of nested objects
I have Sentence model which metadata as JSONField One sample row is Sentence.objects.filter(id=6753315).values('id', 'metadata')[0] {'id': 6753315, 'metadata': [{'filters': [{'id': None, 'level_name': 'Brand Hierarchy'}, {'id': None, 'level_name': 'Category Hierarchy'}], 'product': None, 'themes': [{'id': 35299, 'sentiment': 'Positive'}, {'id': 35301, 'sentiment': 'Positive'}]}]} metadata is list of object and that object have nested list of objects. I want to query such rows based on theme id. In this example row length of metadata list is 1 and length of themes list is 1 so its easy to query like In [30]: Sentence.objects.filter(id=6753315, metadata__0__themes__0__contains={"id": 35299}) Out[30]: <QuerySet [<Sentence: Sentence object>]> But length of metadata and themes can be anything so how can I query such rows to check if some theme id is present in that row or not for any length of metadata and themes. I just want to find out all the rows which have some particular theme id Sentence.objects.filter(metadata__*__themes__*__contains={"id": 35299}) I dont know the index so wrote * to make my problem easy to understand. -
Passing metadata to Stripe on creation of Card
I'm trying to pass billing address information to stripe on the addition of a new card. As per this link (https://stripe.com/docs/api#create_card), under the Create a Card section, it indicates that you can pass metadata when creating the card. On the right of the page, in the response section, they give examples of the types of things you can pass (I assume the key in the response is the key that you have to send them...maybe I'm wrong?). I've got the following code in my view (I've used Toronto just to test with. This will be billingaddress.city after I get this working). metadata1 = { "address_city": "Toronto" } stripe_card_response = customer.sources.create(source=token, metadata=metadata1) When I look at the test transaction in Stripe and click on "Event Data", it shows that address_city is null. Any thoughts on why the value of Toronto isn't being sent to Stripe as the city? I should note that the rest of the transaction comes through to Stripe just fine. Thanks! -
Django form field - variable amount of selects under one field name?
I want to make a field name in my form within a formset called tests. For each form in my formset, I want the tests field to contain a variable amount of select boxes, each labelled differently. Is this possible? forms.py: fields = [] for gene, test in tests.items(): fields.append(forms.ChoiceField( label=gene, choices=TEST_CHOICES )) self.fields['tests'] = fields thanks