Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add Bootstrap to Inbulit Login View Django
I am using the default view for logging the users.So I have not made any modelForm for it.So I am not able to provide any bootstrap class to the input fields i.e username and password. So my login form is looking ugly.Is there anyway. I want to add bootstrap class form-control to the input fields username and password. Following is my HTML and URL snippets. All functions and classes used have their modules imported. urls.py url(r'^login/$', login, {'template_name': 'app/login.html'}), login.html <form class="form-signin" method="post"><span class="reauth-email"> </span> {% csrf_token %} <!--{{form.as_p}}--> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} <!--<input class="form-control" type="email" required="" placeholder="Email address" autofocus="" id="inputEmail">--> <!--<input class="form-control" type="password" required="" placeholder="Password" id="inputPassword">--> <div class="checkbox"> <div class="checkbox"> <label><input type="checkbox">Remember me</label> </div> </div> <button class="btn btn-primary btn-block btn-lg btn-signin" type="submit">Sign in</button> </form> -
django-modeltranslation become a already exists field in translatable
I'm using django-modeltranslation to translate models in my app. I've a model wich I've sync with the db with migrate command. Also I've a lot of records for that model. class Home(models.Model): description = models.TextField() Of course, at this point, I can retrieve description field from db h = Home.objects.first() h.description # --> "This home is near to..." Now, I want to become the description field translatable using django-modeltranslation. I've follow de guide, I've registered the model for translation in the translation.py file, Finally I've executed makemigrations and migrate commands. This added to my db, in the home table, the fields description_en and description_es, as my availabe languajes are en and es, the former is the default. At this point i need to populate the description_en field wich is the default for any query, I tried Home.objects.all().update(description_en=F('description')) but it doesn't work because when it tries to access to the description field it in fact is trying to access to description_en, and it is empty: h = Home.objects.first() h.description # --> '' Empty?!!! I've check if the data still in the db and they are! My question is: if description data still in db, and h.description retrieve me in fact h.description_en, … -
Ajax send a list as a string instead of just a list
I am using jQuery to gather all the information entered on the webpage, and then using ajax to send this info to my django view. This is the code that takes care of that: var button = $("#serialise"); var JSON_content = $('#JSON_Contents') $(button).click(function() { var vals = []; $("#questions :input").each(function(index) { if($(this).attr('type') == 'checkbox') { if($(this).prop("checked")) { vals.push('on'); } else { vals.push('off'); } }else { vals.push($(this).val()); } }); vals = JSON.stringify(vals); var url = window.location.pathname; $.ajax({ method: "POST", url: url, data: { 'vals': vals }, dataType: 'json', success: function (data) { //On success } }); }); The view then receives the info here: def add_questions(request, review_id = None): if request.method == 'POST': vals = request.POST.get('vals', None) args = {'recieved': 'true'} return JsonResponse(args) The problem I am getting, is that the info that is sent, is sent as a string, not as a list. So its being sent as '["Example", "Example"]' instead of ["Example", "Example"]. I assume my vals = JSON.stringify(vals); is causing this, however if I remove this, nothing is received by the view. How do I turn it into the list like I want it to? -
Django adding img to the <option>
Hello i got a question to u guys. How can i add a specific img to each of this options in django <select id="sTypes2" name="current_tier" class="form-control input-lg c-square"> <option value="Silver I">Silver I</option> <option value="Silver II">Silver II</option> <option value="Silver III">Silver III</option> <option value="Silver IV">Silver IV</option> <option value="Silver Elite">Silver Elite</option> <option value="Silver Elite Master">Silver Elite Master</option> <option value="Gold Nova I">Gold Nova I</option> <option value="Gold Nova II">Gold Nova II</option> <option value="Gold Nova III">Gold Nova III</option> <option value="Gold Nova Master">Gold Nova Master</option> <option value="Master Guardian I">Master Guardian I</option> <option value="Master Guardian II">Master Guardian II</option> <option value="Master Guardian Elite">Master Guardian Elite</option> <option value="Distinguished Master Guardian">Distinguished Master Guardian</option> <option value="Legendary Eagle">Legendary Eagle</option> <option value="Legendary Eagle Master">Legendary Eagle Master</option> <option value="Supreme Master First Class">Supreme Master First Class</option> <option value="Global Elite">Global Elite</option> -
Issues with django and postgresql triggers
I have made several tables in a Postgres database in order to acquire data with time values and do automatic calculation in order to have directly compiled values. Everything is done using triggers that will update the right table in case of modification of values. For example, if I update or insert a value measured @ 2017-11-06 08:00, the trigger will detect this and do the update for daily calculations; another one will do the update for monthly calculations, and so... Right now, everything is working well. Data acquisition is done in python/Qt to update the measured values using pure SQL instruction (INSERT/UPDATE/DELETE) and automatic calculation are working. Everything is working well too when I use an interface like pgAdmin III to change values. My problem comes with development in django to display and modify the data. Up to now, I did not have any problem as I just displayed data without trying to modify them. But now I don't understand what's going on... If I insert a new value using model.save(), eveything is working: the hourly measure is written, the daily, monthly and yearly calculation are done. But if I update an existing value, the triggers seem to not … -
No questions asked when installing Django CMS - so no bootstrap
I installed Django CMS through Powershell using the command: pip install djangocms-installer I'm new to this, and the tutorial that I've been following suggested that I should be asked questions to set up Bootstrap and the SuperUser account. These questions weren't asked. Does anybody know know why and how I could change this by hand? The django docs don't seem to be much help here because they assume that the questions are asked. -
Django Changing css for base.html based on model instance field value
I have just built this notification system and it works great. However, I don't want to expect that a user will check the notifications page themselves, and so in order to notify the user that they have a new notification I would like the notification link in the nabber to have different css properties depending on if that user has any notifications that have not been read. I am a little stuck on this because the html link that should be changed is in my base.html rather than the app. Also, being that it is a notifications system and new notifications are created all the time and being marked read all the time it needs to be able to go through a loop and look at every notification pertaining to the logged in user. Here is my code, any help would be much appreciated. Notify app Model: class UserNotification(models.Model): fromUser = models.ForeignKey(User,related_name='user',null=True) post = models.ForeignKey('feed.UserPost',related_name='post') toUser = models.CharField(max_length=100,default='user') timestamp = models.DateTimeField(auto_now_add=True) notify_type = models.CharField(max_length=10) read = models.BooleanField(default=False) def get_absolute_url(self): return reverse('notify:user_notifications') def __str__(self): return str(self.fromUser) Base.html navbar: <nav> <div class="container"> <a class="brand" href="{% url 'index' %}">Evverest</a> <div class="navbar"> <a class="nav-link" href="{% url 'index' %}">Home</a> {% if request.user.is_authenticated %} <a class="nav-link" … -
Django rest framework if serializer returns empty
I have am implementing a follower and followers system in my drf api. My relationship model and serializer: models.py class Relationship(models.Model): user = models.ForeignKey(User, related_name="primary_user", null=True, blank=True) related_user = models.ForeignKey(User, related_name="related_user", null=True, blank=True) incoming_status = models.CharField(max_length=40, choices=RELATIONSHIP_CHOICE, default=RELATIONSHIP_CHOICE[0]) def __str__(self): return self.user.username + " " + self.incoming_status + " " + self.related_user.username serializers.py class RelationshipSerializer(serializers.ModelSerializer): outgoing_status = serializers.SerializerMethodField() class Meta: model = models.Relationship fields = ( 'user', 'related_user', 'incoming_status', 'outgoing_status', ) def get_outgoing_status(self, obj): related_user = obj.related_user user = obj.user try: query = models.Relationship.objects.get(user=related_user, related_user=user) user_id = query.incoming_status except models.Relationship.DoesNotExist: user_id = "none" return user_id views.py class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = serializers.UserSerializer @detail_route(methods=['get'], url_path='relationship/(?P<related_pk>\d+)') def relationship(self, request, pk, related_pk=None): user = self.get_object() query = models.Relationship.objects.filter(user=user)&\ models.Relationship.objects.filter(related_user__pk=related_pk) serializer = serializers.RelationshipSerializer(query, many=True) return Response(serializer.data) Incoming status is your relationship to the user and outgoing status is the users relationship to you to so for example this can return [ { "user": 2, "related_user": 1, "incoming_status": "follows", "outgoing_status": "none" } ] This means you follow the user and the user doesn't follow you back When you follow a user my code works fine because it returns "incoming_status": "follows" and it then checks for the outgoing status in the serializers. However when … -
Using Q to get reports not equal to
I'm on the last step of my view and I can get all reports to return using QVReportList.objects.all() it shows the report ID correctly in my template. However I'd like to use Q to show only the reports that don't exists in my reportdetail shown below: def profile(request): owner = User.objects.get (formattedusername=request.user.formattedusername) reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername).values('report_id','report_name','report_access') reportlist = QvReportList.objects.filter(~Q(report_id = reportdetail.report_id)) # excludedlist = QvReportList.objects.filter(report_id = reportlist.Report_ID) print(reportlist) args = {'user':owner, 'applicationaccess':reportdetail, 'applicationlist':reportlist}#, 'excluded':excludedlist} return render(request, 'accounts/profile.html', args) When I try to run it as it I get an AttributeError that states report_id doesn't exist, but it does when I can render it with applicationaccess.report_id and applicationlist.report_id: AttributeError at /account/profile/ 'QuerySet' object has no attribute 'report_id' Why does it state the object has no attribute report_id? It clearly exists in the existing database table and my models. -
ObjectDoesNotExist not catching a DoesNotExist exception
I'm trying to catch a DoesNotExist exception, and inspecting the code where the exception is thrown is difficult. I can't reach the line that throws it in pdb, and in the debug trace there's no information on what object is throwing the exception, as it is contained under an instance variable so the django trace doesn't show what it's value is. I have read the docs at https://docs.djangoproject.com/en/1.11/ref/exceptions/#objectdoesnotexist and this question at Catching Any DoesNotExist Error. Both of these indicate that to catch any DoesNotExist exception, one simply imports ObjectDoesNotExist and that covers all of them. It is not in my case. The exception is not caught in my except ObjectDoesNotExist block. Code: from django.core.exceptions import ObjectDoesNotExist def check_permission(user): """function checks whether the user is in the list of allowed groups""" for option in ALLOWED: # list of groups, constant try: if user.groups.get().name == option: return True except ObjectDoesNotExist: pass else: pass return False The trace reads: File ".../lib/python3.6/site-packages/django/db/models/query.py", line 379, in get self.model._meta.object_name django.contrib.auth.models.DoesNotExist: Group matching query does not exist. Which gets thrown from the line in my code: if user.groups.get().name == option attempting to access django.contrib.auth.models.DoesNotExist simply returns an AttributeError: model 'django.contrib.auth.models' has no attribute 'DoesNotExist' How do … -
Django - How to upload one file to multiple objects?
So the problem I'm face is that we have multiple shops that has the same image, so we would like to upload just one image then we create multiple objects from that image. The problem is that when we saved a model that file cannot be used anymore, seem like the file is closed. This is the error I've got. ValueError: seek of closed file -
Error: 2 issue, reverse accessors for foreign keys clashing
I'm struggling with my codes.I'm following this tutorial and i have some troubles. https://tutorial.djangogirls.org/en/django_forms/ . Could anyone can help me ? My models: model file from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here is my issue, reverse accessors for foreign keys clashing. Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packag s\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packag s\django\core\management\commands\runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\lib\site-packag s\django\core\management\base.py", line 472, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check id ntified some issues: ERRORS: blogapp.Post.author: (fields.E304) Reverse accessor for 'Post.author' clashes w th reverse accessor for 'Post.user'. HINT: Add or change a related_name argument to the definition for 'Post author' or 'Post.user'. posts.Post.user: (fields.E304) Reverse accessor for 'Post.user' clashes with re erse accessor for 'Post.author'. HINT: Add or change a related_name argument to the definition for 'Post user' or 'Post.author'. System check identified 2 issues (0 silenced).`enter code here` What could i do? -
Django admin - Auto save current user to model via inlines?
I have the following and it throws an error when I attempt to upload a document via the admin page for Proceeding. How can I auto populate the entered_by field for the Document model when using an inline? Error: IntegrityError at /admin/myapp/proceeding/6/change/ (1048, "Column 'entered_by_id' cannot be null") # models.py class Proceeding(models.model): date = models.DateField() entered_by = models.ForeignKey(User) class Document(TimeStampedUserModel): proceeding = models.ForeignKey(Proceeding) document = models.FileField(upload_to='documents/') entered_by = models.ForeignKey(User) #admin.py class DocumentAdmin(admin.ModelAdmin): fields = ('proceeding', 'document', ) list_display = ('proceeding', 'entered_by', ) def save_model(self, request, obj, form, change): instance = form.save(commit=False) instance.entered_by = request.user instance.save() form.save_m2m() return instance def save_formset(self, request, form, formset, change): def set_user(instance): instance.entered_by = request.user instance.save() if formset.model == Document: instances = formset.save(commit=False) map(set_user, instances) formset.save_m2m() return instances else: return formset.save() class DocumentInline(admin.TabularInline): model = Document fields = ( 'proceeding', 'document', ) extra = 0 class ProceedingAdmin(admin.ModelAdmin): inlines = [DocumentInline, ] fields = ('date',) list_display = ('date', 'entered_by', ) def save_model(self, request, obj, form, change): instance = form.save(commit=False) instance.entered_by = request.user instance.save() form.save_m2m() return instance def save_formset(self, request, form, formset, change): def set_user(instance): instance.entered_by = request.user instance.save() if formset.model == Proceeding: instances = formset.save(commit=False) map(set_user, instances) formset.save_m2m() return instances else: return formset.save() -
Django Email validation continue
I have next code(Using default django validations): def save(request): form = UserProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: return redirect('profile') My purpose is to save emails, such as anrd@gmail and etc. Emails without dots. How can I pass default validation to do it? Thx. -
I want to run a python script of machine learning algorithm using django.
The idea is to make a somewhat replica of Weka, only it won't be a desktop application but it will be a web application. Question.1: Is it even possible? Question.2: How do i run a python code and display results using Django? -
Python manage.py startapp does not work
When I run the python manage.py startapp "app name" command in my Django project directory nothing happens... Every other manage.py command works without problem. What could be the problem? Thanks a lot!! Andrew -
PIp exception error while insalling django
I am installing django in ubuntu using the command pip install django==1.11.2 but i am getting the following error Collecting django==1.11.2 Exception: Traceback (most recent call last): File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 555, in urlopen self._prepare_proxy(conn) File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 753, in _prepare_proxy conn.connect() File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connection.py", line 230, in connect self._tunnel() File "/usr/lib/python3.5/http/client.py", line 832, in _tunnel message.strip())) OSError: Tunnel connection failed: 407 Proxy Authentication Required During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 328, in run wb.build(autobuilding=True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 748, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 360, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 512, in _prepare_file finder, self.upgrade, require_hashes) File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 273, in populate_link self.link = finder.find_requirement(self, upgrade) File "/usr/lib/python3/dist-packages/pip/index.py", line 442, in find_requirement all_candidates = self.find_all_candidates(req.name) File "/usr/lib/python3/dist-packages/pip/index.py", line 400, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "/usr/lib/python3/dist-packages/pip/index.py", line 545, in _get_pages page = self._get_page(location) File "/usr/lib/python3/dist-packages/pip/index.py", line 648, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/lib/python3/dist-packages/pip/index.py", line 757, in get_page "Cache-Control": "max-age=600", File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get return self.request('GET', url, **kwargs) File "/usr/lib/python3/dist-packages/pip/download.py", line 378, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in … -
Error while running collectstatic while deploying Django to Heroku
I have a django rest framework api that I am trying to deploy to heroku. I run the git push heroku master command and everything works fine up until the collectstatic method is ran. remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 112, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 397, in listdir remote: for entry in os.listdir(path): remote: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_f0e1fb0957c8f67cf4c508df62f6ca99/assets' 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 … -
Django - Deleting all the related ForeignKeys to a model
I have a model called Team, with a ForeignKey relationship to Agent (my user model). When an Agent who is a team_leader deactivates the team, all the Agents with team_member set to the current team will have their team_member attribute removed and set to NULL/empty. I read this and this, I know I'm either supposed to do something with ._meta.get_fields() or with the Collector class. I'm experimenting with the get_fields() but haven't managed to get it working. models.py class Agent(AbstractUser): team_member = models.ForeignKey('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_member') team_leader = models.OneToOneField('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_leader') class AgentTeam(models.Model): team_is_active = models.BooleanField(default=False) views.py def deactivate_team(request): request.user.AgentTeam.team_is_active = False # request.user in this case is the team_leader # I need to set all the Agent's with team_member set to the request.user's team to NULL. I have experimented with the code below and gotten only errors, mostly related to ReverseToOne like ''ReverseManyToOneDescriptor' object is not iterable' agents = [ f for f in AgentTeam._meta.get_fields() if (f.one_to_many) and f.auto_created and not f.concrete ] for agent in agents: objects = getattr(AgentTeam, agent.name).all() for object in objects: object.team_member = None Please provide some comments and pointers on my views code and any errors I made. Thank you. -
Check if user has a permission with specific codename in django
I am trying to check if a user has a permission, which I have defined in the class Meta of the model, with a specific codename. At the moment I have: if request.user.has_perm('app_label.code_name'): do something What I am trying to avoid is using the app_label, however using has_perm('code_name') does not seem to work. -
Bad Request 400 on Django Heroku deployment
I'm facing a Bad Request (400) error on my Django deployment on Heroku. The logs show a SuspiciousOperation error, and specifically the platform nags about that: Su spiciousOperation: Attempted access to '/jquery/dist/jquery.min.js' denied. Traceback (most recent call last): ValueError: the joined path is located outside of the base path component I've set my ALLOWED_HOSTS to [.mydomain.com] although the error still persists. Any ideas? -
Django ModelAdmin: How to access data from inline fields?
models.py: class SomeClass(models.Model): name = models.CharField(max_length = 140) total = models.FloatField(default=0) items = models.ManyToManyField(Item, through="ItemDetail") def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length = 140) amount = models.FloatField(default=0) def __str__(self): return self.name class ItemDetail(models.Model): item = models.ForeignKey('Item') someclass = models.ForeignKey('SomeClass') quantity = models.FloatField() admin.py: class SomeInlineAdmin(admin.TabularInline): model = SomeClass.items.through extra = 1 class SomeClassAdmin(admin.ModelAdmin): fields = ('name','total',) readonly_fields = ('total',) inlines = (SomeInlineAdmin,) list_display = ['name','total',] So, basically when I am adding a new SomeClass through django admin, I would like to add a name, choose some items, mention their quantities and save. now, there's a total field in SomeClass. I would like it to be auto calculated and saved upon saving the model. I want the total to be like the following: total = summation of (item.amount)*(respective quantity mentioned in ItemDetail) I did some digging around save_model method. Couldn't help myself. So, how do i achieve this? I am still very new to Django. Thanks in advance for your help. -
Serializer in Django Rest is not returning a relation object
I have 4 models, one of them is a relation between the other three. The same for the serializers. But when I retrieve the data from the API I'm not receiving all the data, I'm only receiving the fields 'day', 'order' and 'time', not 'teacher', 'subject' and 'in_class' fields declared on ScheduleClassTeacherSubjectSerializer Models: class User(models.Model): name = models.CharField(max_length=20, unique=True, blank=False, null=False) class Subject(models.Model): name = models.CharField(max_length=20, unique=True, blank=False, null=False) class Class(models.Model): name = models.CharField(max_length=20, unique=True, blank=False, null=False) class ClassTeacherSubject(models.Model): teacher = models.ForeignKey(User, related_name='classes_subjects', on_delete=models.CASCADE, null=False, blank=False, ) subject = models.ForeignKey(Subject, related_name='classes_teachers', on_delete=models.CASCADE, null=False, blank=False, ) teaches_in = models.ForeignKey(Class, related_name='teachers_subjects', on_delete=models.CASCADE, null=False, blank=False, ) class Schedule(models.Model): MONDAY = 'MONDAY' TUESDAY = 'TUESDAY' WEDNESDAY = 'WEDNESDAY' THURSDAY = 'THURSDAY' FRIDAY = 'FRIDAY' DAY_CHOICES = ( (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), ) ORDER = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), ) day = models.CharField(max_length=10, choices=DAY_CHOICES, null=False, blank=False ) order = models.IntegerField(choices=ORDER, null=False, blank=False) time = models.TimeField(null=True, blank=True, ) class_teacher_subject = models.ForeignKey(ClassTeacherSubject, on_delete=models.CASCADE, null=False, blank=False, ) class Meta: unique_together = ('day', 'order', 'class_teacher_subject') Serializers: class TeacherSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', … -
How to catch sqlite database locked errors
I have code right now in a Django framework that needs to access a data stored in an Sqlite file and return it as JSON (GeoJSON specifically). This works, but I have a specific case where the database can be accessed in a locked state. I know why the problem is happening, but I'd like to know how to detect when it is happening, and return an appropriate response. My naive guess was to try to catch an Sqlite OperationalError, but this is non-effectual. The problem code: class GetVectorLayer(APIView): def post(self, request): ... ... import sqlite3 try: cache.write_layers(VectorLayer.objects.filter(pk=layer.pk), Formats.GeoJSON, file_path, epsg, bbox) except sqlite3.OperationalError as e: return Response("Cache Locked", status=status.HTTP_423_LOCKED) import json When this executes I get the same error as before I added the try: ERROR 1: sqlite3_step() failed: database is locked (5) The error happens in lower level code that is accessing the DB. That code throws whatever error that is printing to my console, but it doesn't seem to be actually raising an exception fortunately. The error happens when the cache is still being populated from an external source while someone tries to access data from it. I don't know how to properly check for this state … -
django how to change __str__ label by user status?
I want to change select option's label by user status. my model is class BookCategory(model): label_1 = char label_2 = char def __unicode__(self): #something here? class Book(model): name = char categoey = models.Foreignkey(BookCategory) BookCategory is used in createview for new book, and the page has modelform, textinput for book.name and choices for book.catgory. My goal is if user type==1: =>display category's label_1 if user type==2: =>display category's label_2 I know "__unicode__" can display instance's value, but I want to know change its field by user's status. Anyone knows the solution?