Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django+gunicorn+nginx, django admin return 504 Gateway Time-out
I am working on django+gunicorn+nginx. In the django admin, i am trying to delete an item 'user', which links to quite a lot of data in database, and it returns ' 504 Gateway Time-out' after 60 seconds. Then I tried on changing the config of nginx and the one of gunicorn as below in gunicorn: timeout = 10000 and in nginx proxy_connect_timeout 50000; proxy_read_timeout 50000; proxy_send_timeout 50000; But no matter what i have changed, the server always timeout after 60 seconds! What can i do? I am total clueless... -
Oracle Database in Django
I am working on pip virtual environment and have installed django in it. Now I want to connect it with Oracle Database instead of sqlite3. I have installed cx-oracle(6.2.1), now I am getting problem with Oracle Client. So how to install Oracle Client? I have tried to install Oracle Client but getting error when I run my server. Error:django.db.utils.DatabaseError: ORA-12569: TNS:packet checksum failure -
Multiple file upload at the same time in Django
form.html {% for fields in form %} <div class="control-group"> <label class="control-label" for="{{ field.id_for_label }}"> {{fields.label}}</label> <div class="controls"> {{fields}} {% if fields.label == 'Photo' %} <br> <p></p> <button type="button" class="btn btn-primary success" id="add_new_file">+ Add Another File</button> {% endif %} </div> </div> <script> $("#add_new_file").click(function(){ $("p").append('<input type="file"><br>'); }); </script> For every click in + Add Another File button, another input file option added. Here i use model form to insert into the database.The first one is adder into the db, but how can i add multiple photo or other types files at the same time. views.py if request.method == 'POST': form_values = Registration_Form(request.POST, request.FILES) multiple_files = request.POST print(multiple_files) for file in multiple_files: print(file) if form_values.is_valid(): data = form_values.save(commit=False) password = data.password.encode('utf-8') password = hashlib.sha256(password).hexdigest() data.password = password activation_code = str(random.randrange(0, 999999)) data.activation_code = activation_code data.save() -
Mapping Irregular Imported CSV to Django Models
I have a lot of data that I am trying to import into Django. Some of the files have some information, some have others. I want to import as much information as possible, which is why I am using the objects.update_or_create I've gotten this far, but having to manually edit my import.py for each file seems tedious, and if I want to reuse this over and over I figure there is a better way. here is the current code: #!/usr/bin/env python import csv, os, sys, datetime from dateutil import parser from tqdm import tqdm project_dir = "REDACTED" sys.path.append(project_dir) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django django.setup() from data.models import Email, List, ListIDs filepathname="/REDACTED/demo.csv" data = csv.reader(open(filepathname)) total_rows = len(list(data)) data = csv.reader(open(filepathname)) #for row in data: for row in tqdm (data, leave=True, total=total_rows): if row [0] != 'email': # Currently used to skip the first row, there's got to be a better way though obj, created = Email.objects.update_or_create( email=row[0], defaults={ 'status' : 1, 'domain' : row[0].split('@')[1], 'first_name' : , 'last_name' : , 'gender' : , 'address' : , 'city' : , 'state' : , 'system_added_date' : datetime.date.today(), 'system_updated_date' : datetime.date.today(), } ) some dummy data: email, first name, gender test@test.com, john, M … -
reactjs error - AJAX Failed: SyntaxError: Unexpected token < in JSON at position 0
I get the following error on the console for running the reactjs application. AJAX Failed: SyntaxError: Unexpected token < in JSON at position 0 on the developer tools console window. I got the following error. search-e3e9d0f9da88f042e3cb.js:446 Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server: (client) " data-reactid="18">Medium</div><button (server) " data-reactid="18">Large</div><button s It is wagtail application(it is like Django-cms), in which react module is called inside the wagtail application. The development environment is Ubuntu on aws. Please help me in resolving this issue. I am not able to find the origin of the error. -
Update user profile when user runs view function Python/Django
I am pulling JSON data from Coinbase API when a user clicks a button on the site. When I get the data, I want to save it as a string into the user profile that caused the request. I am using template tags to cause the function to run, it generates the data desired, now I want it to save that data straight to their account all without them doing anything. I am stuck on how to essentially update the current user profile with this string. template_tag.py: from coinbase.wallet.client import Client from django.shortcuts import render from django import template from ico_login.models import UserAddress register = template.Library() @register.simple_tag() def generate_address_btc(): client = Client('api', 'key') r = client.get_addresses('account_stuff') return r['data'][0]['address'] views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from ico_details.templatetags.address_extras import generate_address_btc def save_address(): address = generate_address_btc user = UserProfile() user.address = address user.save() models.py from django.db import models from django.contrib.auth.models import User class UserAddress(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=300) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import UserAddress class UserAddressInline(admin.StackedInline): model = UserAddress can_delete = False verbose_name_plural = 'address' class UserAdmin(BaseUserAdmin): inlines = (UserAddressInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) -
Django admin - How to add a link to table's page that allow set a value for a column
For example, I have a table's page in Django admin as follow: Django admin table I want all devices will have same regulations_url and regulations_version So, I want to add a link button like button "Add Device. This link will point to page that allow change value of 2 columns regulation_url and regulations_version of all devices in table. Does anyone have work around this problem, Thanks! -
Django javascript not working $ is not defined
So, I've been working on a django project (using djagno 1.11) and I saw a really cool chat feature that someone mocked up (using django 2.0) here with their git repo here. I can recreate the entire project following the guide in its own app, but when I add it to my own I get into trouble. My current app uses bootstrap and has javascript to add items to cart and other such things and I wonder if that is getting in the way. That other javascript still works, the new javascript doesnt'. I get your basic error: Uncaught ReferenceError: $ is not defined and when I google search it I see that this means that something is being used before it is defined. I'm decent at python, but an extreme novice at javascript and so I'm not sure what is happening. Diving into the error, I see the following: <script src="https://project.s3.amazonaws.com/static/js/chat.js"></script> <script> // For receiving sender_id = ""; receiver_id = "1"; //For sending $(function () { <<-- This is where the error is pointing to. scrolltoend(); $('#chat-box').on('submit', function (event) { event.preventDefault(); var message = $('#id_message'); send('', '', message.val()); message.val(''); }) }) </script> </div> The above code is at the … -
Django ORM between MySQL and PostgreSQL
I'm learning some django lecture that used postgresql database. But I am familiar with MySQL so I want to use mysql. I heard that Django ORM automatically convert command to query.(So user do not have to know exact database query) I want to know that, Can I use mysql instead of postgresql in this lecture? Any problem with this? -
Slick django debug error?
I've got a Django instance running nicely. An endpoint is secured using jwt . Naturally, I cannot use the browser as it don't know how to send jwt headers, so I use curl which works fine. Now, if something goes wrong, django dump ~2852 lines of html in to my terminal. Can I reduce this somehow? Ideally I would like to just return the same things that's logged when an error returns. Only in debug=True of course. Any pointers? -
Call django custom management command in redis queue
Is it possible to call a django management command as a queued job in redis? This fails for me with: from django.core.management import call_command from rq import Queue queue = Queue(connection=redis_client) job = queue.enqueue(call_command, 'elastic_update') The error I get is: CommandError: Unknown command: 'elastic_update'. Anybody know what I'm doing wrong? This same command works when I run it from the command line or with a shell. -
Why are two arguments provided when I call a parent class method in Python
I am trying to call the cleanse method from ParentSerializer but from the ChildSerializer as seen in the last line. class ParentSerializer(models.ModelSerializer): def cleanse(self): if hasattr(self, 'initial_data'): val1 = self.initial_data['name'] val2 = self.initial_data['age'] val3 = self.initial_data['city'] return self.initial_data class ChildSerializer(GenericSerializer): def is_valid(self, raise_exception=False): if hasattr(self, 'initial_data'): super(ChildSerializer, self).cleanse(self) error: TypeError: cleanse() takes 1 positional argument but 2 were given Why is this not working? -
Passing a list into MultipleChoiceField form as initial value
I've got a field called 'service'. It stores a list of ints that are representative of the services that a company offers (1=accounting, 2=HR, etc.). Once the list is saved to the 'service' field, I want to be able to pass it in as an 'initial' value to the form so that the user can see what options they previously selected. What works: a) User can select services b) Services are saved to the 'service' field as a list of ints (eg. [2,3,5] What doesn't work: When I try to pass the 'selectedservice' field into the form, I'm told that there is an error in my forms.py: NameError: name 'selectedservices' is not defined Essentially, I'm not sure how to pass a list into a form :( model.py class BaseServicesOffered(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) service = models.CharField(max_length=255, default='', null=True, blank=True) def __str__(self): return self.user.username form.py class BaseServicesOfferedForm(forms.ModelForm): service = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, **initial=selectedservices**) def __init__(self, *args, **kwargs): user = kwargs.pop('user') **selectedservices = kwargs.pop('selectedservices')** super(BaseServicesOfferedForm, self).__init__(*args, **kwargs) self.fields['service'].choices = [(t.id, t.service) for t in AllServices.objects.filter(industrycode=user.userprofile.industry)] class Meta: exclude = ('user',) model = BaseServicesOffered views.py @login_required(login_url="/accounts/login/") def baseservicesoffered(request): try: base_services_offered = BaseServicesOffered.objects.create(user=request.user) except: pass user = request.user services = user.baseservicesoffered.service instance = get_object_or_404(BaseServicesOffered, user=user) … -
Set password field in GenericViewSet Django
I want to create a user in one of my views and store the user password hashed. class DetailedUserViewSet(CreateModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) def __init__(self, *args, **kwargs): super(DetailedUserViewSet, self).__init__(*args, **kwargs) def create(self, request, *args, **kwargs): response_data = {'message' : 'Invalid data'} validated_data = self.request.data user = User(username=validated_data['email'], is_active=True, email=validated_data['email']) user.set_password = validated_data['password'] user.save() profile = UserProfile(mobile=validated_data['mobile'],user=user) profile.save() token = Token.objects.get(user=user) response_data['message'] = 'OK' response_data['token'] = token.key return Response(response_data, status=status.HTTP_201_CREATED) user.set_password is usually used within serializers, but in my case I want to also have extra info in my request such as token/message. This doesn't seem to be doing anything on my password field. Maybe I have to do it in my serializers? If so how? -
python django-autocomplete-light UnorderedObjectListWarning
I've been doing website using Django lately and I encountered difficulties in implementing chained drop-down / dependent drop-down. I tried smart-selects but couldn't implement it, that's when I stumbled with django-autocomplete-light. I was able to implement this and it fits my current requirement, however, I haven't noticed that python is throwing this warning until recently: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'project.models.Driver'> QuerySet. I followed tutorial from the django-autocomplete-light thoroughly and I'm still missing something. forms.py class TripModelForm(forms.ModelForm): driver = forms.ModelChoiceField( queryset=Driver.objects.all(), widget=autocomplete.ModelSelect2(url='driver_autocomplete', forward=['hauler']) ) class Meta: model = Trip fields = ['ticket', 'date_issued', 'department', 'hauler', 'plate_number', 'driver',] urls.py urlpatterns += [ path('driver-autocomplete/', views.DriverAutocomplete.as_view(), name='driver_autocomplete'), ] views.py class DriverAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Driver.objects.none() qs = Driver.objects.all() hauler = self.forwarded.get('hauler', None) if hauler: qs = qs.filter(hauler=hauler) if self.q: qs = qs.filter(name__istartswith=self.q) return qs -
Migration doesn't have User field
I am attempting to add a User field to a model, but it's not being generated in the migration file. // models.py from django.db import models from django.contrib.auth.models import User class Foo(models.Model): """This class represents the Foo model.""" name = models.CharField(max_length=255, blank=False, unique=True) owner = models.OneToOneField(User, related_name='foos', on_delete=models.CASCADE), date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): """Return a human readable representation of the model instance.""" return "{}".format(self.name) I run python3 manage.py makemigrations and get this output: // 0001_initial.py migrations.CreateModel( name='Foo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, unique=True)), ('date_created', models.DateTimeField(auto_now_add=True)), ('date_modified', models.DateTimeField(auto_now=True)), ], ), Anyone have an idea what to do here? Should one avoid using the Django-supplied User object and just create your own? -
How do I notify a user of insufficient funds and wait for them to top up?
I am kind of new to Python and Django. I'm creating a web service to send vouchers which are in three categories thirty,fifty and hundred. Each of these vouchers are stored in their own models. The payment gateway sends an Instant Payment Notification to my website which I then process and filter the amount and phone number from the JSON in a separate app. Here is my code for the models(Model thirty only.) from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ValidationError from django.urls import reverse from django.db import models from django.utils import timezone, formats from timezone_field import TimeZoneField from django.core.validators import RegexValidator import arrow class Thirty(models.Model): voucher_regex = RegexValidator(regex=r'\d{5}[-]\d{5}', message="Voucher must be entered in the format: '99999-99999'. Up to 12 digits allowed.") name = formats.sanitize_separators(models.CharField(validators=[voucher_regex], max_length=17, blank=True)) # validators should be a list time = models.DateTimeField(auto_now_add=True) time_zone = TimeZoneField(default='Africa/Nairobi') used = models.BooleanField(default=False) task_id = models.CharField(max_length=50, blank=True, editable=False) def __str__(self): return 'Voucher #{0} - {1}'.format(self.pk, self.name) def get_absolute_url(self): return reverse('view_voucher', args=[str(self.id)]) def send_sms(self): """Starts a Celery task to send a voucher to the person who paid""" # Sends a voucher transaction_id = #comes from an external app model(should be unique each time) amt = #comes from external … -
Make certain field not need to be validated django
class DetailedUserViewSet(CreateModelMixin, GenericViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) def __init__(self, *args, **kwargs): super(DetailedUserViewSet, self).__init__(*args, **kwargs) self.fields['lit_points'].required = False self.fields['picture'].required = False class UserSerializer(HyperlinkedModelSerializer): picture = CharField(source='userprofile.image_url') password = CharField(write_only=True) mobile = CharField(source='userprofile.mobile') lit_points = IntegerField(source='userprofile.lit_points') location = SerializerMethodField() class Meta: model = User fields = ('id', 'mobile', 'first_name', 'last_name', 'email', 'password', 'picture', 'lit_points', 'location') readonly_fields = ('picture', 'lit_points', 'location') Right now it says fields is not defined. When I get rid of the fields option; it gives me "lit_points" = ( "This field is required." ); picture = ( "This field is required." ); I'm trying to do so those 2 fields aren't mandatory on the POST request. ERROR: AttributeError: 'DetailedUserViewSet' object has no attribute 'fields' -
Approach for sharing data between two URL patterns in Django
I want to have two URL patterns in my Django project. I use http://localhost:8000/complete for displaying completions as the user types a query in the search box provided. When they submit the query, I want to redirect the form data to http://localhost:8000/search. The challenge is that I have a logging mechanism running in my complete view, I want to dump the data I logged when they press submit on the search page. I am not able to figure out a neat approach to doing this. So far, I was resorting to a simple hack. I pass the payload with different names and callback http://localhost:8000/complete in both cases and use the following code. def complete(request): prefix = request.GET.get('q','') submitted = False mode = request.GET.get('mode','') if len(mode) == 0: # Hack to detect submit mode = request.GET.get('rb', '') submitted = True # and call the function to write the logs to a file. What will be a really neat approach to doing this? -
Why is my Django Python Model not displaying the nested json to the view?
I have been trying for a while to get a working API call to the blacklist website, hetrixtools (https://docs.hetrixtools.com/blacklist-check-api/), to just set up a simple API call, using an ip address, just so I can learn how to do API calls. I have followed guides on how to set up the seriliazers, models, forms, views and the html itself but I have not found any solution as to why it is not displaying the nested json. It displays the top level json perfectly fine, but when I try to nest my model it doesn't work. I have tried many=true, depth, readonly but none of them make a difference. What am I doing wrong to get the nested data? views.py def save_blacklist(request): if request.method == "POST": form = SubmitBlacklist(request.POST) if form.is_valid(): ip = form.cleaned_data['ip'] r = requests.get('https://api.hetrixtools.com/v2/' + settings.API_KEY + '/blacklist-check/ipv4/' + ip + '/') json = r.json() print(json) serializer = BlacklistCountSerializer(data=json) if serializer.is_valid(): blacklist = serializer.save() return render(request, 'blacklists.html', {'blacklist': blacklist, 'ip': ip}) else: form = SubmitBlacklist() return render(request, 'index.html', {'form': form}) serializer.py class BlacklistNamesSerializer(serializers.ModelSerializer): class Meta: model = BlacklistNames fields = ('id','blacklist_name', 'direct_link') class BlacklistCountSerializer(serializers.ModelSerializer): blacklists = BlacklistNamesSerializer(many=True) class Meta: model = BlacklistCounts fields = ('id','status', 'api_calls_left', 'blacklist_check_credits_left', 'blacklists') … -
Django - Check an integer must to start with 9 and length is 10
Where is my mistake? mobile = forms.IntegerField( label='Mobile', widget=forms.NumberInput(attrs={ 'class': 'form-control', 'required': 'required' }), error_messages={ 'invalid': 'Required', } ) def clean_mobile(self): mobile = self.cleaned_data['mobile'] if not re.match('^((?!([0-8]))[0-9]{9})$', str(mobile)): self.add_error('mobile', 'Wrong number') return mobile Always returns False! -
Django - Uploading sensitive data/images
I was wondering how, in a Django project, if a user was to upload a picture (such as a passport or ID card) for verification purposes - how might I prevent others from going to the /media/... url for that file and then viewing this sensitive data? i.e. could you do some sort of if statement that prevents any type of user from going to a specific url, but not all of the /media/ paths since some media may be allowed to be publicly viewable? -
Django multiple profiles
In what way can a Student submit an assignment to a particular Teacher(teaching a particular course)... What relationship we they have?? model.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to='media/pictures/', blank=True) regex = RegexValidator(r'^\d{2}/\d{4}', message='Required. 7 characters or fewer. This value must contain only numeric and slash.') matric_no = models.CharField(validators=[regex], blank=True, null=True, max_length=7, unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list address = models.CharField(max_length=150, blank=True) birth_date = models.DateField(null=True, blank=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to='media/pictures/', blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list address = models.CharField(max_length=150, blank=True) birth_date = models.DateField(null=True, blank=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=False, default='M',) def __str__(self): return str(self.user) maybe something like user messaging or mailing (User to User)... -
django 2.0 error (admin.e202) 'accounts.CustomUser' has no field named 'accounts.CustomUser'
im fairly new to django and im currently trying to make a web app that builds a new user profile everytime a new user is created upon site registration, however i keep getting the following error when trying to migrate that says, "class 'accounts.admin.CustomUserInline'>: (admin.E202) 'accounts.CustomUser' has no field named 'accounts.CustomUser'.": class 'accounts.admin.CustomUserInline'>: (admin.E202) 'accounts.CustomUser' has no field named 'accounts.CustomUser'. can anyone tell me what im doing wrong? ive been trying to sort this out for 2 days now to no avail. heres the code i have so far: settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'localflavor', 'crispy_forms', 'accounts', 'pages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'studybuddy_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, … -
Count of queryset where foreign key occurs exactly n times
If I have a django model with a foreign key, e.g: class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) is there a way for me to get a count of the number of reporters that have exactly n articles on a specific date? For example, how many reporters have published exactly 2 articles "today" date = timzone.now().date() articles_on_date = Article.objects.filter(pub_date=date) # now what can I do?