Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding Google-Auth user creation
I added the google login and when I selected an account after the continue I get the following. Traceback (most recent call last): File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\utils.py", line 229, in deserialize_instance v = f.from_db_value(v, None, None) During handling of the above exception ('ImageField' object has no attribute 'from_db_value'), another exception occurred: File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\socialaccount\views.py", line 39, in dispatch self.sociallogin = SocialLogin.deserialize(data) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\socialaccount\models.py", line 215, in deserialize user = deserialize_instance(get_user_model(), data["user"]) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\socialaccount\adapter.py", line 189, in deserialize_instance return deserialize_instance(model, data) File "C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\allauth\utils.py", line 231, in deserialize_instance raise ImproperlyConfigured( Exception Type: ImproperlyConfigured at /accounts/social/signup/ Exception Value: Unable to auto serialize field 'verified', custom serialization override required I have an abstractuser with the field verified and want to create a default user with google all-auth. How would I handle that? from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField from django.templatetags.static import static class Profile(AbstractUser): bio = models.TextField(max_length=100, blank=True) phone_number = PhoneNumberField(max_length=25, region='US') birth_date = models.DateField(blank = True, null = True) is_doctor = models.BooleanField(default=False) verified = models.ImageField(default='',upload_to='media/doctor') date_created = models.DateTimeField(auto_now_add=True) avatar = … -
Using Len Of A List To Create Django HTML Pages?
I know this has had to have been asked before, I can't seem to figure out the correct terminology to search to find what this is called or how to do it. I have a dynamic table that one day may have 5 items and the next 10 items (pulled from a DB), I am going to create hyperlinks within the table that would then open another HTML page specifically about that list object. I can't seem to figure out how to make this work? The way my mind works with Django right now is that I create a HTML file and URL view for each specific page, but if I one day want to create 3 and the next day 5 how can I do that, right now my mind can't understand how to dynamically create that HTML file for each thing in the list by using only one template? Just looking for someone to tell me what this is called if anything or what I can search in Django documentation to find examples? -
Django/Python: Manage Different Requirements (pip) Among Git Branches
Django website, with two requirements files (base and local for stuff like django-debug-toolbar). This project has mainly been managed by only me, but recently we added a developer. We've got our main branch deploying to production (master) and several issue branches for development of features or fixing bugs, (eg issue-1234). Let's say in a branch (django4-upgrade) I want to explore updating to Django 4 from 3.2. I can make a branch, then I can pip install django==4.0.0 and test/develop, but then if I git checkout master after pushing those experimental changes, my virtual environment has Django 4.0.0. Stuff might break. What is the best practices strategy for managing different requirements across Git branches on the same system (eg, using the same virtual environment)? I can imagine multiple branches for testing different features, all requiring slightly different requirements.txt files. I do not currently commit my virtual environments to Git repos. My current naive approach is to freeze the requirements for a given branch when I'm done developing, then when I checkout a different branch, I can install all those requirements and get my original virtual environment back to how it was. This has limitations. I see this post, but this doesn't … -
How to show Django form in template?
I want to display countries and states in Django form, for that I am trying to get data from json, create form, pass json data to form and get state of the country on ajax request. I managed to write the process as far as I learned, but at last form is not rendered on Django template. How can I render Django form with following code structure? My Model: from django.db import models class Address(models.Model): country = models.CharField(null=True, blank=True, max_length=100) state = models.CharField(null=True, blank=True, max_length=100) def __str__(self): return '{} {}'.format(self.country, self.state) My Form: from django import forms from .models import Address import json def readJson(filename): with open(filename, 'r') as fp: return json.load(fp) def get_country(): """ GET COUNTRY SELECTION """ filepath = './static/data/countries_states_cities.json' all_data = readJson(filepath) all_countries = [('-----', '---Select a Country---')] for x in all_data: y = (x['name'], x['name']) all_countries.append(y) return all_countries def return_state_by_country(country): """ GET STATE SELECTION BY COUNTRY INPUT """ filepath = './static/data/countries_states_cities.json' all_data = readJson(filepath) all_states = [] for x in all_data: if x['name'] == country: if 'states' in x: for state in x['states']: y = (state['name'], state['name']) all_states.append(state['name']) else: all_states.append(country) return all_states class AddressForm(forms.ModelForm): country = forms.ChoiceField( choices = get_country(), required = False, label='Company Country Location', … -
How to integrate Node.js in Django?
I've been struggling to plan out how to build a multiplayer browser game using Django and Phaser, as it is the web framework I am most familiar with. I'm aware that to build a multiplayer browser game, I need to utilize web sockets. Unfortunately, there is not a lot of documentation on how to create a Phaser game using any framework other than Node.js paired with Socket.io (I looked into how to make use of Django channels) and I'm completely new to the idea of bidirectional communication with servers. For that reason, I was wondering how to set up Django with Node.js and how exactly these two web frameworks would communicate with each other when needed. Much appreciated if anyone could lend some insight on this idea of mine. -
Django: Fetching data from an open source API
I am trying to fetch public holiday data for France, Australia and Germany from https://date.nager.at/ with the documentation at https://date.nager.at/swagger/index.html and store it in a JSON file. Until now, I have created an endpoint /fetch_from_db with its own URL, but only managed to write dummy data in the views.py file. How do I fetch the data above and store it in a database through Django? -
'bytes' object has no attribute '_committed'
I will create multi image add page. But the following error occurs. Could your help me? I think mistake in views.py. I'm not sure. Note : It's frustrating that Stackoverflow asks for a long explanation. error: AttributeError at /en/projects/multiimageadd/10/ 'bytes' object has no attribute '_committed' @login_required @permission_required('is_superuser') def MultiImageAdd(request, id): blog = BlogModel.objects.filter(id=id).first() if request.method == 'POST': images = request.FILES['images'] for image in images: Images.objects.create(project=project, image=image) return redirect("home") return render(request,"multiImage.html") <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> </div> <div class="card-body"> <form class="needs-validation" method="POST" action="" enctype="multipart/form-data" novalidate=""> {% csrf_token %} <div class="row"> <div class="col-sm-12"> <div class="form-group row"> <label for="id_images" class="col-xl-3 col-md-4">Images:</label> <span class="form-control col-md-8"> <input required type="file" name="images" id="id_images" multiple> </span> </div> </div> </div> <div class="pull-right"> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </div> </div> </div> </div> </div> models.py class Images(models.Model): blog = models.ForeignKey(BlogModel, related_name='blogmodel', on_delete=models.CASCADE, blank=True,null=True) image = models.ImageField(blank=False, null=True) -
Custom Error Reporting Capability in Django
I have setup the ADMINS variable in settings.py. I've configured my email and everything works as intended. I get a very good, detailed error message from my production box when it encounters an error. I also understand the MANAGERS variable and how it can handle 404 errors and send alerts. OK, fine... However, I have another use case whereas I'd like to send the error report (standard 500 detailed report) to a set of individuals based on the app the error occurs in (or a default if outside a specific app). So, let's say I have 1 person developing/supporting webapp1 and 2 supporting webapp2. If the error occurs in webapp2, I only want to send to those 2 and if in webapp1 the person developing/supporting that app. If the error doesn't occur in a specific app, I'd send to everyone defined in ADMINS variable. First off, is there a better way to address this use-case than through custom error process? and.. Secondly, is this possible within the custom error capability? -
Django3: change style of selection field in admin view?
In my django project I have a project model with a many to many field for users, which can be added and removed. This works well, however, the selection field in the admin view is a bit inconvenient. Selection works by clicking on the usernames. To select multiple users CTRL has to be held. If you do that wrong all selections can be removed just by clicking on a certain item. So, it is easy to loose the current selection with this tool. A better tool would be something that works like the user-groups and -rights window, with two separate panels, unselected and selected items. My question is whether this tool: can be replaced this tool: So that users not joined the project are listed on the left and joined users are on the right? Or vice versa. -
Problem deployment Django Rest Framework app to Heroku
I'm trying to deploy a simple app to Heroku, and recently started getting the following error: remote: -----> $ python manage.py collectstatic --noinput remote: Post-processing 'drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js' failed! remote: Traceback (most recent call last): remote: File "/tmp/build_33d50075/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_33d50075/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect remote: raise processed remote: whitenoise.storage.MissingFileError: The file 'drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f4a4526efb0>. remote: The JS file 'drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js' references a file which could not be found: remote: drf-yasg/swagger-ui-dist/swagger-ui-es-bundle.js.map remote: Please check the URL references in this JS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic … -
How to group by in ManyToMany relationships in Django?
I am creating a web application with Django and I have some problems using its ORM to make queries. I have these models: class Country(models.Model): name = models.CharField(max_length=25) class Song(models.Model): title = models.CharField(max_length = 25) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="songs") ratings = models.ManyToManyField(Country, through='Rating') class Rating(models.Model): rating = models.PositiveSmallIntegerField() country_id = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) song_id = models.ForeignKey(Song, on_delete=models.SET_NULL, null=True) A Country rates many Songs (with ratings 1-10), and a Song can be rated by many Countries, so there's a ManyToMany relationship between these models through the Rating table. I am making a query to get the number of 10 points a Song has received, but I don't know how. To do that, I tried this query: result = Rating.objects.filter(rating=10).values('song_id').annotate(ten_points = Count('rating')) I read Django documentation and I understood that values() method is like group by clause in SQL, but it doesn't work because this query returns a queryset of dictionaries like this: <QuerySet [{'song_id': 1, 'ten_points': 1}, {'song_id': 2, 'ten_points': 1}, {'song_id': 2, 'ten_points': 1}, {'song_id': 3, 'ten_points': 1}, {'song_id': 3, 'ten_points': 1} Why am I getting different dictionaries with the same key and value 1, instead of a dictionary with the key and the value the total number of … -
hello need help for displaying comments on per post on home page
can some one be able to help me out please. i want to display number of comments on blog home page where all post is showing up. i want to show number of comments on little comment icon under every post,is having. thanks my model: class BlogPost(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=60, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, null=False, blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date_published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date_updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.CharField(max_length=20, choices=CATEGORIES_NAME, default='Entertainment') slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title class BlogComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(Account, on_delete=models.CASCADE) post = models.ForeignKey(BlogPost, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=now) def __str__(self): return str(self.sno) my homepage view: BLOG_POSTS_PER_PAGE = 4 def home_screen_view(request): context = {} query = "" if request.GET: query = request.GET.get('q', '') context['query'] = str(query) blog_posts = sorted(get_blog_queryset(query), key=attrgetter('date_updated'), reverse=True) comments = BlogComment.objects.all() # Pagination page = request.GET.get('page', 1) blog_posts_paginator = Paginator(blog_posts, BLOG_POSTS_PER_PAGE) try: blog_posts =blog_posts_paginator.page(page) except PageNotAnInteger: blog_posts =blog_posts_paginator.page(BLOG_POSTS_PER_PAGE) except EmptyPage: blog_posts =blog_posts_paginator.page(blog_posts_paginator.num_pages) context['blog_posts'] = blog_posts context['comments'] = comments return render(request, "personal/home.html", context) -
Django3: ManyToMany field causes: Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin
I have a custom user model without username, but using email instead. class User(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) uuid = models.CharField(max_length=36, default=uuid4, unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email And a project model that has multiple users: from user.models import User class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(max_length=256, unique=True, blank=False) created = models.DateTimeField(auto_now_add=True) description = models.TextField(max_length=10000, default="") slug = models.SlugField(max_length=256, unique=True) created_by = CurrentUserField(related_name='creator') users = models.ManyToManyField(User, related_name='users') .... My UserAdmin model looks like this: class CustomUserAdmin(UserAdmin): list_display = ("email", "is_staff", "is_superuser") readonly_fields = ("last_login", "date_joined", "uuid") ordering = ("email",) fieldsets = ( ( "Fields", { "fields": ( "email", "uuid", "date_joined", "last_login", "is_active", "is_staff", "is_superuser", "groups", "user_permissions", "password", ) }, ), ) admin.site.register(User, CustomUserAdmin) However, when I go to admin view to a project instance and try to add user I get: FieldError at /admin/user/user/add/ Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. Request Method: GET Request URL: http://localhost:8000/admin/user/user/add/?_to_field=id&_popup=1 Django Version: 3.2.11 Exception Type: FieldError Exception Value: Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin. I added my user model as a default model in settings, so I don't know … -
update the basket without using update button just with select tag Django & ajax
hi guys my form need update button to sending data but I want to send data(quantity of product) by select tag and no one has a solution **ajax $(document).on("click", ".update-button", function (e) { e.preventDefault(); var prodid = $(this).data("index"); $.ajax({ type: "POST", url: '{% url "basket:basket_update" %}', data: { productid: $(this).data("index"), productqty: $("#select" + prodid + " option:selected").text(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { total = (parseFloat(json.subtotal) + 11.50).toFixed(2); document.getElementById("basket-qty").innerHTML = json.qty; document.getElementById("subtotal").innerHTML = json.subtotal; document.getElementById("total").innerHTML = total; }, error: function (xhr, errmsg, err) {}, }); }); **html <label for="select">Qty</label> <select id="select{{product.id}}" style="width:50px;height:31px;"> <option value="" selected disabled hidden>{{item.qty}}</option> <option value="">1</option> <option value="">2</option> <option value="">3</option> <option value="">4</option> </select> <a type="button" id="update-button" data-index="{{product.id}}" class="update-button text-decoration-none small ps-3">Update</a> -
How to solve error 401 unauthorized login in DRF simple jwt user login
I am creating DRF authentication APIs for Abstract Base users in my Django project and I am using simple JWT. The registration and email verification APIs work fine, but when I try to log in using the credentials of a valid user, I get an error 401 unauthorized access. Here is my login class-based view in views.py: class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) Here is the LoginSerializer in serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(max_length=255, min_length=3) password = serializers.CharField(max_length=68, min_length=8, write_only=True) username = serializers.CharField(max_length=255, min_length=3, read_only = True) tokens = serializers.CharField(max_length=68, min_length=8, read_only = True) class Meta: model = User fields = ['email', 'password', 'username', 'tokens'] def validate(self, attrs): email = attrs.get('email', '') password = attrs.get('password', '') user = auth.authenticate(email=email, password=password) if not user: raise AuthenticationFailed('Invalid Credentials, try again!') if not user.is_active: raise AuthenticationFailed('Acccount disabled, please contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') return { 'email': user.email, 'username': user.username, 'tokens': user.tokens } return super().validate(attrs) In settings.py the only settings dealing with DRF-simple Jwt are: REST_FRAMEWORK = { 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } So the error raised is "Invalid credentials" meaning that details of the user don't exist, … -
django collectstatic on server
Recently, my DB on my server has shat the bed. I imagine the mistake was somewhere on my end and my wagtail database ended up being wiped clean. I've managed to get my sqlite db working again but my collectstatic is still failing. I have tried renaming my static folder using mv static staticold and reran python manange.py collecstatic but it still fails. The error message reads: Post-processing 'scss/main.css' failed! ... ... raise ValueError("The file '%s' could not be found with %r." % (filename, self)) ValueError: The file 'images/5f5a5b3515c4dd0c2c455925_110642301_938622823267359_7859124022958180678_n201.jpg' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7f00badf6f60>.` I don't really care about these old images, though I would like my js and css files to be updated with collectstatic -
user table not created on django deployment but superuser created on heroku bash
I'm trying to upload my first django app and I've been struggle with this issue for sometime, help is appreciated. I already set up my project to be on heroku, I followed this tutorial: https://www.youtube.com/watch?v=6DI_7Zja8Zc in which django_heroku module is used to configure DB, here is the link to library https://pypi.org/project/django-heroku/ The app throws the error on login as if user tables didn't exist but I already create a super user using the heroku bash feature, after apply migrations using "heroku run python manage.py migrate". When I run "ls" command on heroku bash this is my directory: manage.py Procfile requirements.txt runtime.txt smoke staticfile "smoke" is my folder app, should I could see the db in this directory? if the db was not created how could I create a superuser using heroku bash feature? This is the DB configuration that django gives me on server: {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': PosixPath('/app/db.sqlite3'), 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': ''}} I see that db is sqlite3 and should be postgreSQL but I understand that django-heroku library should do that. I don't know … -
Getting Django migration error "sequence must have same owner as table it is linked to", but all tables and sequences have the same owner
I'm trying to run a migration in a Django project. (Django 3.1, Python 3.9.9) I'm in my virtual environment. I keep getting a puzzling error. python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, intake, sessions Running migrations: Applying intake.0021_auto_20220115_1147...Traceback (most recent call last): File "/Users/me/Sites/client/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.ObjectNotInPrerequisiteState: sequence must have same owner as table it is linked to But when I list out my tables and sequences, they all have the same owner. intake=# \dt List of relations Schema | Name | Type | Owner --------+----------------------------+-------+----------- public | auth_group | table | dbuser public | auth_group_permissions | table | dbuser public | auth_permission | table | dbuser public | auth_user | table | dbuser public | auth_user_groups | table | dbuser public | auth_user_user_permissions | table | dbuser public | django_admin_log | table | dbuser public | django_content_type | table | dbuser public | django_migrations | table | dbuser public | django_session | table | dbuser public | intake_byattorney | table | dbuser public | intake_client | table | dbuser (12 rows) intake=# \ds List of relations Schema | Name | Type | Owner --------+-----------------------------------+----------+----------- public | auth_group_id_seq | sequence … -
I want that in my project the members who are having role as manager should not be able to see the priority field while updating the form
MODELS.PY : class Ticket(models.Model): status_choice = ( ("Approval","Approval"), ("Assigned","Assigned"), ("Scoping","Scoping"), ("In Progress","In Progress"), ("Completed","Completed"), ("Cancelled","Cancelled"), ("Rejected", "Rejected") ) priority_choice = ( ("High","High"), ("Moderate","Moderate"), ("Low","Low"), ) category = models.ForeignKey("vats.Category",on_delete=models.CASCADE) subcategory = models.ForeignKey("vats.Subcategory",on_delete=models.CASCADE) title = models.CharField(_("Title"), max_length=50,) problem_descp = models.TextField(_("Problem Description"), max_length=500) created_by = models.ForeignKey("registration.User", related_name=_("Issues"), on_delete=models.CASCADE) priority = models.CharField(_("Priority"), max_length=50,null=True,blank=True,choices=priority_choice) start_date_time = models.DateTimeField(_("Start Date Time"), auto_now_add=True) end_date_time = models.DateTimeField(_("End Date Time"), null=True, blank=True) assigned_to = models.ForeignKey("registration.User",related_name=_("Tasks"), on_delete=models.SET_NULL,null=True,blank=True) status = models.CharField(_("Status"), max_length=50,choices=status_choice,null=True,blank=True) class Meta: verbose_name = _("Ticket") verbose_name_plural = _("Tickets") def __str__(self): return self.title def is_open(self): if self.status == 'Completed' or self.status == 'Cancelled': return False return True Forms.py : class TicketForm(forms.ModelForm): # subcategory = forms.ModelChoiceField(queryset=Subcategory.objects.filter(category__id = self.fields['category'])) class Meta: model = Ticket fields = ("category", "subcategory", "title","problem_descp") class TicketUpdateForm(forms.ModelForm): class Meta: model = Ticket fields = ("category","subcategory", "title","problem_descp","status","assigned_to","priority") def __init__(self, *args, **kwargs): super(TicketUpdateForm,self).__init__(*args, **kwargs) self.fields['category'].disabled = True self.fields['subcategory'].disabled = True self.fields['title'].disabled = True self.fields['problem_descp'].disabled = True -
Using Django-modeltranslation in combination with PostgreSQL SearchVector
I'm using django-modeltranslation to translate model fields. And suppose I have the following model (where the name is translated in the DB): class Book(models.Model): name = models.CharField(max_length=90) Then, in a DRF view, I have an endpoint that takes a query text and searches through the book names using this code: from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank class BookView(APIView): def get(self, request): q = request.get('q') vector = SearchVector('name') # this is where the issue is query = SearchQuery(q) matches = Book.objects.annotate(rank=SearchRank(vector, query))\ .filter(rank__gt=0.1)\ .order_by('-rank') # etc. This works great when I was working with English only. But now I added a new language, and all aspects of the localisation are working fine, except this search. It's looking at the name_en field values only. If the target language is German for example, and I explicitly change the following line from: vector = SearchVector('name') to: vector = SearchVector('name_de') Then the search works over the correct field. Is there a way to pass in the correct field to SearchVector? -
Current data on django containers get cleared after rebuilding a Container
I dockerized my Django application, but every time and make an update and rebuild images, all the data gets cleaned. Below are the Dockerfile and docker-compose.yml files: Docker ########### # BUILDER # ########### # pull official base image FROM python:3.8.10-buster as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apt-get update \ && apt-get install -y postgresql gcc python3-dev libpq-dev musl-dev python3-setuptools binutils libproj-dev gdal-bin # lint RUN pip3 install --upgrade pip RUN pip3 install flake8 COPY . . # RUN flake8 --ignore=E501,F401 . # install dependencies COPY ./requirements.txt . RUN pip3 wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.8.10-buster # create directory for the app user RUN mkdir -p /home/app # create the app user # RUN addgroup -S app && adduser -S app -G app RUN useradd app && usermod -aG app app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME WORKDIR $APP_HOME RUN mkdir $APP_HOME/static WORKDIR $APP_HOME RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME # install dependencies RUN apt update && apt install libpq-dev binutils libproj-dev gdal-bin -y COPY --from=builder … -
Why am I getting error "Client with IP address x.x.x.x isnt allowed to connect to this MySql server" when trying to connect to MySql from Django?
I am trying to create tables for my models in this full stack project (Django/React). After I run the python manage.py migrate command I'm expecting to see: Migrations for X: X\migrations\0001_initial_py - Create model Departments - Create model Employees Instead I get the following error: (9000, "Client with IP address 'X' is not allowed to connect to this MySQL server." I have tried the command pip install pymysql then edited the settings.py file adding import pymysql pymysql.install_as_MySQLdb() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mytestdb', 'USER': 'testadmin@mytestmysql', 'PASSWORD': 'XXXXXXXXXX#', 'HOST': 'mytestmysql.mysql.database.XXXXXXXXXXXXX.com', 'PORT': '3306' -
How can I send React variable to Django view?
I'm using Django and React for a project that consumes Trello's API. I created functions in django views.py that will get user's boards, lists and cards. The problem is, to get a list, I need that the user select a board, because the list's endpoint requires a board id (and so on). I can show the user's boards on my react page and storage the board's id on a variable in Index.js (on pages folder), but I have no ideia how I can send the selected board id to views.py to consume Trello's api according to the user's selected board. Here's my code. Django views.py: from rest_framework.decorators import api_view from rest_framework.response import Response from dotenv import load_dotenv from treegia.settings import TRELLO_URL import os import requests load_dotenv() TRELLO_KEY = os.getenv('TRELLO_KEY') TRELLO_TOKEN = os.getenv('TRELLO_TOKEN') @api_view(['GET']) def get_boards(request): if request.method == 'GET': board_endpoint = TRELLO_URL+'members/me/boards' jsonObj = {'fields':'name,id', 'key':TRELLO_KEY, 'token':TRELLO_TOKEN} boards = requests.get(board_endpoint, json=jsonObj).json() return Response(boards) @api_view(['GET']) def get_lists(request): if request.method == 'GET': list_endpoint = TRELLO_URL+ 'boards/' + id_board + '/lists' jsonObj = {'fields':'name,id', 'id':id_board, 'key':TRELLO_KEY, 'token':TRELLO_TOKEN} lists = requests.get(list_endpoint, json=jsonObj).json() return HttpResponse(lists) @api_view(['GET']) def get_cards(request): if request.method == 'GET': card_endpoint = TRELLO_URL+ 'lists/' + id_list + '/cards' jsonObj = {'fields':'name,id', 'id':id_list, 'key':TRELLO_KEY, … -
login via dj-auth with view
i need login via system(self) inside of a view of django that import dj-rest-auth. i try these code but get error: value = { "username" : '0967826354', "password" : '##heelo!!heelo' } data = LoginView.as_view()(value) return Response(data) error: sensitive_post_parameters didn't receive an HttpRequest. If you are decorating a classmethod, be sure to use @method_decorator. -
Bootstrap main element goes behind sidebar
I am using the Dashboard example from Bootstrap 5: https://getbootstrap.com/docs/4.0/examples/dashboard/. It runs fine when I open the html file outside of my app. But then I add it to my Django Web App and the element goes behind the side bar as shown below, which leaves a gap on the right side of the page: The page should look like this, where the graph doesn't go behind the sidebar Here is the relevant code I'm using: Dashboard.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale = 1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>Dashboard Template for Bootstrap</title> <link rel="stylesheet" href="{% static 'appbase.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0"> <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">Company name</a> <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search"> <ul class="navbar-nav px-3"> <li class="nav-item text-nowrap"> <a class="nav-link" href="#">Sign out</a> </li> </ul> </nav> <div class="container-fluid"> <div class="row"> <nav class="col-md-2 d-none d-md-block bg-light sidebar"> <div class="sidebar-sticky"> <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link active" href="#"> <span data-feather="home"></span> Dashboard <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <span data-feather="file"></span> Orders </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> <span data-feather="shopping-cart"></span> Products </a> </li> <li …