Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Will a CICharField (Postgres field type) work with AWS RDS?
Since Django 1.11 there is a case-insensitive Textfield (CICharField) in Django that is awesome for storing case-insensitive unique usernames or emails. I'd love to use this field but plan to host my application on AWS RDS and I am not sure if it will work on RDS. Will it work? -
Catching errors when quering in Django of fields that do not exist in the database or model
I am trying to catch errors of fields that do not exist either in the model or database. To do that i follow EAFP approach. But it doesn't work, i get the following error: Cannot resolve keyword 'bin_height_mm_desc' into field. Choices are: .... def DeviceDetailView(request,device_id): tbl_dict = {} try: a = Bin.objects.values('bin_height_mm_desc','received_at_ymd','received_at_hm') tbl_dict = a except (ValueError, TypeError, AttributeError) as e: tbl_dict = e context = { 'tbl_data' : tbl_dict, } return render(request, 'applications/device.detail.html', context) -
No foreign_key related in validated_data in Django
Hi I want to POST into my Album using my AlbumSerializer. The problem is I don't receive the Artist name in the validated data inside the function create. #models.py class Artist(models.Model): name = models.CharField() ... class Album(models.Model): name = models.CharField() artist = models.ForeignKey(Artist) class Track(models.Model): album = models.ForeignKey(Album) title = models.CharField() #serializers.py class AlbumSerializer(serializers.ModelSerializer): artist = serializers.StringRelatedField() tracks = TrackSerializer(many=True) class Meta: model = Album fields = '__all__' def create(self, validated_data): print(validated_data) ... I am passing in this data: { "name": "Test", "artist": "Enimem", ... } When I print the validated_data, the artist is not included. Is it because it is a foreign key? Then how will I add it to the validated_data? {'name': 'Test', ...} I have tried adding the function to_interval_value, which resolved my problem, but I really don't want it added because it messes up the default ValidationErrors. def to_interval_value(self, data): return data -
Django restframework JWT unable to set-cookies
When I look in the source code of rest_framework_jwt if api_settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) response.set_cookie(api_settings.JWT_AUTH_COOKIE, token, expires=expiration, httponly=True) return response It set JWT in the cookies (httponly) when returning the response. But when I use httpie to inspect it. Here is the header. HttpPie I have no idea either it will appear in httpie or not. Correct me if I am wrong. However, when I use APIView to send the credentials, no JWT cookies also Both frontend and serverside withCredentials = True Do I need to set the cookies myself or there is another way to do it? -
How to use pip freeze --exclude?
I am working with django project, where I am creating requirements.txt with pip freeze> requirements.txt asgiref==3.2.3 certifi==2019.11.28 chardet==3.0.4 dj-database-url==0.5.0 Django==2.0.7 django-admin-multiple-choice-list-filter==0.1.1 django-heroku==0.3.1 django-multiselectfield==0.1.11 djangorestframework==3.11.0 fuzzywuzzy==0.17.0 gunicorn==20.0.4 idna==2.8 nltk==3.4.5 numpy==1.18.1 pandas==1.0.1 psycopg2==2.8.4 psycopg2-binary==2.8.4 python-dateutil==2.8.1 pytz==2019.3 requests==2.22.0 six==1.14.0 sqlparse==0.3.0 urllib3==1.25.8 whitenoise==5.0.1 I want remove some packages like pandas, numpy and fuzzywuzzy I am using pip freeze --exclude pandas, numpy, fuzzywuzzy > requirements.txt but not getting right output fuzzywuzzy asgiref==3.2.3 certifi==2019.11.28 chardet==3.0.4 dj-database-url==0.5.0 Django==2.0.7 django-admin-multiple-choice-list-filter==0.1.1 django-heroku==0.3.1 django-multiselectfield==0.1.11 djangorestframework==3.11.0 fuzzywuzzy==0.17.0 gunicorn==20.0.4 idna==2.8 nltk==3.4.5 numpy==1.18.1 pandas==1.0.1 psycopg2==2.8.4 psycopg2-binary==2.8.4 python-dateutil==2.8.1 pytz==2019.3 requests==2.22.0 six==1.14.0 sqlparse==0.3.0 urllib3==1.25.8 whitenoise==5.0.1 how to use pip freeze --exclude command? -
In django, getting the following usernames in user profile
i'm building a following model. I have created a following model as shown below and it is working fine in the admin. I did not create a view for the following because i'm in primary stage of building i'm testing in templates to bring that usernames in userspostlist, but it's not working. my models.py for following: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE) following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='followed_by') def __str__(self): return str(self.following.all().count()) my views.py for userpostlist: class UserPostListView(ListView): model = post template_name = 'blog/user_post.html' #<app>/<model>_<viewtype>.html context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return post.objects.filter(author=user).order_by('-date_posted') and my userpostlist.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <h1 class="mb-3">posts by {{view.kwargs.username}}</h1> {% for user in username.owner.following.all %} {{ user.username }} {% endfor %} {% for post in posts %} <article class="content-section"> <div class="article-metadata"> <div class="img"> <img class="rounded-circle article-img" data-toggle="modal" data-target="#mymodal" src="{{ post.author.profile.image.url }}"> </div> <div class="profile-info"> <a class="h2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <div class="text-muted">{{ post.date_posted }}</div> </div> </div> {% endfor %} {% endblock content %} Is there any problem with the userpostlist view in views.py? do i need to add some code there? -
Why am i receiving IntegrityError (1062, "Duplicate entry '' for key 'username'")? Can you help me understand the solution to this?
I am receiving the following error (1062, "Duplicate entry '' for key 'username'") even though I haven't provided a username field at all. I am trying to save the updated info of the user in its existing Account table. Can you please help me understand the problem? The following are the details and code snippets. Thank you for your time in advance. Error: Request URL: http://127.0.0.1:8000/profile/profileUpdate/ Django Version: 3.0.2 Exception Type: IntegrityError Exception Value: (1062, "Duplicate entry '' for key 'username'") Exception Location: C:\Users\hp\Envs\test\lib\site-packages\MySQLdb\connections.py in query, line 239 Python Executable: C:\Users\hp\Envs\test\Scripts\python.exe Python Version: 3.7.3 froms.py: class ProfileUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('image', 'phone', 'guardianPhone', 'parrentPhone', 'emergencyPhone', 'address1', 'address2') models.py: class Account(AbstractBaseUser): username = models.CharField(max_length = 50, unique= True) email = models.EmailField(verbose_name = "email", max_length = 50, unique=True) image = models.ImageField(upload_to = "pics/", default = "user/noimg") dateTime_joined = models.DateTimeField(verbose_name="date joined", auto_now_add = True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) first_login = models.BooleanField(default=True) room = models.CharField(max_length = 10 , default = "unAssigned") 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 = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list #phone = PhoneNumberField(null=False, … -
Get rid of gunicorn.service and all traces of it completely
Objective: I'm trying to deploy a django project via gunicorn + nginx. Problem Encountered: Earlier on when I attempted to run sudo systemctl status gunicorn, I got this: ● gunicorn.service Loaded: not-found (Reason: No such file or directory) Active: failed (Result: exit-code) since Thu 2020-02-13 10:41:40 UTC; 20h ago Main PID: 9879 (code=exited, status=3) Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: File "", line 219, in _call_with_frames_removed Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: File "", line 994, in _gcd_import Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: File "", line 971, in _find_and_load Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: File "", line 953, in _find_and_load_unlocked Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: ModuleNotFoundError: No module named 'ussd' Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: [2020-02-13 10:41:40 +0000] [9899] [INFO] Worker exiting (pid: 9899) Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: [2020-02-13 10:41:40 +0000] [9879] [INFO] Shutting down: Master Feb 13 10:41:40 ubuntu-dev gunicorn[9879]: [2020-02-13 10:41:40 +0000] [9879] [INFO] Reason: Worker failed to boot. Feb 13 10:41:40 ubuntu-dev systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED Feb 13 10:41:40 ubuntu-dev systemd[1]: gunicorn.service: Failed with result 'exit-code'. Naturally, I figured out the error about the module not being present, got rid of this gunicorn.service file and created another (ussd-gunicorn.service) that works as shown below: ● ussd-gunicorn.service … -
Mod wsgi issue regarding django apache
I've been stuck in this django apache deployment. When I try to deploy my web page with linode(Linux base server) and tries to access to it, my website keeps showing this 500 Internal Server error. It happens after I ran this in my venv shell. $ sudo service apache2 restart enter image description here Since the web page suggest that I look into log file, which I did, I found I have mod wsgi issue. Here is my log file. [Fri Feb 14 06:43:49.388284 2020] [wsgi:error] [pid 26679:tid 140324755478272] [remote 121.131.97.11:51035] mod_wsgi (pid=26679): Target WSGI script '/home/harryghgim/django_project/django_project/wsgi.py' cannot be loaded as Python module. [Fri Feb 14 06:43:49.388369 2020] [wsgi:error] [pid 26679:tid 140324755478272] [remote 121.131.97.11:51035] mod_wsgi (pid=26679): Exception occurred processing WSGI script '/home/harryghgim/django_project/django_project/wsgi.py'. [Fri Feb 14 06:43:49.388622 2020] [wsgi:error] [pid 26679:tid 140324755478272] [remote 121.131.97.11:51035] Traceback (most recent call last): [Fri Feb 14 06:43:49.388720 2020] [wsgi:error] [pid 26679:tid 140324755478272] [remote 121.131.97.11:51035] File "/home/harryghgim/django_project/django_project/wsgi.py", line 16, in [Fri Feb 14 06:43:49.388726 2020] [wsgi:error] [pid 26679:tid 140324755478272] [remote 121.131.97.11:51035] application = get_wsgi_application() [Fri Feb 14 06:43:49.388734 2020] [wsgi:error] [pid 26679:tid 140324755478272] [remote 121.131.97.11:51035] File "/home/harryghgim/django_project/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Feb 14 06:43:49.388739 2020] [wsgi:error] [pid 26679:tid 140324755478272] [remote 121.131.97.11:51035] django.setup(set_prefix=False) [Fri Feb 14 … -
How to Get Unique Record for each category in django
I have a table called product_type & Product. class Product_type(models.Model): product_type_id = models.AutoField(primary_key=True) product_type_name = models.CharField(max_length=255, null = False, unique=True) product_type_title = models.CharField(max_length=255, null = True) product_type_description = models.TextField(null = False) product_type_slug = models.SlugField(unique=True, blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) class Product(models.Model): product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=255, null = False, unique=True) product_slug = models.SlugField(unique=True, blank=True, null=True) product_title = models.CharField(max_length=255, null = True) product_info = models.TextField(null = False) product_description = models.CharField(max_length = 255) product_price = models.CharField(max_length = 255) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True) product_status = models.CharField(max_length = 100, default = "publish") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) Now, i need data from product which match product type and only 1 record for each brand_id which have price minimum. I tried too much but nothing works. I want your help! -
How to solve the problem of type error in django?
I am trying to make newsletter working but whenever I enter an email it gives me the following error. Following error TypeError at / NewsletterUser() got an unexpected keyword argument 'newsletteremail' newsletteruser = NewsletterUser(newsletteremail=newsletteremail) views.py def index(request): if request.method == 'POST': newsletteremail = request.POST.get('newsletteremail', '') newsletteruser = NewsletterUser(newsletteremail=newsletteremail) newsletteruser.save() return render(request, 'home/index.html') admin.py admin.site.register(NewsletterUser) models.py class NewsletterUser(models.Model): email = models.EmailField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email -
ValueError: Cannot query "": Must be "Group" instance
I create custom user and Group model inherit the Abstract user modeland auth Group model. But I create the staff member and give some permission the same error trigger. then check the user permission the same error trigger. Put some code or error . How to figure out this error?? ` (Pdb) user=request.user (Pdb) user <SimpleLazyObject: <User: Gaurav@gmail.com>> (Pdb) user.groups.first() <UserGroup: Test> (Pdb) g1=user.groups.first() (Pdb) g1.permissions.all() <QuerySet [<Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | group | Can view group>, <Permission: camera | CameraGroup | Can add CameraGroup>, <Permission: camera | CameraGroup | Can change CameraGroup>, <Permission: camera | CameraGroup | Can delete CameraGroup>, <Permission: camera | CameraGroup | Can view CameraGroup>]> (Pdb) user.has_perm('view_cameragroup') *** ValueError: Cannot query "Gaurav@gmail.com": Must be "Group" instance.` -
Getting error in mongo connection during test case?
I am getting the following error during test condition. I did not understand where i am doing mistake. client = MongoClient(settings.MONGO_HOST, settings.MONGO_PORT) raise TypeError("port must be an instance of int") TypeError: port must be an instance of int -
PyLint: No name 'new file' in module 'main_app'
I created a file (permissions.py) in the main app(main_app). Now I imported it to an actual app view (actual_app): from main_app.permissions import SomeClass Pylint is throwing errors: E0611: No name 'permissions' in module 'main_app' (no-name-in-module) E0401: Unable to import 'main_app.permissions' (import-error) However if I excluded E0611, E0401 in the error checking, my program works perfectly fine. Any idea on this? -
Upgraded to Django3 and JSONField throws unexpected error
I have a weird issue. I recently upgraded to django3 from django 1.11 (python 3.8) The following piece of code works in django 1.11: models.py from jsonfield import JSONField class something(models.Model): answers = JSONField(blank=True) if 'csrfmiddlewaretoken' in self.answers: del self.answers['csrfmiddlewaretoken'] When i upgraded to django 3 I started getting the following exception: Traceback (most recent call last): File "/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/models.py", line 88, in save if 'csrfmiddlewaretoken' in self.answers: TypeError: argument of type 'NoneType' is not iterable So i did a quick fix and changed my code in django 3 to: models.py from django.contrib.postgres.fields import JSONField #JSONField in core Django wasnt compatible with Django 3 class something(models.Model): answers = JSONField(blank=True,null=True) if self.answers is not None and 'csrfmiddlewaretoken' in self.answers: del self.answers['csrfmiddlewaretoken'] This fix works. Just wanted to ask if this was the right way to do this. Thanks. -
How can I access a trained image (from CNN) to django application?
**Currently Iam doing a project in django server with postgres db** where I get input image from a trained set.My project is fully patched in python with a combination of opencv and django. Here in opencv part the team train some images and passing one output image with id no. to my django app. Can anyone please explain that , can I use my static folder to receive image and do further steps in django app? If the image storage is getting high what will be the best method to store images in server? How can I store different images in different folder with its id.no? -
How to solve the problem that DevTools is failed to parse?
Whenever I load the site, it gives me a bunch of errors in the console and cmd. I don't know how to deal with that?. I went to those locations but have no idea what to do with these things? Is there anyone to help me because it is not responding in firefox but responding just in chrome "GET /favicon.ico HTTP/1.1" 404 2264 [13/Feb/2020 13:32:06] "GET /static/home/js/popper.min.js.map HTTP/1.1" 404 1802 [13/Feb/2020 13:32:06] "GET /static/home/js/aos.js.map HTTP/1.1" 404 1781 [13/Feb/2020 13:32:06] "GET /static/home/js/typed.min.js.map HTTP/1.1" 404 1799 [13/Feb/2020 13:32:06] "GET /static/home/js/bootstrap.min.js.map HTTP/1.1" 404 1811 [13/Feb/2020 13:32:06] "GET /static/home/css/bootstrap-datepicker.css.map HTTP/1.1" 404 1838 [13/Feb/2020 13:32:06] "GET /static/home/css/aos.css.map HTTP/1.1" 404 1787 [13/Feb/2020 13:32:21] "GET / HTTP/1.1" 200 24434 [13/Feb/2020 13:32:22] "GET /static/home/css/bootstrap-datepicker.css.map HTTP/1.1" 404 1838 [13/Feb/2020 13:32:22] "GET /static/home/css/aos.css.map HTTP/1.1" 404 1787 [13/Feb/2020 13:32:22] "GET /static/home/js/popper.min.js.map HTTP/1.1" 404 1802 [13/Feb/2020 13:32:22] "GET /static/home/js/typed.min.js.map HTTP/1.1" 404 1799 [13/Feb/2020 13:32:22] "GET /static/home/js/bootstrap.min.js.map HTTP/1.1" 404 1811 [13/Feb/2020 13:32:22] "GET /static/home/js/aos.js.map HTTP/1.1" 404 1781 -
Django: How to use async tasks in data migrations?
I'm trying to populate my database using a Data Migration. In my populate function I have 2 api calls like this: async def populate_table(apps, schema_editor): some stuff... an api call like: await get_info()... an api call inside a for loop (any problem with this?) for i in range(): an api call like: await get_another_info()... more stuff... model.save() And then, I have my migration class: class Migration(migrations.Migration): dependencies = [ ('myapp', 'the previous migration'), ] operations = [ migrations.RunPython(populate_table) ] Running the migration a Runtime Warning is raised: RuntimeWarning: coroutine 'populate_table' was never awaited So I tried to decorate my Migration with Async/Await without success. How should I do that? And again, any problem to have async tasks inside a sync for loop? -
Unable to format break tags in reportlab 3.5.34
I'm using reportlab to generate a pdf document. I am using the following markup: <para><strong>Referred to MCH TVM.</strong></para><br/><para><i>Patient presented with bilateral neck nodes.</i></para><br/><para><i>O/E:</i></para><br/><para> Findings: klkllklklk</para><br/><para>Kindly advise.</para><br/> My code includes: regstyle = ParagraphStyle( name='Regular', fontName='Helvetica', fontSize=10, leading=12) AdviseBlock = Paragraph(f"{Advisedata}", style=regstyle) This gives the following error: 2020-02-14 10:46:19,921 django.request ERROR Internal Server Error: /clinic/presc/hm9x9HHIRg Traceback (most recent call last): File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joel/myappointments/clinic/views.py", line 5886, in GoGetPrescription clinicobj=clinicobj, File "/home/joel/myappointments/clinic/views.py", line 13466, in PDFPrescriptions elements = CreateAdvise(elements, cur_clinical_record) File "/home/joel/myappointments/clinic/views.py", line 13421, in CreateAdvise AdviseBlock = Paragraph(f"{Advisedata}", style=regstyle) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paragraph.py", line 1541, in __init__ self._setup(text, style, bulletText or getattr(style,'bulletText',None), frags, cleanBlockQuotedText) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paragraph.py", line 1563, in _setup style, frags, bulletTextFrags = _parser.parse(text,style) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3224, in parse annotateException('\nparagraph text %s caused exception' % ascii(text)) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 1394, in annotateException rl_reraise(t,v,b) File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 147, in rl_reraise raise v File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3222, in parse self.feed(text) File "/usr/lib/python3.6/html/parser.py", line 111, in feed self.goahead(0) File "/usr/lib/python3.6/html/parser.py", line 171, in goahead k = self.parse_starttag(i) File "/usr/lib/python3.6/html/parser.py", line 343, in parse_starttag self.handle_startendtag(tag, attrs) File "/usr/lib/python3.6/html/parser.py", … -
Invalid Block Tag on line 1: 'Load'. Did you forget to register or load this tag?
I am trying to add following line in my index.html {% Load Static %} Also added But on accessing the local host, I am getting above error. Can someone please help? -
How to load the same page after registration using django
I have this code in view.py def room(request, room_name): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('<str:room_name>/') else: form = UserCreationForm() and this is my url.py path('<str:room_name>/', views.room, name='room'), How to load the same page after registration using django -
DRF ImportError on importing serializers circular
I am using Django 2.2 and have two applications authentication and multi_users There is UserSerializer in authentication application. The multi_users model has a field shared_user and thus using UserSerializer in the multi_users.serializers to serialize the shared_user field. Now, there is AccessLevelPermissionSerializer class in the multi_users.serializers which I need in the authentication.serializers to serializer permissions of the user. This is giving error as ImportError: cannot import name 'AccessLevelPermissionSerializer' from 'multi_users.serializers' (/app/multi_users/serializers.py) authentication.serializers from authentication.models import Profile, User, Preference class UserBaseSerializer(UserDetailsSerializer): class Meta(UserDetailsSerializer.Meta): fields = ('email', 'first_name', 'last_name') class UserSerializer(UserBaseSerializer): from multi_users.serializers import AccessLevelPermissionSerializer permissions = AccessLevelPermissionSerializer(required=False) class Meta(UserDetailsSerializer.Meta): fields = UserBaseSerializer.Meta.fields + ( 'permissions' ) multi_users.serializers from authentication.serializers import UserBaseSerializer class SharedPermissionSerializer(serializers.ModelSerializer): class Meta: model = SharedPermission fields = [ 'code', 'name', ] class AccessLevelPermissionBaseSerializer(serializers.ModelSerializer): permission = SharedPermissionSerializer(required=False) class Meta: model = AccessLevelPermission fields = [ 'value', 'permission' ] # Import this in the `authentication.serializers` class AccessLevelPermissionSerializer(AccessLevelPermissionBaseSerializer): pass class MultiUserSerializer(serializers.ModelSerializer): shared_user = UserBaseSerializer(required=False) # Use from `authentication.serializers` class Meta: model = MultiUser depth = 1 fields = [ 'id', 'shared_user', 'access_level', ] How to resolve this circular import issue? -
Changes to the lock_wait_timeout variable in MySQL not being reflected in Django app
I've been trying to change the lock_wait_timeout variable in MySQL because the default value of 50 seconds is not suitable for my Django application. I've used the following commands: set innodb_lock_wait_timeout=2; show variables like 'innodb_lock_wait_timeout'; Although the show variables command confirms that my changes have been made, the timeout is still 50 seconds when my Django app is trying to acquire a lock on a locked record. This is the code snippet that I'm using to lock a particular record using Django: form = Form.objects.select_for_update().filter(id = form_details[FORM_ID]).first() I've tried restarting the MySQL service and even restarting my whole system, all to no avail. -
How to use field.set() for writable nested-many-to-many field in ModelSerializer's create function in Django REST Framework?
I'm sorry for the excesive/bloated title. I've previously asked similar question and tried to combine it with this answer. I've revamped my related models to implement that answer because I think I have similar requirements like his case. When a new Product is going to be created it may have multiple ProductDescription depending on the available languages. It also has multiple ProductImage with a boolean attribute to determine wether it's a default picture or not. The product has some attributes depending on the market it sold at. I save these attributes at ProductMarket model. models.py: class Market(models.Model, RecordStatus): name = models.CharField(max_length=100, null=True, blank=True) regions = models.ManyToManyField(Region) languages = models.ManyToManyField(Language) status = models.CharField(max_length=20, choices=RecordStatus.status, default=RecordStatus.drafted) class ProductImage(models.Model): image = models.ImageField(upload_to='product_images', width_field=None, height_field=None, max_length=250) default = models.BooleanField(verbose_name='Default Picture', default=False) class ProductMarket(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True, blank=True) slabs = models.ManyToManyField(Slab, null=True, blank=True) thicknesses = models.ManyToManyField(Thickness) finish_types = models.ManyToManyField(FinishType) class ProductDescription(models.Model): language = models.ForeignKey(Language, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(max_length=500, null=True, blank=True) class Product(models.Model, ProductStatus): product_code = models.CharField(max_length=6) color = models.ForeignKey(ColorParent, on_delete=models.SET_NULL, null=True) collection = models.ForeignKey(ProductCollection, on_delete=models.SET_NULL, null=True) images = models.ManyToManyField(ProductImage) markets = models.ManyToManyField(ProductMarket) descriptions = models.ManyToManyField(ProductDescription) video = models.URLField(verbose_name='Video URL', max_length=250, null=True, blank=True) status = models.CharField(max_length=20, choices=ProductStatus.status, default=ProductStatus.active) simplified … -
Can insert data to django test database before run test envirunment?
problem describe I'm looking for a way to insert data to django test database before run django test. This requirement happends because urls setting is written as below. urls.py group_names = Group.objects.values_list('name', flat=True) for group in group_names : url(r'^{}/{}'.format(group,'webindex'), web_index) for example, if there is group1 and group2 in database Group table, the url will be '/group1/webindex/' and '/group2/webindex/'. This works find when in production environment. The page show successfully. because the production database already exit group data. However when i want to write the testcase for web_index, problem happened. Here is my code. tests.py class webindexTestCase(TransactionTestCase): fixtures = ['./auth_group.json'] def test_webindex(self): c = Client() r = c.get('/group1/webindex/') print(r.status_code) when run the test, the http response code always get 404. As far as i know, it happended because when run django test the urls were set before insert the group data to test database. Therefore, i'm wondering is there a way to insert data to django test database before setting urls pattern, or reset the urls pattern when run this test?