Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
setting up let's encript certificate at AWS EC2 server
I'm new to VPS and Linux but I'm now at school and for a project need to use GEOlocation with Django so I need to set up a VPS. I did AWS EC2 server and now I need to add SSL certificate as it a requirement to ask the user for GPS permissions and I'm stuck . i folowed the instructions on here : https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/SSL-on-amazon-linux-2.html#letsencrypt I did set up my domain name in GoDaddy and its working. this is the error I'm getting : *> Obtaining a new certificate Performing the following challenges: http-01 challenge for [my domain] http-01 challenge for [my domain] Waiting for verification... Challenge failed for domain [my domain] Challenge failed for domain [my domain] http-01 challenge for [my domain] http-01 challenge for [my domain] Cleaning up challenges Some challenges have failed. IMPORTANT NOTES: - The following errors were reported by the server: Domain: [my domain] Type: connection Detail: Fetching http://[my domain]/.well-known/acme-challenge/g-1VnWMVEKIwAeV0AExkr21aWKtOC6tdTMdbFbBisTE: Timeout during connect (likely firewall problem) Domain: [my domain] Type: connection Detail: Fetching http://[my domain]/.well-known/acme-challenge/uDE6LFBwGINiZmsULN45PxPK_V48w3NCeoVqv4_ylLY: Timeout during connect (likely firewall problem) To fix these errors, please make sure that your domain name was entered correctly and the DNS A/AAAA record(s) for that domain contain(s) the … -
Issue creating a django user with python-social-auth with a custom User model and UserManager
Seems like this isn't a unique problem, but I'm missing something in the solution. I'm using python-social-auth and logging in with Google. All seems to be going well, until it gets to the create_user part of the pipeline. I do have a custom User model and UserManager. On my User model I do have a role property that is hooked up to some choices. When social auth kicks in and logs someone in, it does call create_user in my User manager, however it's only passing email, and no additional fields. I was attempting to hook into the pipeline and add the required role property by adding it to the details social auth dict, but that doesn't seem to have any effect. How should I go about hooking into the create user property to add fields that won't exist as far as social auth is concerned? User Model class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) email = models.EmailField(_("email address"), unique=True) first_name = models.CharField(max_length=240, blank=True) last_name = models.CharField(max_length=240, blank=True) role = models.IntegerField(choices=RoleChoices.choices) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email @property def full_name(self): return f"{self.first_name} {self.last_name}".strip() And … -
How to create single profile for each multiple user?
My app has two different user. 'Teacher' and 'Student'. I want to create profile for each user. 'Student's profile' for student and 'Teacher's profile' for teacher. I'm using post_signal to create 'Student's profile' and 'Teacher's Profile' but when a student user or a teacher signs up, two profiles are created, 'Teacher's profile' and 'Student's Profile'. Is there some logic to prevent this? -
App works but the Django Admin page is not accessible - DoesNotExist at /admin
So everything was working fine. Now I get > DoesNotExist at /admin > IsoControls matching query does not exist. In my console Traceback (most recent call last): File "C:....\exception.py", line 34, in inner response = get_response(request) File "C:\.....\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:.....\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\.....\controls_app\views.py", line 26, in testing testing_sheet = IsoControls.objects.get(slug=slug) File "C:\.....\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\.....\models\query.py", line 415, in get raise self.model.DoesNotExist( controls_app.models.IsoControls.DoesNotExist: IsoControls matching query does not exist. So I checked line line 26 in views.py. Which is: if request.method == "GET": testing_sheet = IsoControls.objects.get(slug=slug) form = forms.ControlTesting(instance=testing_sheet) return render(request, 'controls_app/testing_sheet.html', {'form':form, 'testing_sheet':testing_sheet}) else: testing_sheet = IsoControls.objects.get(slug=slug) form = forms.ControlTesting(request.POST, instance=testing_sheet) if form.is_valid(): form.save() return render(request, 'controls_app/testing_sheet.html', {'form':form, 'testing_sheet':testing_sheet}) the local site works just fine. Only if I go to the /admin page - I get these errors. I cannot access the admin page anymore. -
Django: Trouble with Logging
I configured my logging setting in Django as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {module} {message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'simple' } }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } I use it as as follows in my app views.py: import logging # --------------------------------------------- DEVELOPMENT CODE ------------------------------------------------------# log = logging.getLogger(__name__) def form_valid(self, form): """Redirects to get_success_url() when the form is valid.""" print('got here') activemq_send('This is a test') log.info('hello world') ... When I run my development server, I don't get the log message. Just the print statement. What am I dong wrong? INFO basehttp "GET /traceupload/load_product_config/?product=1 HTTP/1.1" 200 134 INFO basehttp "GET /static/img/favicons/site.webmanifest HTTP/1.1" 304 0 INFO basehttp "GET /static/img/favicons/favicon-16x16.png HTTP/1.1" 200 368 INFO basehttp "GET /static/img/favicons/favicon-32x32.png HTTP/1.1" 304 0 got here INFO basehttp "POST /traceupload/ HTTP/1.1" 302 0 INFO basehttp "GET /traceupload/ … -
Database: new table or new field for order attributes
Current table schema: User - id - default_handling_fee(integer, null=True) Order - id - buyer(user_id) - order_handling_fee(integer, null=True) We now want to add a second type of fee that can apply to orders. Some rules: Fees apply to < 10% of orders. An order can have 0, either, or both fees. Every time order info is displayed to users, we need to highlight fees and show the types of fees. Fees must be editable on an order-by-order basis. We may add additional fees going forward. The db is currently pretty small (a few thousand rows) and unlikely to grow beyond 100k in the next few years. I can see two options: A: Add a new field on order and one on user: User - id - default_handling_fee(integer, null=True) - default_processing_fee(integer, null=True) Order - id - buyer(user_id) - order_handling_fee(integer, null=True) - order_processing_fee(integer, null=True) or B, add a new 'fees table': User - id Order - id - buyer(user_id) - order_fees(many_to_many_field to OrderFees) OrderFees - id - buyer(user_id) - price(integer) - fee_type(choices=['handling', 'processing']) - is_default_value(boolean) If a user creates an order and applies one or both of the fees, in option B (new table), we would first look for existing fees that match … -
Heroku and Django: How to use file server for storing and editing user files
I built a Django app that has some .txt files in a folder on under the project root dir as shown below. <pre> [projectname]/ ├── [projectname]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py ├── [<b> myfiles </b>]/ │ ├── file1.txt │ ├── file2.txt │ ├── file3.txt │ └── file4.txt └── [myApp]/ </pre> I specify the files paths when I am running the django app on my local machine. Now, I tried running my app on Heroku, but the not app does not work when I tried reference any of my files to do some processing. Is there a way that I can use a file server (external or internal to Heroku) where I can store my files on and then update them in via the django app (by the users) and save them back to file server? In my app, when a user creates a new project, in the background a function will create a folder for the user and then copy the files in [myfiles] folder to the user's new project folder. Also, users can enter data through forms that I want to to save to .rdf files and then save to … -
DJANGO - convert POST data to JSON and render HTML partially
I'm stuck trying to convert data from the AJAX call to view.py and back to HTML: JQuery/Javascript function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $(document).ready(function(){ var csrftoken = getCookie('csrftoken'); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); // AJAX CALL TO VIEW $('a.play').click(function(e){ e.preventDefault(); var song_id = $(this).attr('id'); $.ajax({ url: $(this).data('href'), type: 'POST', content: 'application/json; charset=utf-8', data: { 'song_id': song_id }, dataType: 'json', success: function(html) { $('.player').replaceWith(html) }, }); }); }); views.py from django.shortcuts import render from django.http import Http404, JsonResponse from django.core import serializers from django.template.loader import render_to_string from .models import Song def change_song(request): if request.method == "POST": request.session['featured_song'] = request.POST.get('song_id', '') featured_song_id = request.session['featured_song'] obj = Song.objects.get(pk=featured_song_id) song_list = Song.objects.all().order_by('-date') # list of objects context = { "featured_song": … -
Why i can't change my database objects in django/sqlite?
I got the error below when I try to see my products in Django admin panel. Django error discription At line 34 of base.py is a function: def decoder(conv_func): """ Convert bytestrings from Python's sqlite3 interface to a regular string. """ return lambda s: conv_func(s.decode()) I don't have an idea how to fix this bug -
Is there a way to register or record the changes made in the database with Django?
I'm using MySQL as database for this app and I need to register or keep the record of all the changes made in one field of my User Model. For example, every ten minutes I have a bot asking to an API some fields and everytime it PATCH the date field inside User Model. I need to keep record of that minute everytime it changes. -
Django LayerMapping: How to filter shape-file before saving to database
I have a shape-file which I want to import to a django database using the Django-LayerMapping module (Link to module), because it transforms the spatial data into GeoDjango models. The vanilla way to import a shape-file to the db according to the tutorial is as follows: lm = LayerMapping(table, path, mapping, transform=True , encoding='utf-8') # load shape-file lm.save(verbose=True) # save entire file to db But in my case, the table to which I want to import the shape-file data is not empty. I only want to add those rows (or features in shape-file lingo) to the db which are not already present. However, the LayerMapping only provides a method to save an entire shape-file to the db, not single entries, which would result in duplicates in my case. Thus, my question is: how can I filter the entries of a layer mapping-object before saving it? Until now, I thought about two possible solutions: Filter the entries in the layer mapping object and saving the entire object with the .save()-method that is provided. But I don't know how to delete single entries from a layer mapping object. Iterate through all entries in the layer mapping object and check for each if … -
What is the simplest way to include Facebook authentication with Django?
I'm currently making a website with django, and I want users to be able to log in with Facebook (and in fact I don't want any other way to log in). I tried to do this using social-auth-app-django. It was easy to implement, but when I clicked the 'log in with Facebook' link on my website, I got this error when redirected to Facebook: Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings. I'm pretty sure I had included the domains though. This question seems to be the same issue, but I think it's for a different library, and the solution seems a bit hacky. As far as I can tell the problem is something to do with social-auth-app-django not being up-to-date with Facebook's stricter GDPR requirements? I'm very new to web development, so could somebody please tell me how to implement Facebook login easily? Is there a simple library that's more up-to-date and won't cause problems? -
Django views print dictionary values of linked keys
In Django views, how to print values of a dictionary identified by a key stored in another dictionary, linked keys? I have d1 = {'d2item1':{'key1':'d2key1'}} d2 = {'d2key1':'something', 'sub': {'d2key1': 'subitem'}, 'd2item1':'data'} iterate, traverse on d1 to retrieve buried value of key1 i.e d2key1 use value of key1 for retrieving the value from d2 Views {% for i, v in d1.items %} <a>{{ // retrive d2 values using key `d2key1`, expected `something` //}}</a> <a>{{ // retrive d2 values using key `d2key1`, expected `subitem` //}}</a> <a>{{ // retrive d2 values using key `d2item1`, expected `data` //}}</a> {% endfor %} -
Django rest framework post request not retrieving anything
I am trying to create a user creation api and post create api, the 'Get' request works fine but the post request is always empty. If there is anything I missed or need to add to the views, because the get request works fine for the post app. What could be the possible errors that are occuring. Serializer.py from rest_framework import serializers from .models import User class RegisterSerializer(serializers.ModelSerializer): password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['username', 'email', 'date_of_birth', 'password', 'password2'] extra_kwargs = {'password': {'write_only': True}} def save(self): print("saved") user = User(email=self.validated_data['email'], username=self.validated_data['username'], date_of_birth=self.validated_data['date_of_birth'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError( {'password': 'Passwords must match.'}) user.set_password(password) user.save() return user Below is the views.py from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .models import User from .serializers import RegisterSerializer from rest_framework.authtoken.models import Token from rest_framework.parsers import JSONParser @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegisterSerializer(data=request.data) data = {} if serializer.is_valid(): print("Hello") user = serializer.save() data['response'] = 'Successfuly registered a new User' data['date_of_birth'] = user.date_of_birth data['username'] = user.username data['email'] = user.email token = Token.objects.get(user=user) data['token'] = token return Response(data) else: return Response(serializer.errors) No … -
Any way to break nested loop in django templete or any thing similar like this
Is there is any way to break my nested loop in django templete because in my loop i have 5000 rows data and every time I have to pick some data from the loop according to my condition therefore it takes so much time to showing the data on my web page Or any other way {% for data in data1 %} <!-5000 rows--> {% for i in indexes %} <!-100 rows--> {% if forloop.parentloop.counter0 == i %} <p>{{data}} {{forloop.parentloop.counter}}</p> {% for count in mainList %} <!-5000 rows--> {% if count.0 >= i %} <h3>{{count.1}} {{count.2}}</h3> {% endif %} <!--break--> {% endfor %} {% endif %} {% endfor %} {% endfor %} -
Django How to save into the database using Selected option?
I am using Django Framework and my database is Postgres, I would like to know if it is possible to save the record to the database using the Selected option, if possible, please create a simple example -
Django bulk_create throws IndexError
I'm trying to write data in my database (I'm using postgresql) by uploading a csv file through Django. Said file doesn't have a fixed amount of rows, but it may be a large amount, so I need to make the uploading fast. However, no matter the size of the file, I keep getting a list index out of range error. This is the relevant part of my code: csv_file = request.FILES.get('file', False) data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) # delete existing data in our db MyModel.objects.all().delete() # write the data text = csv.reader((line.replace('\0', '') for line in io_string), io_string, delimiter=',', quotechar='"') instances = [ MyModel( field1=column[0], field2=column[1], ... ) for column in text ] MyModel.objects.bulk_create(instances) I don't know how to fix it. The Traceback highlights the line "for column in text". Any help is appreciated. -
fetch ids with commas in django
view.py def get(self, *args, **kwargs): res = Question.objects.all() # queryset = super().ListAPIView(*args, **kwargs) if 'tag' in self.request.GET: # split and directly put in main query res = res.filter( Tag_name=self.request.GET['tag'] ) if 'order_by' in self.request.GET: res = res.order_by( self.request.GET['order_by']) serializer = QuestionSerializers(res, many=True) return Response(serializer.data) here I am trying to fetch question with some input tag ids and order by some input , how can I use multiple tag ids in url like http://127.0.0.1:8000/?tag=1,2&order_by=name so I get all objects with tag ids 1 and 2. -
Why is `data` empty in nested serializer validate method?
I am using Django REST Framework. I have a parent serializer class like so: class MyParentSerializer(serializers.Serializer): # Use custom serializer as a field. my_field = MyFieldSerializer( required=False, ) name = serializers.Charfield() } def validate(data): # validation logic And then my child serializer that is used above looks like this: class MyFieldSerializer(serializers.Serializer): email_address = serializers.ListField( required=False, child=serializers.CharField(), ) phone_number = serializers.ListField( required=False, ) def validate(self, data): data <-- <-- This is empty if I pass in random invalid data! check_for_undefined_fields(self.data, self.fields) return data Now, I pass the following data: { "my_field": { "invalid_field": "foo"}, "name": "bar" } However, if I check data in the validate method in my MyFieldSerializer class during validation, IT'S EMPTY! Why? How can I fix this so that data is actually the data I passed? -
Django ManyToMany relation - check for existence?
I am currently learning Django and building a twitter-like app for that purpose. I have used a ManyToManyField in my Profile model to reflect followers as such: models.py class Profile(models.Model): """ Extension of User model to save additional information """ user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) followers = models.ManyToManyField('self', related_name='Followers', blank=True, symmetrical=False) follower_count = models.IntegerField(default=0) following_count = models.IntegerField(default=0) Now I am trying to check if a user is already following another user (when opening the profile so that I can display the correct follow/unfollow button there) views.py def profile(request, username): try: user = User.objects.get(username=username) user_profile = Profile.objects.get(user_id=user.id) except ObjectDoesNotExist: raise Http404("User does not exist") is_following = True if user.id in Profile.followers.all() else False return render(request, 'songapp/profile.html', {'user_profile': user_profile, 'user' : user, 'is_following': is_following}) The issue lies within Profile.followers.all() As I get the following AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' I already used the search function and read through results up to 8 years old but I either did not find or understand the corresponding answer. Any help is highly appreciated -
Django 3 combine DetailView and items (ListView) from ManyToMany relationship in one template
I'm working on a Django 3 project where I'm trying to link people to the products they use. The end goal is to display a detailed view of the person (DetailView) and include the list of products they use (ListView?). Here's what I have in my models, views, and template: # models.py (omitting non-relevant fields) class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=75, db_index=True) products = models.ManyToManyField('Product', through='PersonProduct') class Product(models.Model): name = models.CharField("Product Name", max_length=75) class PersonProduct(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now) # views.py class PersonDetailView(DetailView): model = Person queryset = Person.objects.all() template_name = 'person_detail.html' # person_detail.html (simplified for clarity) {% extends 'base.html' %} {% block content %} <div class="person-detail"> <h2>{{ person.first_name }} {{ person.last_name }}</h2> </div> <div class="gear-list"> <ul> <!-- This is where I'm stuck. I know I need to iterate over the products that are associated with the person, but I can't figure out how to do it. --> </ul> </div> {% endblock content %} The page renders the person's detailed information just fine, but there is nothing at all there for the products he/she uses. I have confirmed that the "PersonProduct" junction table has product entries for the particular person I'm … -
Django rest framework endpoints and passing the values
i am very new to Django and REST. I started working with rest-auth recently just to explore. Can someone explain me, what does this mean and how do i pass the values. rest-auth/ ^password/reset/$[name='rest_password_reset'] -
django admin form widget do not update dynamically
i wanna load jsonschema dynamicaly into one of my admin form widget so this is my code: model.py: class Product(models.Model): name=models.CharField(max_length=255,null=False,blank=False) description=models.TextField(max_length=500,null=True,blank=True) category=models.ForeignKey(Category,null=False,verbose_name='دسته',on_delete=models.CASCADE) values = JSONField() brand=models.ForeignKey(Brand,on_delete=models.CASCADE,null=True) def __str__(self): return self.name class Category(models.Model): category_name=models.CharField(max_length=255,unique=True) type = models.ForeignKey(Type, on_delete=models.CASCADE) attributes_Schema_name = models.CharField(max_length=255) def __str__(self): return self.category_name change_form.html: {% extends "admin/change_form.html" %} {% block extrahead %} {{ block.super }} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" charset="utf-8"> $(function(){ // inspect html to check id of category select dropdown. $(document).on('change', "select#id_category", function(){ $.get($(location).attr('href'),{id: $(this).val()}); }); }); </script> {% endblock %} admin.py: class ProductJSONModelAdminForm(forms.ModelForm): def __init__(self, *args,request=None, **kwargs): cat_id = int(kwargs.get('initial')['id']) if 'id' in kwargs.get('initial') else 1 DATA_SCHEMA_name = Category.objects.values_list('attributes_Schema_name', flat=True).get(id=int(cat_id)) with open("attSchemas/{0}".format(DATA_SCHEMA_name)) as jfile: DATA_SCHEMA = json.load(jfile) super().__init__(*args, **kwargs) self.fields['values'].widget= JSONEditorWidget(DATA_SCHEMA) class Meta: model = Product fields = "__all__" @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): form = ProductJSONModelAdminForm inlines = [productUnitInline, productImageInline] but the problem is ,when i change category dorpdown ,nothing will not change in product form .i even debug my code and i am sure below line is executed when dropdown selected change self.fields['values'].widget= JSONEditorWidget(DATA_SCHEMA) but nothing will change in form .what is the problem ? -
Django DRF serializer Custom relational fields What should to_internal_value do and return?
I'm trying to implement something very similar to Djang Rest Framework tutorial Custom relational fields. For the reminder, the provided code snippet is: import time class TrackListingField(serializers.RelatedField): def to_representation(self, value): duration = time.strftime('%M:%S', time.gmtime(value.duration)) return 'Track %d: %s (%s)' % (value.order, value.name, duration) class AlbumSerializer(serializers.ModelSerializer): tracks = TrackListingField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] And "This custom field would then serialize to the following representation" (quoted in the tutorial): { 'album_name': 'Sometimes I Wish We Were an Eagle', 'artist': 'Bill Callahan', 'tracks': [ 'Track 1: Jim Cain (04:39)', 'Track 2: Eid Ma Clack Shaw (04:19)', 'Track 3: The Wind and the Dove (04:34)', ... ] } I understand that and have implemented it for my particular case. What I don't understand is the way to implement to_internal_value(self, data) as I want to provide a read-write API. What should to_internal_value(self, data) return? If we post the JSON structure above, to_internal_value(self, data) will be called once per track with 'Track 1: Jim Cain (04:39)'... for data values. I don't see how we can update the tracks model from those data values. -
Cant Compare Django IntegerField to Int?
So I'm doing the following: If MyModel.IntField < 3: Do Something And I get the error: TypeError: '<' not supported between instances of 'IntField' and 'int' It seems strange to me that you cannot compare integerfields and integers, so I'm assuming I'm doing something wrong? If not, how can I compare an IntField to an Int? Thank you