Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to sort events by date intervals Django REST
I'm working on a Django Rest project, building an API, and, since I got to the point to get all the events sorted by users, now I'm stuck on dividing those events by dates. For example, I want to sort between init_date and end_date, and be able to change the dates and display the events that occurred between those. -
How to take value from Django form?
I have a form with one field for choosing a method to sort objects. However, when I refer to this field to get it's value, it equals to HTML code that renders out this form. How do I solve this problem? My form: class sortChoice(forms.Form): CHOICES = [('sbd', 'Сортировать по дате'), ('sbp', 'Сортировать по популярности')] choice = forms.ChoiceField(choices = CHOICES, widget = forms.RadioSelect, label = 'Сортировка по') My view: @login_required(login_url = 'login') def vacancyListView(request): searchQueryNavbar = request.GET.get('search_navbar', '') searchQueryVLpage = request.GET.get('search_vlpage', '') form = sortChoice() print(form['choice']) if searchQueryNavbar or searchQueryVLpage: if searchQueryNavbar: searchQuery = searchQueryNavbar else: searchQuery = searchQueryVLpage if form['choice'] == 'sbp': queryset = Vacancy.objects.filter(Q(name__icontains = searchQuery) | Q(salary__icontains = searchQuery) | Q(competences__icontains = searchQuery)).order_by('-viewsAmount') if form['choice'] == 'sbd': queryset = Vacancy.objects.filter(Q(name__icontains = searchQuery) | Q(salary__icontains = searchQuery) | Q(competences__icontains = searchQuery)).order_by('-creationDate') else: queryset = Vacancy.objects.all().order_by('-viewsAmount') context = { 'objectList':queryset, 'form':form } return render(request, "vacancyList.html", context) Console output of print(from['choice']): <ul id="id_choice"> <li><label for="id_choice_0"><input type="radio" name="choice" value="sbd" required id="id_choice_0"> Сортировать по дате</label> </li> <li><label for="id_choice_1"><input type="radio" name="choice" value="sbp" required id="id_choice_1"> Сортировать по популярности</label> </li> </ul> -
IntegrityError at /update/70 NOT NULL constraint failed: tohome_task.title
I was updating the data in the database by takin the data from an html form when this appeared. I have faced this problem earlier also but I dont remember how to solve it . my views.py part def update(request,pk): task = Task.objects.get(id=pk) context = { 'task':task, } if request.method=="POST": task.title= request.POST.get('taskname' ) task.save() return redirect('/main') return render(request,"update.html",context) models.py file : class Task(models.Model): title = models.CharField(max_length =200) complete = models.BooleanField(default = False , blank=True) created = models.DateTimeField(auto_now=True) my html file : <div class="container"> <div class="jumbotron mt-3"> <form method= "post"> {% csrf_token %} <h1 class="text-center">{{task}}</h1> <input type="text" class="form-control rounded " id="task_name" name="task_name" aria-describedby="emailHelp" placeholder="Add the task !"> <p class="lead text-center" > Do you really want to update ?</p> <button class="btn btn-lg btn-primary" type ="submit" >Update &raquo;</button> </form> </div> </div> -
How to get subordinates, recursively?
I have Django models for Organizational Units (OrgUnit) which can be company, department, team, etc., ie. it is a tree structure: from django.db import models from django.contrib.auth.models import User from treebeard.mp_tree import MP_Node, MP_NodeManager class OrgUnit(MP_Node): # MP_Node adds a .path field name = models.CharField(max_length=120) Employees can be connected to one or more OrgUnits: class OUEmployee(models.Model): user = models.ForeignKey(User, related_name='employers', on_delete=models.CASCADE) orgunit = models.ForeignKey(OrgUnit, on_delete=models.CASCADE) ..and managers can manage several OrgUnits: class OUManager(models.Model): user = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE) manages = models.ManyToManyField(OrgUnit, blank=True) Now I want a queryset of all employees that are subordinates of a given manager, implemented as a method on OUManager, however, the current implementation only gives the employees connected directly to the OrgUnits the manager manages, not to the child-orgunits: def subordinates(self): return OUEmployee.objects.filter( orgunit__in=self.manages.all() ) i.e. given: root = OrgUnit.add_root(name='Acme Corporation') dept = root.add_child(name='Dept. of Anvils and Tunnels') team = dept.add_child(name='QA') emp1 = OUEmployee(user=User.objects.create_user(username='emp1'), orgunit=team) emp2 = OUEmployee(user=User.objects.create_user(username='emp2'), orgunit=dept) mngr = OUManager(user=User.objects.create_user(username='manager')) mngr.manages.add(dept) I would like employees = mngr.subordinates() to return a queryset with both emp1 and emp2 (the above implementation only return emp2). Is there a way to write subordinates so it only requires one db-hit? The best method I have come up with so … -
CKeditor not working on CreateVIew in Django
I've installed CKeditor and apply it to the models.py. I run the migrations and migrate it to DB. I tried to test it by going to the admin page. I can see that CKeditor is showing, but when I render it to my template using CreateView, it does not show. Models.py from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField class Content(models.Model): title = models.CharField(max_length=250) content = RichTextField(blank=True, null=True) date = models.DateField(auto_now_add=True) website = models.URLField() github = models.URLField() image = models.ImageField(upload_to=get_image_filename, verbose_name='Image') Forms.py class ContentForm(forms.ModelForm): class Meta: model = Content fields = [ 'title', 'content', 'website', 'github', 'image', ] Views.py class CreateContentView(CreateView): form_class = ContentForm template_name = 'appOne/create_content.html' Template <form method="POST">{% csrf_token %} {{ form.text | safe }} {{ form.media }} <input type="submit" value="Save"> </form> The weird thing is, in the Admin Page, the CKeditor works totally fine, but when I passed it to the template, the toolbar and menubar are not showing. -
Google Cloud VideoIntelligence Speech Transcription - Transcription Size
I use Google Cloud Speech Transcription as following : video_client = videointelligence.VideoIntelligenceServiceClient() features = [videointelligence.enums.Feature.SPEECH_TRANSCRIPTION] operation = video_client.annotate_video(gs_video_path, features=features) result = operation.result(timeout=3600) And I present the transcript and store the transcript in Django Objects using PostgreSQL as following : transcriptions = response.annotation_results[0].speech_transcriptions for transcription in transcriptions: best_alternative = transcription.alternatives[0] confidence = best_alternative.confidence transcript = best_alternative.transcript if SpeechTranscript.objects.filter(text = transcript).count() == 0: SpeechTranscript.objects.create(text = transcript, confidence = confidence) print(f"Adding -> {confidence:4.10%} | {transcript.strip()}") else: pass For instance the following is the text that I receive from a sample video : 94.9425220490% | I refuse to where is it short sleeve dress shirt. I'm just not going there the president of the United States is a visit to Walter Reed hospital in mid-july format was the combination of weeks of cajoling by trump staff and allies to get the presents for both public health and political perspective wearing a mask to protect against the spread of covid-19 reported in advance of that watery trip and I quote one presidential aide to the president to set an example for a supporters by wearing a mask and the visit. 94.3865835667% | Mask wearing is because well science our best way to slow the spread … -
unresolved import 'django.urls'
hello im using Django version 3.1.7 and python 3.9.2 and working on visual studio. so I set up a virtual environment with the command prompt and when I try to import django.urls or django.http it says unresolved import from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("hello world") -
Django Assigning or saving value to Foreign Key field
can any one help me with assigning value to a foreign key field. Im trying to create user profile where user can add there countries. when creating the models, from django admin page there is no problem adding countries im only having an error in the front end side when adding country select option and I got an error value ValueError: Cannot assign "{'countries': 1}": "RegsModel.nationality" must be a "Country" instance. please see my omitted code. models.py class RegsModel(models.Model): name = models.CharField(blank=True, max_length=64) nationality = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.Employee_ID class Country(models.Models): countries = models.CharField(blank=True, max_length=64) def __str__(self): return self.countries forms.py class RegsForm(forms.ModelForm): class Meta: model = RegsModel fields = '__all__' views.py def register(request): if request.method == "POST": form = RegsForm(request.POST) if RegsFrom.is_valid() form.save(commit=False) form.nationality = request.POST['nationality'] else: form = RegsForm(request.POST) return request('register', views.register, name='register',{'form':form}) register.html <form method='POST'> {{form.as_p}} <button type='submit'>add</button> </form> -
Runtime error after installing Django cms
I was in the process of doing a pip install to integrate payments to my Django website. When I run migrations I had gotten a module error that stated that Django cms could not be found. I fixed the problem by running pip install djangocms-installer I then receive this error when running migrations. Traceback (most recent call last): File "C:\Users\User\Desktop\rahisi-ecom\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\payrave\models.py", line 2, in <module> from cms.models import CMSPlugin File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\cms\models\__init__.py", line 2, in <module> from .pagemodel import * # nopyflakes File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\cms\models\pagemodel.py", line 1626, in <module> class PageType(Page): File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 108, in __new__ raise RuntimeError( RuntimeError: Model class cms.models.pagemodel.PageType doesn't declare an explicit … -
I am getting postgresql error while working in django rest framework?
My project was running fine. Then i opened my editor after a while and called my api then they are giving me this error. I don't know what is causing it. Exception Value: could not load library "/Library/PostgreSQL/13/lib/postgresql/llvmjit.so": dlopen(/Library/PostgreSQL/13/lib/postgresql/llvmjit.so, 10): Symbol not found: ____chkstk_darwin Referenced from: /Library/PostgreSQL/13/lib/postgresql/llvmjit.so Expected in: /usr/lib/libSystem.B.dylib in /Library/PostgreSQL/13/lib/postgresql/llvmjit.so enter image description here -
validate django field against another field on loaddata in django
I have a django model class eclipse(Base): type = models.CharField( choices=[1,2,3] default=1, ) daysVisible = models.PositiveSmallIntegerField(default=32767) recurrence = RecurrenceField(null=True, blank=True) and I have a json of eclipse data that I load in with loaddata.py How would I validate that the data loaded in has daysVisible equal to 1 if type is 1? -
How to get the result of a textfield to run python code in django
so i am making a python editor, and i have a model called NewJax. In this model, i have a field called space. The space field executes the python code i typed in there. for example, if i did print('hello') in the space field, it should take me to a detail page, and return the result. Which is hello. but when it takes me to the details page for now, it results in None. Could you someone please let me know, how this should execute? models.py class NewJax(models.Model): title = models.CharField(max_length=60) description = models.TextField(max_length=140) space = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_created'] verbose_name_plural = "New Jax" def __str__(self): return str(self.title) forms.py class CreateNewJaxForm(forms.ModelForm): class Meta: model = NewJax fields = ('title', 'description', 'space') widgets = { "title": forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'name your jax' } ), 'description': forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'add a brief description for jax', 'rows': 4, } ), 'space': forms.Textarea( attrs={ 'class': 'form-control', } ) } views.py def create_new_jax(request): if request.user.username == "Assasinator": logout(request) return redirect('banned_user') if request.method == "POST": form = CreateNewJaxForm(request.POST or None) if form.is_valid(): title = form.cleaned_data.get('title') description = form.cleaned_data.get('description') space = form.cleaned_data.get('space') obj = … -
Save Button Not Working with Attribute Error: 'WSGIRequest' object has no attribute 'project'
I checked the other posts on here that have the attribute error that I have, but they seem to be for different reasons. I am currently requesting the information from a form for users to update a project page. Then, if the form is valid, I am saving the form, saving the project, then trying to return redirect to the project page; however, when I click the button, the computer renders the error page. I will attach my forms.py, views.py, models.py, and urls.py: Views.py for the update section: @wraps(function) def wrap(request, *args, **kwargs): user = request.user name = kwargs.get('name') if uProjects.objects.filter(project=Project.objects.get(name=name), user=user, ifAdmin=True).exists(): return function(request, *args, **kwargs) else: return HttpResponseRedirect('/') return wrap @admin_check def update(request, name): project = Project.objects.get(name = name) if request.method == "POST": pr_form = ProjectUpdateForm(request.POST, request.FILES, instance=project) #if is_admin in Member == True: #need to authenticate user, access user permissions, if user has permission: if pr_form.is_valid(): pr_form.save() messages.success(request, f'This project has been updated.') request.project.save() return redirect('project') else: pr_form = ProjectUpdateForm(instance=project) context = { 'pr_form': pr_form } return render(request, 'projects/updateproject.html', context) forms.py for ProjectUpdateForm: class ProjectUpdateForm(forms.ModelForm): class Meta: model = Project fields=['name', 'department', 'department','bPic', 'logo', 'department', 'purpose', 'projectTag', 'lookingFor', 'recruiting'] urls.py from projects import views as p path('project/<str:name>/', … -
Django celery task api call
I build rss aggregation site, and I try to call iframely.com to get images for my rss objects entry(I save every entry in database). But, when I add celery task for this, rss aggregator don't get new entry and just nothing happend, 0 errors. Task don't run. My code: class Post(models.Model): # an entry in a feed source = models.ForeignKey(Source, on_delete=models.CASCADE, related_name='posts') title = models.TextField(blank=True) body = models.TextField() link = models.CharField(max_length=512, blank=True, null=True) ... def save(self, *args, **kwargs): from .tasks import save_thumbnail_url if not self.image_url: self.image_url = save_thumbnail_url.delay(self.id) super(Post, self).save(*args, **kwargs) I try also post_save signal, same effect. Task: def get_thumbnail_from_url(post: Post): if not post.image_url: req = requests.get('https://iframe.ly/api/oembed?url=' + post.link + '&api_key=493c9ebbdfcbdac2a10d6b') thumbnail_url = req.json()['thumbnail_url'] post.objects.filter(id=post.id).update(image_url=thumbnail_url) @shared_task def save_thumbnail_url(post_id: int): get_thumbnail_from_url(Post.objects.get(id=post_id)) -
Getting Foreign Key data in Django Admin Add/Change Form
I am trying to customise the Django admin add/change for a project. I have created a model called "Visit" which contains 3 Foreign Key fields: "Customer", "Pet" and "Doctor". The workflow is as follows: The user creates a customer. The user creates a pet and associates it with a customer. The user creates a visit and associates it with a pet and a doctor. Below is the code for my models.py class Visit(models.Model): customer = models.ForeignKey('customer.Customer', on_delete=models.CASCADE) pet = models.ForeignKey('pet.Pet', on_delete=models.CASCADE) date = models.DateTimeField() doctor = models.ForeignKey( 'configuration.Doctor', on_delete=models.DO_NOTHING, null=True, blank=True) status = models.CharField( choices=PET_STATUS, max_length=3, null=True, blank=True) reason = models.CharField(max_length=255) diagnosis = models.TextField(null=True, blank=True) treatment = models.TextField(null=True, blank=True) comment = models.TextField(null=True, blank=True) prescription = models.TextField(null=True, blank=True) weight = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True) class Meta: ordering = ('-date',) My issue is that someone using the Django Admin to create a Visit can wrongly choose a Customer and Pet. Hence, the Customer does not own that Pet. I would like to know how can I customise the Django Admin, so that, when the user selects a Customer, only Pets under that particular Customer is displayed in the dropbox. Below is my admin.py class VisitAdmin(admin.ModelAdmin): change_form_template = 'visit/invoice_button.html' add_form_template = 'visit/add_visit.html' … -
@login_required decorator redirecting back to login, after log in
My web app successfully logs in the user into the home page (pick.html) but however when clicking on a link in the navigation bar ('Home'), the user gets logged out when the @login_required decorator is used in the pick.html view. views.py: def postsign(request): email=request.POST.get('email') passw=request.POST.get('pass') try: user=auth.sign_in_with_email_and_password(email,passw) except: message="Invalid credentials. Try again." return render(request,"login.html", {"msg":message}) session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"pick.html") @login_required(login_url='login') def pick(request): return render_to_response('pick.html') pick.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>FYP - Is Your Network Safe?</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/bootstrap/css/loader.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/grayscale.min.css' %}" rel="stylesheet"> <script src="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js"></script> <link href="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css" rel="stylesheet" /> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">TestPage</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> Menu <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'pick' %}">Home</a> </li> <li class="nav-item"> … -
Django i18n prefix_default_language=False can't redirect back to default language
I'm adding support for German on an English default site. I want the German version to add the /de/ prefix to all URLs as Django suggests but want to keep the standard URLs for the English version so it doesn't break the links I already have set up. The prefix_default_languge=False works as expected when you go directly to the URLs. The form that Django supplies switches to German correctly but doesn't allow you to switch back to the default language. This is only a problem with it set to False, When True the form works as expected (adding the /en/ prefix) and if I disable the i18n_patterns and just change the language without the URL changing the form also works. Why is this a problem just when prefix_default_language=False? urls.py: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.urls import include, path urlpatterns = [ path("admin/", admin.site.urls), path("staff/", include("stats.staff_urls")), path("i18n/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns( path("", include("stats.urls")), prefix_default_language=False, ) settings.py LANGUAGE_CODE = 'en' LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) LANGUAGES = ( ('en', 'English'), ('de', 'German'), ) TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True form.html {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <form … -
Sorting serialized data - Django - getting keyerror
Version Info: Django: 1.11.2 Python 2.7 In my application, I want to sort by a field in the data that is returned by the serializer, however, it is throwing an error. The resultset is of type rest_framework.utils.serializer_helpers.ReturnList, the data is given below (only sample, actual data is pretty huge). [OrderedDict([(u'id', 941), ('business_location', {'distance': 3.7249839781687317, 'business': 941, u'id': 916}), ('business_detail', {'business_profile': u"Good solutions!", 'website': None}), ('business_images', []), ('business_service', [OrderedDict([(u'id', 1587), ('length_of_slots', 12), ('price', 25.0), ('business_group', None)])])]), OrderedDict([(u'id', 1595), ('business_location', {'distance': 6.376269428282773, 'business': 1595, u'id': 1634}), ('business_detail', {'business_profile': u'A long-term wellness.', 'website': None}), ('business_images', []), ('business_service', [OrderedDict([(u'id', 5361), ('length_of_booking_slot', u''), ('price', 125.0), ('business_group', None)])])])] The error I'm getting is (KeyError('price',), 'price') The views.py, I'm using this code to sort by price. sorted(business_serializer.data, key=lambda k: (k['price'])) Kindly suggest what is that I'm doing wrong. Also, I would want to implement ASC/DESC functionality. Note: I tried to implement order_by in the serializer, since my data has a different category & each of them will have a price it is not getting sorted at the result level. -
Django: How to treat null as equal to everything for uniqueness constraints?
In the title I mean equal to any value, not just to other nulls. Let's say for the sake of the example that we have a household, with household members (people) and electronic devices. Some electronic devices are personal and belong to one person, but some do not belong to any one household member, like for example a common computer in the study. We might then model electronic devices like this: class ElectronicDevice(models.Model): name = models.CharField(null=False, max_length=64) owner = models.ForeignKey(HouseMember, null=True, on_delete=models.CASCADE) Now let's say we want device names to be unique from the perspective of house members. A house member should not have two devices available for them which have the same name. So name and owner should be unique together, but there should also not be two devices, one private and one common (owner is null) which have the same name. Thus a normal UniqueConstraint: class Meta: constraints = [ models.UniqueConstraint(fields=['name', 'owner'], name='uniqe_device_name'), ] would not do, since it still allows two devices to have the same name if for one of them owner is null. Only constraining the name field: class Meta: constraints = [ models.UniqueConstraint(fields=['name', ], name='uniqe_device_name'), ] also would not do, because this would not … -
Access User object from FilterSet init Django
I am trying to set django filter choices for User Groups. I have tried setting the init function but I am not able to get the self.request to access user's groups. def __init__(self, *args, **kwargs): super(Filter, self).__init__(*args, **kwargs) self.filters['group'].extra['choices'] = [ (group.id, group.name) for group in self.request.user.groups.all() ] -
Django: How do I remove the ending "?" from the URL
I need to remove the "?" at the end of my URL: urls.py urlpatterns = [path("map_fslis_top/totals/<int:fstype_id>", views.edit_totals, name="edit_totals"),] view.py def edit_totals(request, fstype_id): # Some code... return render(request, "DataMech/totals.html", { 'fstype': fstype, 'typefslis': typefslis, 'totals': totals, }) html trigger <button href="{% url 'edit_totals' fstype_id=fstype.id %}" class="btn btn-primary" class="form-control" type="submit" value="submit">Totals</button> The URL of the page generated: http://127.0.0.1:8000/map_fslis_top/totals/1? How do I get rid of that ugly "?" at the end of the URL? -
Django development stage best practice
I am going to be working on a Django Project for my final requirement in school, and I am wondering if I should use PostgreSQL on development stage or if I should stick with built-in sqlite3 during development. I am worried if I used sqlite3 on development stage there will be problems with migrations if I switch to PostgreSQL on Production. -
I added a timefield in a model in django, when I applied migrations there was an error, when I removed that field in the model there still was error
Error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, tohome Running migrations: Applying tohome.0003_auto_20210323_1611...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\core\management\commands\migrate.py", line 245, in handle fake_initial=fake_initial, File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site- packages\django\db\migrations\operations\fields.py", line 106, in database_forwards field, ) File "C:\Users\madhu\Desktop\Django work\work_env\lib\site-packages\django\utils\dateparse.py", line 90, in parse_time match = time_re.match(value) TypeError: expected string or bytes-like object models.py from django.db import models class Task(models.Model): title = models.CharField(max_length =200) complete = models.BooleanField(default = False , blank=True) created = models.DateTimeField(auto_now=True) settime = models.TimeField((""), auto_now=False, auto_now_add=False) def __str__(self): return … -
I'm getting this error when i'm trying runserver in pycharm
File "C:\Users\rajiv\anaconda3\envs\deep learning\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\rajiv\anaconda3\envs\deep learning\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\rajiv\PycharmProjects\pyshop\venv\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\core\management\commands\testserver.py", line 34, in handle db_name = connection.creation.create_test_db(verbosity=verbosity, autoclobber=not interactive, serialize=False) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\utils.py", line 211, in __getitem__ self.ensure_defaults(alias) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\utils.py", line 172, in ensure_defaults conn = self.databases[alias] File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\db\utils.py", line 153, in databases self._databases = settings.DATABASES File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "c:\users\rajiv\pycharmprojects\pyshop\venv\lib\site-packages\django\conf\__init__.py", line 67, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or ca ll settings.configure() before accessing settings. -
How to get values for a chart with JavaScript in Django?
I created an application with Django. In this system, there is an approval system. I created an ApprovalProcess model and it has a beginning_date field. I crated a chart for showing how many approval processes are started on which day? But I cannot fill this chart. But I cannot figure it out how can I get approval process values as my data? models.py class ApprovalProcess(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter') doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True) begin_date = models.DateTimeField(auto_now=True) end_date = models.DateTimeField(auto_now=True) status = models.IntegerField(default=0) highest_rank = models.IntegerField(default=0) last_approved = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='last_approved') customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) views.py def approval_context_processor(request): if request.user.is_authenticated: current_user = request.user rank_priority = RankPriority.objects.filter(rank=current_user.rank) priority = rank_priority[0].priority pend_list = ApprovalProcess.objects.filter(status=priority) submit_list = ApprovalProcess.objects.filter(user_id=current_user) userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) all_approvals = ApprovalProcess.objects.filter(user_id__company=request.user.company) approved_reports = 0 waiting_reports = 0 for submit in submit_list: if submit.status - submit.highest_rank == 1: approved_reports += 1 else: waiting_reports += 1 else: pend_list = 0 submit_list = 0 context = { 'pend_list': pend_list, 'submit_list': submit_list, 'approved_reports': approved_reports, 'waiting_reports': waiting_reports, 'customer_list': customer_list, 'all_approvals': all_approvals } return context chart <div class="row"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <div class="card-head-row"> <div class="card-title">User Statistics</div> <div class="card-tools"> </div> </div> </div> <div class="card-body"> …