Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Annotate distinct foreign ManyToMany relation
Given the following simplified model setup class Tag(models.Model): name = CharField() class Template(models.Model): name = CharField() tags = ManyToManyField(Tag) class Collection(models.Model): name = CharField() templates = ManyToManyField(Template) class GenericViewSet(viewsets.ModelViewSet): def get_queryset(): ... queryset = Collection.objects.all() queryset = queryset.annotate(tags=models.Distinct('templates__tags')) ... Is there a way similar to the last line above to annotate a Collection queryset with a distinct set of tags originating from its templates? Example (Template): name: History 1 tags: [England, France] (Template): name: History 2 tags: [England, United States) (Collection): name: History of England templates: [History 1, History 2] tags: [England, France, United States] Where the collections tags are derived from its templates. -
Unable to Login to Admin Panel in Django using Custom User Model
I have created a custom user model that overrides the default AUTH_MODEL in settings.py. I am unable to login on the admin panel using python manage.py createsuperuser. The message that the admin throws back at me is: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. Below is my code for models.py: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from django.contrib.auth.hashers import make_password from phonenumber_field.modelfields import PhoneNumberField class UserAccountManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, phone, password=None): if not email: return ValueError("User must have an email address!") if not username: return ValueError("User must have a username!") if not first_name: return ValueError("User must have a first name!") if not last_name: return ValueError("User must have a last name!") if not phone: return ValueError("User must have a phone number!") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, phone=phone, ) hashed_password = make_password(password) user.set_password(hashed_password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, phone, password): user = self.create_user( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, phone=phone, password=password, ) user.is_admin = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser): username = models.CharField(null=False, blank=False, max_length=30, unique=True) first_name = models.CharField(null=False, blank=False, max_length=50) last_name = models.CharField(null=False, blank=False, max_length=50) email = models.EmailField(null=False, blank=False, unique=True) … -
Store JWT tokens in cookies with django-rest-framework-social-oauth2 library
I wanted to securely store my JWT token. Up until now, I have used local storage, but I have read that using local storage is not secure. Hence, I wanted to start using HttpOnly cookies to store my JWT tokens. I was going to use CSRF protection inbuilt into Django to mitigate the security issues with cookies. However, I can't figure out how to use cookies with the Django-rest-framework-social-oauth2 library. There doesn't need to be any other library that has social auth and JWT auth. So my first question, is there a secure storage method that doesn't need cookies. If not, how does use django-rest-framework-social-oauth2 library with cookies? -
How not to skip what follows hashtags in django admin search field?
In Django admin, there is the search bar for list_display page of objects. Lets say there is search_fields = ["name"] for given admin. If there is an object with the name "abc" and the search term is "ab", an object is returned. however, when there is a name "abc#deg" and "ab" is searched for, doesn't return any. Seems like the Django admin search bar perceives # as a special character for setting parameters or something, does anyone know how to avoid this? Any hint would be much appreciated! -
Django/PythonAnywhere -- Getting Error "Something went wrong :-("- Debugging Tips
I am new and learning Full Deployment walkthrough on python Anywhere, But getting the Error. I have tried all possible things which I could do to resolve it but I am stuck here. where supriya25 is my directory name Error is: **Something went wrong :-(** Something went wrong while trying to load this website; please try again later. If it is your site, you should check your logs to determine what the problem is. There was an error loading your PythonAnywhere-hosted site. There may be a bug in your code. Error code: Unhandled Exception **Debugging tips** -The first place to look is at your web app page to ensure that there are no errors indicated there. -Next, check your site's server and error logs for any messages — you can view them here: -supriya25.pythonanywhere.com.error.log -supriya25.pythonanywhere.com.server.log -You can find helpful tips on the PythonAnywhere help site: -There's an ImportError in the logs -"403 Forbidden" error or "Connection Refused" error in logs -Database connection errors -There are many more helpful guides on our Help pages If you get completely stuck, then drop us a line at support@pythonanywhere.com, in the forums, or use the "Send feedback" link on the site, with the relevant … -
Is there a best practice for storing data for a database object (model) that will change or be deleted in the future (Django)?
I am building an order management system for an online store and would like to store information about the product being ordered. Now, if I use a Foreign Key relationship to the product, when someone changes the price of the product or deletes it, the order will be affected as well. I want the order management system to be able to display the state of the product when it was ordered even if it is altered or deleted from the database afterwards. I have thought about it long and hard and have come up with ideas such as storing a JSON string representation of the object; creating a duplicate product whose foreign key I then use for the order etc. However, I was wondering if there is a best practice or what other people use to handle this kind of situation in commercial software? -
Revoke celery task queue based on task id
I have two button in Django View in which the first button starts a celery task. I want to stop the queue when i press the second button. Is it possible to stop the queue simply based on the task id? -
Django makemigrations not working, how can i fix the dependencies?
I'm getting the error at the end of the trace back below. When I run 'python manage.py makemigrations'. I Get similar errors when I run it by 'python manage.py makemigrations accounts' and 'python manage.py makemigrations homedb'. If I run the accounts app, it says I'm missing a dependency in the accounts app and if I run the homedb app, it says I'm missing a dependency in the accounts app. In an effort to fix this, I've deleted my migrations, many pycache_ items, and the database to no avail. I also unstalled then reinstalled django. I would be greatful for any help. This is a portion of my traceback: self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/core/management/commands/makemigrations.py", line 88, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/loader.py", line 262, in build_graph self.graph.validate_consistency() File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, Du mmyNode)] File "/home/PyKane/.virtualenvs/django23/lib/python3.9/site-packages/d jango/db/migrations/graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, Du mmyNode)] File … -
Customize Create funciton in DRF viewset
I want to customize the user viewset i.e. when the user registers the user account was created as well. -
How to require non-admin login before accessing Wagtail admin login
I am working on a Django App that uses Wagtail and django-allauth. I am using a workaround from Allauth docs to take advantage of some Allauth's features which are lacking in vanilla Django Admin login. from django.contrib import admin from django.contrib.auth.decorators import login_required admin.site.login = login_required(admin.site.login) I am trying to do the same for the Wagtail Admin, but am having no luck so far. My difficulty might be because the Wagtail admin views are class-based - I don't think I can use method_decorator in this context. Any help or pointers are highly appreciated. -
How to adjust ChainedManyToManyField to populated field based on another field?
I'm trying to populate district based on the selected city in the admin page. I tried the ChainedManyToManyField, but when selecting a city, there is no districts in the dropdown menu! class District(Timestamps): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=100) class ListingPrice(MinimumListingPriceBase): city = models.ForeignKey("location.City", on_delete=models.CASCADE, null=True) district = ChainedManyToManyField( District, horizontal=True, chained_field="city", chained_model_field="city", auto_choose=True ) How to make it possible to select districts based on selected city in the admin page? -
unsupported operand type(s) for @: 'Q' and 'Q' in Django RestFramework
I am trying to make login api using django rest framework and while doing login api serilization I encounter this error "unsupported operand type(s) for @: 'Q' and 'Q'" inside validate function. I couldn't understand why this error came and help me to solve this This is my model.py file class User(models.Model): first_name=models.CharField(max_length=100, null=True) last_name=models.CharField(max_length=100, null=True) username = models.CharField(max_length=100, null=False,unique =True) email = models.EmailField(max_length=100, null=False, unique =True) # work_email = models.EmailField(max_length=100,unique =True) password = models.CharField(max_length=50, null=False) phone= models.CharField(max_length=100, null=True,unique =True) phone2=models.CharField(max_length=100, null=True,unique =True) is_login = models.BooleanField(null=True, default=False) is_verified=models.BooleanField(null=True) is_active=models.BooleanField(null=True) token = models.CharField(max_length=100, null=True, default="") user_type_id=models.ForeignKey(UserType, on_delete=models.CASCADE,null=True) created_at=models.DateField(null=True) updated_at=models.DateField(null=True) def __str__(self): return "{} -{}".format(self.username, self.email) and here is serializers.py file from django.db.models import Q, fields from django.db.models.base import Model # for queries class UserLoginSerializer(serializers.ModelSerializer): username=serializers.CharField() password=serializers.CharField() token=serializers.CharField(required=False, read_only=True) def validate(self,data): # user,email,password validator username=data.get("username",None) password=data.get("password",None) if not username and password: raise ValidationError('Detail not enter') user=None # if email is passed in username if '@' in username: user= User.objects.filter(Q(email=username) & Q(password=password)).distinct() if not user.exists(): raise ValidationError("User credintials are not correct.") user= User.objects.get(email=username) else: user=User.objects.filter(Q(username=username)@ Q(password=password)).distinct() if not user.exists(): raise ValidationError("User credentials are not correct.") user = User.objects.get(username=username) if user.is_login: raise ValidationError("User already logged in.") user.is_login = True data['token'] = uuid4() user.token = … -
Test Django validator with parameters
I want to test a custom validator for an ImageField that checks that the aspect ratio of the image is between the given parameters. The validator takes a min_aspect_ratio and a max_aspect_ratio parameter, and returns a validator function, which takes the image from the ImageField: def validate_image_aspect_ratio(min_aspect_ratio: int, max_aspect_ratio: int): """Checks that the proportions of an image (width / height) are what we expect.""" def validator(image): if image is None: return aspect_ratio = image.width / image.height error_message = _( 'Image\'s height proportion to its width should be between %(min_aspect_ratio)s and %(max_aspect_ratio)s. ' 'It was %(aspect_ratio)s.' ) % { 'aspect_ratio': "{:.2f}".format(aspect_ratio), 'min_aspect_ratio': min_aspect_ratio, 'max_aspect_ratio': max_aspect_ratio } if aspect_ratio < min_aspect_ratio or aspect_ratio > max_aspect_ratio: raise ValidationError( error_message ) return validator Here's how I am using the validator: image = models.ImageField( _('Image'), help_text=_('A default image will be used if this is not set.'), blank=True, validators=[validate_image_aspect_ratio(1.25, 1.35)] ) Now I want to test this method, for which I will give it two arguments for the aspect-ratio range, but how do I pass the image to it? The problem is not creating a mock image for the test, just how do I pass it to the function, since it is passed to the returned … -
How should I send input array from javascript to django views.py
I am trying to send an array from javascript function to views.py and after some calculations to array i want to display the array on the webpage -
Ajax returns whole HTML page in Django
I'm trying to implement a simple form using the bootstrap modal but whenever I submit the form the response I get is whole HTML page. The request is POST. I have tried almost all answers which are present on the StackOverflow but none of them worked for me. My Modal form code: <div id="alert-box"></div> <form id="ajax-form" autocomplete="off"> {% csrf_token %} {{contact_form|crispy}} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> This is my Ajax code: <script type="text/javascript"> const alertBox = document.getElementById('alert-box'); const msgForm = document.getElementById('ajax-form'); const name = document.getElementById('id_name'); const number = document.getElementById('id_phone_number'); const message = document.getElementById('id_message'); const csrf = document.getElementsByName('csrfmiddlewaretoken'); const handleAlerts = (type,text) => { alertBox.innerHTML = `<div class="alert alert-${type}" role="alert"> ${text} </div>` } const url = ""; console.log(csrf); msgForm.addEventListener('submit',e => { e.preventDefault(); const fd = new FormData(); fd.append('csrfmiddlewaretoken',csrf[0].value); fd.append('name',name.value); fd.append('number',number.value); fd.append('message',message.value); $.ajax({ type: 'POST', url: url, data: fd, cache: false, contentType: false, processData: false, enctype: 'multipart/form-data', success: function(response) { const sText = `${response.name}`; handleAlerts('success', sText) setTimeout(()=>{ alertBox.innerHTML = ""; name.value = ""; number.value = ""; message.value = ""; }, 5000); }, error: function(error){ handleAlerts('danger', 'oops..something went wrong') } }) }); </script> This the form which I want to submit. -
Django Static Files does not deploy on Google Cloud Bucket
I am deploying an Django App, which runs on google server but it does not load the static files, so that App does not load the css and images. I checked the bucket I created but there is no files in the bucket. Here is settings.py STATIC_URL = '/static/' STATIC_ROOT = "static" PRODUCTION = True if PRODUCTION: # Define static storage via django-storages[google] GS_BUCKET_NAME = env("GS_BUCKET_NAME") print(GS_BUCKET_NAME) STATIC_URL = "/static/" DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_DEFAULT_ACL = "publicRead" else: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Here is app.yaml file. runtime: python38 handlers: - url: /static static_dir: static/ - url: /.* script: auto Here is urls.py. urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I deploy the app, it was done successfully. but the static files does not deploy into the bucket. As well I run this bellow command. python manage.py collectstatic I followed this tutorial. -
IndentationError: unindent does not match any outer indentation level (views.py, line 20)
enter image description here Tried every damn thing from changing indentation to spaces to writing a new file, this error is determined to not go from django.urls import path from . import views app_name="main" urlpatterns= [ path("",views.homepage,name="homepage"), path("register/", views.register, name="register") ] -
I want to fetch the data using api in flutter
I am trying to build freelancing type app. I am using flutter and for my backend data i created an api using django rest framework. Here is the models.py: class Package(models.Model): management_duration_choices = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ("9", "9"), ("10", "10"), ("11", "11"), ("12", "12"), ("13", "13"), ("14", "14"), ("15", "15") ) title = models.CharField(max_length=120) delivery_time = models.ForeignKey( DeliveryTime, on_delete=models.CASCADE, null=True) package_desc = models.TextField(null=True) revision_basic = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_basic") revision_standard = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_standard") revision_premium = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_premium") num_of_pages_for_basic = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_basic", blank=True) num_of_pages_for_standard = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_standard", blank=True) num_of_pages_for_premium = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_premium", blank=True) is_responsive_basic = models.BooleanField(default=False, null=True, blank=True) is_responsive_standard = models.BooleanField(default=False, null=True, blank=True) is_responsive_premium = models.BooleanField(default=False, null=True, blank=True) setup_payment = models.BooleanField(default=False, null=True, blank=True) will_deploy = models.BooleanField(default=False, null=True, blank=True) is_compitable = models.BooleanField(default=False, null=True, blank=True) supported_formats = models.ManyToManyField(FileFormats, blank=True) # For Logo Design provide_vector = models.BooleanField(default=False, null=True, blank=True) is_3dmockup = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_basic = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_standard = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_premium = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_basic = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_standard = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_premium = models.BooleanField(default=False, null=True, blank=True) # For Digital … -
What is a good way to proceed to store and use sensitive data in prod environment?
I have a django web app in a production environment hosted on a server. To store sensitive data I am using a .env file excluded from my git process stored on the server where my app is hosted. # .env file { "ENV_TYPE": "prod", "SECRET_KEY": "mysecretkey", "ALLOWED_HOSTS":[ "somewhere.com" ], "DEBUG": false, "STATIC_ROOT": "/somewhere/staticfiles", "DATABASES": { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "databaseName", "USER": "username", "PASSWORD": "myPassword", "HOST": "somewhereelse.com" } } } And in my app I get back data like this in setting.py for instance: # setting.py # Get back non secret env data such as DEBUG, ALLOWED HOSTS with open(os.path.join(BASE_DIR, '.env'), 'r') as f: env_data = json.load(f) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env_data["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env_data["DEBUG"] ALLOWED_HOSTS = env_data["ALLOWED_HOSTS"] Do you believe this is a good way to proceed ? Indeed I still have somewhere on my server some passwords that are hard coded. -
Apache24 Production Server For Django React App: React Shows 403 Forbidden Error
I am trying to run a production server on an AWS EC2 instance (Windows) using Apache for a Django backend connected with a React frontend. When I test the app on Django's runserver everything works well, but currently, when I try to use it on Apache I am just seeing a blank screen. When I check the console it tells me that I don't have permission to access the react static files (403 forbidden error). In my attempts to fix this, I have run collectstatic, which has put all of the static files (including the react ones) on an S3 Bucket. This means that the Django pages (admin pages) are able to use the static files, but the React pages aren't accessing the files from the S3 bucket. I'm not sure if it is better to find a way to get my React app to use the static files from the bucket, or if I should just continue to find a way to get Apache to serve the static files. I know that the files are able to be found because it isn't a 404, but a 403, so it must be some problem with my configuration that isn't giving … -
I got error while creating virtual environment in django
while creating a virtual environment in Django I got site-package is not writable and that's why when i write command of Django-admin so i got error not found in external or internal can anyone how I solve this -
How to Iterate a list sent from React in Django
I want to iterate colors in Django, it should print first red then green # data from frontend react data = request.data print(data) <QueryDict: {'colors': ['red', 'green']}> result should be like this : red green -
How do i maintain a user cover uploaded image in fields whiles adding new images without it getting deleted in django
How do i get Django to store already uploaded cover image to a user without getting it deleted when a new image is uploaded, but simply replace it? I'm having a challenge trying to figure out how to maintain old cover images while adding new once to a user. what happens is that when i upload a new cover image it simply deletes the previous one from the database. Here is my cover image models: class AccountCover(models.Model): account = models.ForeignKey(Account,on_delete=models.CASCADE) cover_image = models.ImageField(max_length=255,upload_to=get_cover_cover_image_filepath,default=get_default_cover_image,) Here the view to upload cover image cover = AccountCover.objects.filter(account=account.id).first() if request.user: forms = CoverImageForm(request.POST, request.FILES,instance=cover, initial = {'cover_image':cover.cover_image}) if request.method == 'POST': f = CoverImageForm(request.POST, request.FILES,instance=cover) if f.is_valid(): data = forms.save() data.account = cover.account data.save() return redirect('account:edit', account.id) else: f = CoverImageForm() context['f'] = f -
Sending data from django app to the arduino
I have written an arduino sketch to turn on and off a light using serial port. I coded to send serial data using pyserial. It worked fine. The python script below worked fine. But the problem is when I implemented that in the django application. Everthing works fine sending data, return values everything works fine but it doesn't turn on the light. I checked return value for s.write("on".encode()) it is also same as of the python script but in django it doesn't turn on the light. **Code from Arduino Sketch** String command; void setup() { Serial.begin(9600); Serial.println("Type your command"); } void loop() { if(Serial.available()){ command = Serial.readStringUntil('\n'); if(command =="on"){ digitalWrite(7, HIGH); } else if(command == "low"){ digitalWrite(7, LOW); } } } **code from python script** import serial ser = serial.Serial() ser.baudrate = 9600 ser.port = 'COM5' ser.open() data = ser.readline(82) ser.write("on".encode()) print(data.decode("utf-8")) **code from django** import serial # Create your views here. @csrf_exempt def index(request): if (request.method=="POST"): giveCommand = ReadFromArduino(baudrate=9600, port = "COM5") res = giveCommand.writeData(commandData = "on") return HttpResponse(res) s = serial.Serial() s.baudrate = 9600 s.port = "COM5" s.open() ret = s.write("on".encode()) print(ret) s.close() return HttpResponse("Hello") # giveCommand = ReadFromArduino(baudrate=9600, port = "COM5") # res = giveCommand.writeData(commandData = "on") … -
How to make the django rest framework POST button work?
I have a model like this: class Ad(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) text = models.TextField() # Shows up in the admin list def __str__(self): return self.title A Viewset like this: class AdViewSet(viewsets.ModelViewSet): """ API endpoint that allows ad to be viewed or edited. """ queryset = Ad.objects.all().order_by('-created_at') serializer_class = AdSerializer I have made the router and the serializer that I didn't include here because I don't think it's needed to show my issue. In the Django Rest Framework in /api/ads/ I can see all my previous ads created using the django admin and below a form to post data which looks like this: When I click on the POST button of the form,it doesn't make a POST request it just reload the page. I can confirm it from the Firefox devtool and the server log, no POST request are made. So my question is this: how to make this POST button works as expected so I can check my serialiser and everything work as it should ?