Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.models.query_utils.DeferredAttribute object at 0x7f29cbbf0fd0
Using Django im setting up a sms server to store numbers based on sms responses.Thur Django twilio I was able pulled the number and the response. Now that i have the number and the response, being able to go into the InteractiveConsole and show an actually list of phone numbers in for certain list is now my problem views.py from django.http import request from django_twilio.decorators import twilio_view from django_twilio.request import decompose from twilio.twiml.messaging_response import MessagingResponse from .models import Clients @twilio_view def sms_choice(request): twilio_request = decompose(request) contact_num = twilio_request.from_ response = twilio_request.body resp = MessagingResponse() Clients.doctor = contact_num resp.message('Thanks for subscribing') print(contact_num, response) return Clients.doctor models.py from django.db import models class Clients (models.Model): doctor = models.BigAutoField( primary_key=True) def __str__(self): return self -
Force Django to Consider Join Table in makemigrations
I needed to change my foreign key on my User model from a UUIDField to an IntegerField. I did this in two steps: Rename the current primary key from id to old_id and run a migration. This generated a RenameField operation. Deleted the old_id field entirely from User so that the automatic id field would take over. This generated a RemoveField operation on old_id and an AddField operation for a models.AutoField named id. Perfect. The database shows that User now has an int id field, auto-incrementing. Then I went to run the app and quickly ran into a problem: the database join tables automatically generated by the models.ManyToManyFields on User (e.g. user_languages weren't updated - they still have both a language_id AND a user_id that are UUID data types. There is no foreign key constraint in the database, but there are indexes on that field. How can I force Django to regenerate those join tables with the new data type for the User.id column? Notes: manage.py makemigrations doesn't pick up any pending changes. Also, I'm OK with losing the data in the db. -
Managing global variables with Celery and Supervisor
I'm using Supervisor to daemonize Celery on Ubuntu 16.04 and having a lot of intermittent issues with global variables. I store all of my project variables in a settings.ini file (it's a Django Rest Framework project), however this file isn't available to Supervisor. Supervisor's docs and many Stackoverflow articles suggest to add the variables to the Supervisor program as shown below: [program:foo] command=/foo/bar/foo worker -A application_name --loglevel=INFO directory=/foo environment=DJANGO_KEY="foo",MANDRILL_KEY="foo",DJANGO_SETTINGS_MODULE="settings.local",DJANGO_APP_ENVIRONMENT_JR="local"... ... I'm then accessing the variables from a task as follows: import os from foo.celery_tasks import app @app.task def send_email(foo, bar): mandrill_key = os.environ.get('MANDRILL_KEY', '') ... The application I'm working on queries several external APIs after certain actions. The querying itself is taken care of by a Celery task. Because the tasks involve API keys / environmental information, they each need access to the global variables. Every time I test this, one task succeeds and I get a key error in the other task. I'm not an expert on the inner workings of Supervisor and am relatively new to scripting in general. Any ideas as to what's going on here? -
Django models class ordering
I am using Python 3.5.2 & Django 1.10.5. I have a models class that allows the user to enter multiple address details in different languages. I can then display the users address details in the different languages. The question I have is how can I change the ordering of the details so that the Address Format is ordered in the language of the record, not by the address_country_style_type id. For the code below, I have the address_country_style_type in the meta ordering for display purposes. Here is my models.py code: class AddressDetails(FillableModelWithLanguageVersion): user = models.ForeignKey(settings.AUTH_USER_MODEL) address_country_style_type = models.PositiveIntegerField( choices=address_country_style_types.ADDRESS_COUNTRY_STYLE_TYPES, default=address_country_style_types.SELECT_A_COUNTRY_OR_TERRITORY, validators=[MinValueValidator(1)]) # the default value of 242 is default / USA address format. address_style_one_line = models.BooleanField(default=False) address_line_1 = models.TextField(null=True, blank=True, max_length=150) address_street_details = models.CharField(null=False, blank=False, max_length=100) address_locality = models.CharField(null=True, blank=True, max_length=100) address_region = models.CharField(null=True, blank=True, max_length=100) address_postal_code = models.CharField(null=True, blank=True, max_length=20) address_country_name = models.CharField(null=True, blank=True, max_length=100) address_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) address_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return truncatechars(self.address_street_details, 20) class Meta: ordering = ['language_version', 'address_country_style_type', 'address_style_one_line', 'address_street_details', 'id'] Here is the display of the users address details: I have read the docs and searched SO & google, but could not find an answer to this question. Any suggestions would be appreciated. -
how to simulate graph in database
i have a website that simulate courses dependencies like this : i found that network model is the best model or my case but i haven't found any implementation to it in RDBMS. i am using now adjacent list but it have problems in some scenarios and weak performance. i have read about modified pre-order traversal tree but it is useful in tress not graphs so how can i simulate graph in database ? -
After delay() is called on a celery task, it takes more than 5 to 10 seconds for the tasks to even start executing with redis as the server
I have Redis as my Cache Server. When I call delay() on a task,it takes more than 10 tasks to even start executing. Any idea how to reduce this unnecessary lag? Should I replace Redis with RabbitMQ? -
Search multiple tables by multiple values in Django
I'm implementing search functionality with an option of looking for a record by matching multiple tables. Say I want to find a customer by his/her first or last name, or by ID of placed order which is stored in different model than customer. The easy scenario which I already implemented is that a user only types single word into search field, I then use Django Q to query Order model using direct field reference or related_query_name reference like: result = Order.objects.filter( Q(customer__first_name__icontains=user_input) |Q(customer__last_name__icontains=user_input) |Q(order_id__icontains=user_input) ).distinct() Piece of a cake, no problems at all. The problem appears when user types multiple words into search field. Say, user have typed Bruce Wayne, after splitting this into separate parts I'm having Bruce and Wayne. Obviously I don't want to search Orders model because there aren't any records with this king of order_id, but also I don't understand how to build query to match all the scenarios. For example if user has typed in first name, then last name, or last name and after that first name. I'm guessing the solution is trivial and there's for sure an elegant way to create such a dynamic query, but I can't think of a way how. -
Django Selenium click button on ajax modal pop-up window
I'm currently doing some task for my university. I'm writing Django Selenium tests for my app. I'm trying to write test for deleting object. They key parts of my code are: delete confirmation.html <form action="" method="post" id="confirmForm">{% csrf_token %} <p>{% trans "Are you sure you want to delete this car?" %}</p> <input class="center-block btn btn-danger" type="submit" value="{% trans 'Confirm' %}"/> </form> modal.js function showModal(url) { $("#myModalBody").text(); $("#myModal").modal(); $.ajax({ url, cache: false }).done(function (html) { $("#myModalBody").html(html); $("#confirmForm").attr('action', url); }); } When I click following button <button class="btn btn-primary btn-sm pull-left" value="" id="car-delete-modal-btn m-10-b" onclick="showModal('{% url 'c2crental:delete_car' details_car.id %}');">{% trans "Delete car" %}</button> Modal appears And test stops with result: Unable to locate element. I was trying to use different selectors but none of them worked. For now test looks like this: # click 'delete' button to display popup confirmation window delete_btn = self.selenium.find_element_by_id('car-delete-modal-btn m-10-b') delete_btn.click() # click 'confirm' to delete object in popup window submit = 'input[type="submit"]' confirm_btn = self.selenium.find_element_by_id(submit) confirm_btn.click() I just can't seem to find proper selector for this button or it's a problem with a synchronization. Can someone help me fix it? Sorry for my broken english and i hope you will understand what I'm trying to do … -
Adding conditions to left join using Django queryset
First of all, I have got 2 models. The first one is a Customer with some properties: class Customer(models.Model): name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) email = models.EmailField(null=True) The second one is a Payment: class Payment(models.Model): customer = models.ForeignKey('Customer', related_name='payments', on_delete=models.CASCADE) month = models.DateField() paid = models.BooleanField(default=False) I want to know if a Customer has paid in filtering by month. Month dates are stored using the 1st day (01/MM/YYYY). However a Customer might not have a payment created for the month that I'm filtering but I still want to list this customer and using a default value for paid (the default value is false in this case). This is my queryset: values = ['id', 'paid', 'payment_id'] qs = Customer.objects.filter(Q(payments__isnull=True) | Q(payments__month = date_filter)).annotate(paid=Coalesce('payments__paid', False), payment_id=F('payments__id')).values(*values) I get this SQL Query using print(queryset.query): SELECT "restapi_customer"."id", COALESCE("restapi_payment"."paid", False) AS "paid", "restapi_payment"."id" AS "payment_id" FROM "restapi_customer" LEFT JOIN "restapi_payment" ON ("restapi_customer"."id" = "restapi_payment"."customer_id") WHERE ("restapi_payment"."id" IS NULL OR "restapi_payment"."month" = 2018-04-01) However this will not return every customer, it will only return the customers without any payment or with payments done in the filtered month. If a customer has only payments in different dates, it won't appear. So I've been trying to add … -
Incorrect show message in Django admin
I'm overrides method save in Django admin, what would show message: my created and default 'add_message', but 'add_message' should not display since not happens save_model. Expected result: if a = b should display only error massage. What doing wrong? - http://joxi.ru/DmBBWOatN0PBxm from .models import Ticket class NewTicket(admin.ModelAdmin): models = Ticket def save_model(self, request, obj, form, change): #example if a == b: return messages.error(request, 'Categoty alredy exist') else: return super(NewTicket, self).save_model(request, obj, form, change) admin.site.register(Ticket, NewTicket) -
Python - Selenium returning empty results w/ all methods
This has been asked before but none seems to solve my issue. I try to locate an element in this page, but fail at my attempts: driver = webdriver.Chrome() driver.set_window_size(0, 0) driver.set_window_position(0, 0) url = "https://www.autotrader.com/cars-for-sale/2003/Aston+Martin/DB7" driver.get(url) print (driver.find_element_by_xpath("//span[@data-qaid='txt-lowest-price']").text) driver.close() I can not scrape any other data from this page either (by_id, by_name, by_class_name, by_css_selector), all returning empty texts. Any suggestion or feedback will be welcomed and greatly appreciated. Thank you! -
Uploading multiple images in Django with django-multiupload library
I'm trying to use the below library to implement multi upload in my Django proejct. https://github.com/Chive/django-multiupload boutique/models.py class Photo(models.Model): store = models.ForeignKey(Store) photo = models.FileField(null=True, blank=True, upload_to='boutique/index/%Y/%m/%d') url = models.CharField(max_length=40, null=True, blank=True, verbose_name='Image URL') created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.photo) def get_absolute_url(self): return reverse('cms:photo_edit', args=[self.pk]) cms/forms.py from django import forms from boutique.models import Photo from multiupload.fields import MultiFileField class PhotoCreateForm(forms.ModelForm): class Meta: model = Photo fields = ['store'] attachments = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5) cms/views.py class PhotoCreateView(FormView): model=Photo template_name='cms/photo_new.html' form_class = PhotoCreateForm success_url=reverse_lazy('cms:photo') queryset = Photo.objects.all() def form_valid(self, form): for each in form.cleaned_data['attachments']: Attachment.objects.create(file=each) return super(PhotoCreateView, self).form_valid(form) cms/photo_new.html {% extends 'cms/base.html' %} {% load staticfiles %} {% block page-header %}Add Photo{% endblock %} {% block content %} <form action="" method="post"> {% csrf_token %} <table class="table table-hover store-form"> {{ form.as_table }} </table> <input class="btn btn-success btn-block" type="submit" name="" value="Submit"> <br> </form> {% endblock %} FYI, I'm not using Django default admin, but my own customized admin, which is the app named cms. I'm also using models in the app named boutique. When I upload photos, nothing happens and the page doesn't even move to the success url. After submitting the files, the file input field just says "Thie field is required", … -
Prefetch object not working with order_by queryset
Using Django 11 with PostgreSQL db. I have the models as shown below. I'm trying to prefetch a related queryset, using the Prefetch object and prefetch_related without assigning it to an attribute. class Person(Model): name = Charfield() @property def latest_photo(self): return self.photos.order_by('created_at')[-1] class Photo(Model): person = ForeignKey(Person, related_name='photos') created_at = models.DateTimeField(auto_now_add=True) first_person = Person.objects.prefetch_related(Prefetch('photos', queryset=Photo.objects.order_by('created_at'))).first() first_person.photos.order_by('created_at') # still hits the database first_person.latest_photo # still hits the database In the ideal case, calling person.latest_photo will not hit the database again. This will allow me to use that property safely in a list display. However, as noted in the comments in the code, the prefetched queryset is not being used when I try to get the latest photo. Why is that? Note: I've tried using the to_attr argument of Prefetch and that seems to work, however, it's not ideal since it means I would have to edit latest_photo to try to use the prefetched attribute. -
change links in tabular inlines not displayed after django-baton installed
Change links, normally appear in each row in tabular inlines, not displayed after django-baton installed. django 1.11 python 3.4 django_baton 1.1 show_change_ling is correctly set. -
SQL raw query django: connection.cursor()
I'm using the code that can be finded in django's documentations Here, with connection.cursor() as cursor: cursor.execute(""SELECT Firstname,LastName FROM TeacherCourse,Teacher WHERE course_name=%s and TeacherCourse.teacher_id=Teacher.id", [course_name]) row = cursor.fetchone() but I don't get the results rows, instead I get <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x0000000006C98948> I do not understand why -
Parsing a django object in template with javascript
I am attempting to read a Django object in javascript. I have serialized the django model object like so: recent_data = leafSamples.objects.filter(field_name=str(fields_distinct[0])).latest('id') recent_data_json = serializers.serialize('json', [recent_data]) Next I have tried to parse the JSON data in javascript: var recentData = {{recent_data_json |safe}}; parsedData = JSON.parse(recentData); console.log(parsedData) However, I keep receiving an error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data When stringified, my data looks like this: [ { "fields": { "copper": "21", "guess": null, "zinc": "32", "chloride": "", "potassium": "2.36", "irrigation": null, "manganese": "19", "calcium": "1.81", "iron": "66", "magnesium": "0.37", "nitrogen": "3.14", "boron": "46", "date": "2018-04-08", "sulfur": "0.33", "field_name": "104A", "age": null, "phosphorus": "0.40" }, "model": "scoutapp.leafsamples", "pk": 1126 } ] How can I parse my data in the "fields" property? I would like to be able to have parsedData.copper return "21," or something to that effect. Thanks! -
Uncaught SyntaxError: Unexpected token true
WHETHER_DJANGO_USER_IS_AUTH = "{{user.is_authenticated|yesno:"true, false"}}"; This code causes an error I have tried try {} catch but it doesn't work for me. It says Uncaught SyntaxError: Unexpected token true thx, everyone. I didn't think about the quote. -
Trying to extend User to UserProfile in form Django
Hi I am having serious trouble this getting this form to work. When I try to run my program it gets to print("4") then throws the error UNIQUE constraint failed: slug_trade_app_userprofile.user_id To be clear the new user i am creating doesnt exist prior to clicking submit on the form It seems like profile is trying to create a new user again but since (i think) user created a new user, that user already exists its throwing the error. HELP!! Views.py def signup(request): if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): print("1") user = user_form.save(commit=False) user.save() print("2") profile = profile_form.save(commit=False) print("3") profile.user = user print("4") profile.save() print("5") user = authenticate(username=user_form.cleaned_data['email'], password=user_form.cleaned_data['password1'], ) login(request, user) return redirect('/home') else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'slug_trade_app/signup.html', {'user_form': user_form, 'profile_form': profile_form}) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='static/profile_pictures', blank=True ) bio = models.TextField(max_length=500, blank=True) on_off_campus = models.CharField(max_length=3, default="on", choices=CAMPUS_STATUS) forms.py class UserForm(UserCreationForm): email = forms.EmailField(required=False) class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'password1', 'password2', ) def save(self, commit=True): user = super(UserForm, self).save(commit=False) user.username = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user … -
ImportError: No module named django.shortcuts
Am using Django for the very first time. I find unresolved reference to django while running the views.py file. Please share your inputs. This is my views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse def hello(request): text = """<h1>welcome to my app !</h1>""" return HttpResponse(text) And the error am receiving is: Traceback (most recent call last): File "/Users/rajorshi/Documents/bha/views.py", line 4, in <module> from django.shortcuts import render ImportError: No module named django.shortcuts -
can locale translate email templates depending on the 'http_host'? django
I have an app, same code but deployed to two different domains let's say one is example.en another one is example.ch I am trying to see if it's possible to use locale from django to do such thing. I got django.middleware.locale.LocaleMiddleware setup in my middleware_class I got all these setup in my settings LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) I have this in my html email template too {% load i18n %} inside my html email template I did something like {% trans "translate testing 123" %} after this, I did the python manage.py makemessages -l en --extension=html so the translation would only go for html (I was going to target a directory but didn't seem to work) I changed the django.po file and it looks like this msgid "translate testing 123" msgstr "测试123??~!~!~!~???" as for my final step, I ran python manage.py compilemessages -l en at first in my View class, I did something like this, if request.META['HTTP_HOST'] == '127.0.0.1:8000': request.session['_language'] = 'en' the 127.0.0.1:8000 was just for developing purpose as if this works, then I can target example.en or example.ch to change the session language then … -
Get object or all in django query_set
I have a model like this: class Product(models.Model): name = models.CharField(_('name')) ... user = models.ForeignKey(User, related_name='products', on_delete=models.CASCADE, verbose_name=_('user')) ... and i want: if the user authenticated: return the user products else if user did not authenticate: return all products in linq C# we can solve this problem with: Product.Where(!request.user.is_authenticated() || user.id == request.user.id) i know that in python can solve it with if else: if request.user.is_authenticated: return Product.objects.filter(user=request.user) else: return Product.objects.all() Question: is there a solution like the C# linq? -
Django REST framework: non-model URLS
I try to implement a tecnologi named "vauld" in my REST api, since the data is secitive(passwods/stuff) i cant store in a DB. So i need to create a non-model "endpoint" in order to store the secrets in the vauld app. But i neet to generate dinamic URLS to store mi "secrests" example: get /secrest/<"value"> By the moment I am capable to get one secret "hadcoded" :P -- viesw.py -- class VaulApiView(APIView): """ API endpoint the allows generate keys and get secrets """ def __init__(self): self.client = hvac.Client(url=os.environ['VAULT_ADDR'], token=os.environ['VAULT_TOKEN']) def get(self, request, format=None): context = self.client.read('secret/foo') return Response(context) def post(self, request, *args, **kwargs): path = request.data.get('path', None) wrap = request.data.get('wrap_ttl', None) if path and wrap: self.client.write(path, baz=wrap ) return Response({"success": True}) else: return Response({"success": False}) -- urls.py -- path('test/', views.VaulApiView.as_view()) -
Overwriting rest-auth RegisterSerializer, add age validation
I'm trying to validate age for user during creation by rest-auth. I managed to add field and save it during registration, but now I'm having hard time to validate if age is < 18. Someone could point me at the way I should do it? I have tried with validation through my AbstractUser model, with @property method, and it was raising ValidationError during registration, but the User account was saving anyway, and i couldn't acces to user detail view because of the ValidationError, so I came to the conclusion that I would just prefer to prevent registration through validation, but it isn't working in my case. class RegisterSerializer(serializers.Serializer): username = serializers.CharField( max_length=get_username_max_length(), min_length=allauth_settings.USERNAME_MIN_LENGTH, required=allauth_settings.USERNAME_REQUIRED ) email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) date_of_birthday = serializers.DateField() ### ADDED BY ME password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) def validate_username(self, username): username = get_adapter().clean_username(username) return username def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_age(self, date_of_birthday): ### ADDED BY ME age = relativedelta(datetime.now(), date_of_birthday).years if age < 18: raise serializers.ValidationError('Must be at least 18 years old to register.') else: return age def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): … -
How to upload multiple files in Django
I'm really struggling to upload multiple files in Django. https://docs.djangoproject.com/en/2.0/topics/http/file-uploads/ I found the above documentation but I'm still confused with that. Here's my codes. boutique/models.py class Photo(models.Model): store = models.ForeignKey(Store) photo = models.FileField(null=True, blank=True, upload_to='boutique/index/%Y/%m/%d') url = models.CharField(max_length=40, null=True, blank=True, verbose_name='Image URL') created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.photo) def get_absolute_url(self): return reverse('cms:photo_edit', args=[self.pk]) cms/forms.py from django import forms class FileFieldForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) cms/views.py from django.views.generic.edit import FormView from .forms import FileFieldForm class FileFieldView(FormView): form_class = FileFieldForm template_name = 'cms/photo_new.html' success_url = reverse_lazy('cms:photo') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: for each in form.cleaned_data['attachments']: Attachment.objects.create(file=each) return self.form_valid(form) else: return self.form_invalid(form) I'm not using Django default admin, so I'm making my own customized admin in the app named cms. I'm bringing Photo model from the app named Boutique. Under cms/forms.py, I put the code to make the upload model to receive multiple files, but it still takes one itme. How can I connect the form code to models? I'm not sure if those codes are enough to implement multiple file uploads. Can anyone check my codes? -
Error: Module build failed: Error: Couldn't find preset "react-app" relative to directory "/[project] frontend"
I am following the tutorials to create a react app using create-react-app. There were a number of dependencies that didn't get installed when loading the webpack-dev-server. I get the following error when I try to npm run start. What does this mean and can anyone tell me what is needed to fix it? Module build failed: Error: Couldn't find preset "react-app" relative to directory "/[Proeject folder]/frontend"