Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
floatformat causes data not to render
I am trying to use the built in filter floatformat to format my data but its just causing it not to render. I can print the data fine using {{ form.field }} but when I add {{ form.field|floatformat:2 }} the data does not render. I thought it might be from the fact I a passing it to my template as a dictionary and therefor it's treating my data as a string which could cause some errors but I am not completely sure how to check that or if that is even the problem. -
App label over-riding an earlier app label
How can I assign a Django app, a label (e.g. auth) to over-ride an earlier application? The django.contrib.auth.… modules claim the app label auth. I want to have that installed, but claim the auth label for my site's custom auth app. -
Django URL tag makes variable suddenly be empty?
Weird puzzling problem. In my Django template, I can display a variable using {{item.slug}} and it's just fine. But, when I use that same variable in a URL tag, it's an empty variable. for example... <a href="{{item.slug}}">{{item.name}}</a> ...that works. <a href="{%url 'charts:ye_songs' start|date:"Y" 'r' 'label' item.slug %}">{{item.name}}</a> ...but that results in an error because item.slug is an empty string. I'm bamboozled what could be causing that. At first I thought it was 'cause I was using UTF-8 slugs, but that can't be the issue 'cause it does this with regular ol' Latin-1 ASCII characters too. If I hard code the variable, it works whether I use ASCII or UTF-8 characters. Also, this only occurs in this section of code. Other url tags aren't having this issue. Even the url's using the 'charts:ye_songs' are working as expected. I also tried using item.name where I'm using the slug. That displays the var string. My url.py path for this link looks like this... path('<int:chartyear>/<slug:sor>/<str:chart_type>/<str:slug>', views.ye_songs, name='ye_songs'), ...and that works for everything using this except for this particular bit. If I change the <str:slug> to <slug:slug>, then the variable string shows up but it results in a new error that affects all the links … -
What is the best way to upload a django project to cPanel?
I am trying to figure out an easy way to upload a django project to cPanel. Is there a way to do it with gitHub? I know how to make a python app, but I do not want to rebuild the whole thing. How can I upload an entire project? -
"Requested setting INSTALLED_APPS, but settings are not configured" error
getting this error in django project any ideas? File "C:\Users\Israel\PycharmProjects\defi\venv\lib\site-packages\django\conf_init_.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [screenshot][1] [1]: https://i.stack.imgur.com/vnyqW.png -
VCSNotInstalled: 'git' is not installed error with cookiecutter, but git is installed
I've been trying to create a project using cookiecutter but for some reason it doesn't identify my git installation. I'm running on Windows 10 and the installation was done with GitHub Desktop. (everycheese) C:\Django>cookiecutter gh:roygreenfeld/django-crash-starter Traceback (most recent call last): File "C:\Users\user\.conda\envs\everycheese\Scripts\cookiecutter-script.py", line 9, in <module> sys.exit(main()) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 829, in __call__ return self.main(*args, **kwargs) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 782, in main rv = self.invoke(ctx) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\click\core.py", line 610, in invoke return callback(*args, **kwargs) File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\cli.py", line 140, in main cookiecutter( File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\main.py", line 67, in cookiecutter repo_dir, cleanup = determine_repo_dir( File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\repository.py", line 110, in determine_repo_dir cloned_repo = clone( File "C:\Users\user\.conda\envs\everycheese\lib\site-packages\cookiecutter\vcs.py", line 84, in clone raise VCSNotInstalled(msg) cookiecutter.exceptions.VCSNotInstalled: 'git' is not installed. Nevertheless, when I run git from the Command Prompt it recognizes the command. Any ideas why cookiecutter might not be recognizing my git installation? -
Different rendering of same template with different views
I'm having a weird behaviour on my Django (3.0.3) site that is driving me mad. I have a CreateView and an UpdateView for my blog posts; both use the same post_form template, that extends from the base one. The problem is that when creating a new post my page is shown correctly, while when editing a post the styling is ignored! I'm completely lost... any help or direction to look at would be greatly appreciated. views.py ... class EditPost(LoginRequiredMixin, UpdateView): login_url = 'blog:login' model = Post form_class = PostForm class NewPost(LoginRequiredMixin, CreateView): login_url = "blog:login" model = Post form_class = PostForm def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.authorInfo = self.request.user.get_full_name() self.object.save() return redirect(self.get_success_url()) ... post_form.html {% extends "base.html" %} {% block title %} {% if form.instance.pk %} Edit post {% else %} Create post {% endif %} - {% endblock %} {% block content %} <div id="journal"> <div id="content"> {% if form.instance.pk %} <h2>Edit post</h2> {% else %} <h2>New post</h2><br> {% endif %} <form class="post-form" method="POST"> {% csrf_token %} {% for field in form %} <br> <p>{{field.label_tag}}{{field}}</p> {% endfor %} <button id="formButton" class="btn" type="submit">Save post</button> </form> </div> </div> {% endblock %} -
Page not found (404) Request Method: GET Request URL: http://localhost:8000/edit [closed]
Wondering if someone can help with an issue I'm having with an error message I received on my code. enter image description here Below is my urls.py enter image description here below is my views.py enter image description here and below is my html enter image description here -
DRF How to duplicate make duplicate of related FK
My models class Inspection(models.Model): user = models.ForeignKey(User, related_name="inspection", on_delete=models.CASCADE, blank=True, null=True) inspection_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Category(models.Model): inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE, related_name="categories") category_name = models.CharField(max_length=255) is_done = models.BooleanField(default=False) class Task(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='tasks') task_name = models.CharField(max_length=255) photo = models.FileField(upload_to="upload/task_photo", blank=True, null=True) text = models.CharField(max_length=355) is_done = models.BooleanField(default=False) contact_info = models.CharField(max_length=100) Question is how can I create duplicate of this 3models on POST request?? Any suggestions? -
Django reputation / like system for public user profile - error 404
I hope you're well :) I'm beginning with Django. I try to use a like system for the public profile of my users. But I don't understand why I got an error 404. Do you think it's possible to use PK with OneToOneField for user? user/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) reputation = models.ManyToManyField(User, related_name='user_reputation') ... user/views.py # public profile reputation @login_required(login_url='/earlycooker/login') def ReputationView(request, pk): userprofile = get_object_or_404(UserProfile, id=pk) if request.method == "POST": userprofile.reputation.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @property def total_reputation(self): return self.reputation.count() user/urls.py path('reputation/<int:pk>/', ReputationView, name="reputation_public"), user/templates/user_public_profile.html <form action="{% url 'user:reputation_public' user.pk %}" method="POST">{% csrf_token %} <button type="submit" name="user_id" value="{{ user.id }}" style=""><img src="/static/img/like.png" width="20px" height="20px" class="" style="border-radius: 90px;background: #ffffff36;" title=""> {{current_user.userprofile.total_reputation}} cherries</button> </form> Thanks a lot for your help, -
Default the value of an external key in a form
In the form for adding a calendar (of the Model "Calendar"), in the "group" field shows a drop-down menu where all the "CalendarGroups" are. I would like this menu not to be there and "group" to be set by default with the "group" id which I pass through the url parameter ("group_id"). How could I solve this? In models.py: class CalendarGroups(models.Model): name = models.CharField(max_length = 155, blank=True, null=True, unique=True) def __str__(self): return str(self.name) @property def get_html_url(self): url = reverse('', args=(self.id,)) return f'<a href="{url}"> {self.name} </a>' class Calendar(models.Model): name = models.CharField(max_length=200, unique=True) #created_by group = models.ForeignKey(CalendarGroups, on_delete = models.CASCADE, default='') @property def get_html_url(self): url = reverse('cal:calendar_view', args=(self.id, self.group)) return f'<a href="{url}"> {self.name} </a>' In forms.py: class CalendarGroupsForm(ModelForm): class Meta: model = CalendarGroups fields = ('name',) def __init__(self, *args, **kwargs): super(CalendarGroupsForm, self).__init__(*args, **kwargs) class CalendarForm(ModelForm): class Meta: model = Calendar fields = ('name', 'group') def __init__(self, *args, **kwargs): super(CalendarForm, self).__init__(*args, **kwargs) In views.py: def group(request, group_id=None): instance = CalendarGroups() if group_id: instance = get_object_or_404(CalendarGroups, pk=group_id) else: instance = CalendarGroups() form = CalendarGroupsForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) def calendar(request, group_id=None): instance = Calendar() form = CalendarForm(request.POST or None, instance=instance) if request.POST and … -
Django-ajax submitted data and created but gives error
I created a signup function captcha with the ajax method. if the user fills up fillup captcha correctly user account is created but the user doesn't fillup captcha code incorrectly user not created. It is ok. The problem is when user-submitted data always goes to the error block in the ajax part. if the user fillup invalid captcha it doesn't give any error. How can I fix it? HTML part <form class="user_signup_sidebar_form" action="{% url 'account:signup-sidebar' %}" method="post" data-mail-validation-url="{% url 'account:check_if_email_available' %}" id="customer-signup-form"> {% csrf_token %} <fieldset> {% bootstrap_form_errors form type="non_fields" %} {% for field in signform %} {% if not forloop.last %} {% bootstrap_field field %} {% endif %} {% endfor %} <div class="captcha_wrapper"> <label for="id_captcha_1" id="id_captcha_2">{{ signform.captcha.label }}</label> <div class="captcha_input"> {% bootstrap_field signform.captcha show_label=False %} <div class="captcha_reloader"> <span><i class="icon-refresh" id="js-captcha-refresh_modal"></i></span> </div> </div> </div> <style type="text/css"> </style> {# <input type="hidden" id="id_next" name="{{ REDIRECT_FIELD_NAME }}" value="{{ request.get_full_path }}"/>#} </fieldset> {% url 'page:details' slug='customer-terms-conditions' as page_details_url %} <p>By clicking "Signup", you agree on aadi <a target="_blank" href="{{ page_details_url }}">Terms & Conditions</a>.</p> <div class="form-group w-100 align-items-center d-flex justify-content-center m-0"> <button title="Signup" type="submit" class="btn btn-dark w-100 text-uppercase">Signup</button> </div> <a title="Seller Signup" rel="nofollow" class="link--styled pt15" href="{% url 'account:vendor-signup' %}"> Want to be a seller at … -
How can you dynamically set initial value of form select field at the time of rendering django template
I have a requirement to render select field multiple times and each field will have pre-selected value. Now My question is: How can you dynamically set initial value of django form selectfield at the time of rendering django template?? my form: class RequestProdApvr(forms.Form): product = forms.ModelChoiceField(queryset=SPA_Product.objects.all().order_by('hierarchy_code'), label='', required=False) I have to use this form in multiple row in my listview and pre-populate value based on saved data. I searched SO for the solution and non of them met my requirement... Django. Initial value of Choice Field dynamically Dynamically set default form values in django Hence I am posting separate question here... -
Things to check when there is 'no such table' exception in Django
I defined a new model in django. It looks like this: class User(models.Model): email = models.EmailField(primary_key=True) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' is_anonymous = False is_authenticated = True I've registered the app it is contained under into the settings.py INSTALLED_APPS = [ # 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'lists', 'accounts', # <-- this ] I've flushed database, re-made migrations and migrated. So that I do not have any you have un-applied migrations messages when running server. However, the django.db.utils.OperationalError: no such table : accounts_user persists. I've used shell, and it too throws error: >>> from accounts.models import * >>> User <class 'accounts.models.User'> >>> User.objects <django.db.models.manager.Manager object at 0x7fbcbea35ef0> >>> User.objects <django.db.models.manager.Manager object at 0x7fbcbea35ef0> >>> User.objects.all() Traceback (most recent call last): django.db.utils.OperationalError: no such table: accounts_user I've exhausted all other options known to me. Can someone provide a general check-list for things to check (no matter how stupid), when faced with an error like this? -
Pass extra params in DRF serializer class
I am trying to pass arguments table_name and serial_class to the serializer class, but request.data_name says Name error : request is not defined http://localhost:8000/get_data??format=json&table_name=something&serial_class=other Please suggest where I am doing wrong views.py class get_data(generics.ListAPIView): table_name = eval(request.GET.get('table_name')) # NOT WORKING serial_class = eval(request.GET.get('serial_class')) # NOT WORKING start = table_name.objects.values("start_date").order_by("-start_date")[0]['start_date'] end = table_name.objects.values("end_date").order_by("-end_date")[0]['end_date'] queryset = table_name.objects.filter(start_date=start,end_date=end) serializer_class = serial_class serializer.py class OrdersDataSerializer(serializers.ModelSerializer): class Meta: model = orders_data fields = '__all__' -
How reverse an include pattern path in Django
Hi i am wondering how i can reverse a urlpattern path that uses include pattern. Since there is no namespace i don't know how to reverse it. Also i am new to Django so all this is a little bizarre to me. v1_api = Api(api_name='v1') urlpatterns = [path('', include(v1_api.urls))] + restless.get_urls()] + restless.get_urls() I want to use from django.urls import reverse class SiteResource(ModelResource): baselayer = fields.ToOneField( 'erma_api.api.resources.data_layer.DataLayerResource', 'baselayer', null=True) class Meta(ModelResource.Meta): queryset = models.Site.objects.all() resource_name = 'site' authorization = SiteAuthorization() validation = CleanedDataFormValidation(form_class=SiteForm) detail_allowed_methods = ['get', 'post', 'put', ] list_allowed_methods = ['get', 'post'] excludes = [] abstract = False filtering = { 'site_name': ALL, 'verbose_site_name': ALL, 'site_id': ALL, 'site_path': ALL, 'extent': ALL, } -
Django: Get a queryset of ForeignKey elements from another queryset
Let's say I have a Foo class. Given a queryset of Foo, how can I retrieve the queryset of Users? class Foo(models.Model): user = models.ForeignKey("users.User", related_name="foos") ... foo_objects = Foo.objects.all() One method I've seen is: users = Users.objects.filter(id__in=list(foo_objects.values_list("user_id", flat=True)) Is there any way to get the list of all users in the foo_objects queryset without this list conversion? users = User.objects.filter(user_id__in=foo_objects.values("user_id")) If the second option works– does anyone have any experience re: which method works better with postgresql? I've heard nested queries (the second option) doesn't work great on some databases. -
Can I create a progressive web application in django?
Convert the Django website to a progressive web application. Would it work on mobile devices? What do I need, due to the loss of connection through Wifi, in a private network. I run Python with Django and postgresql, when I run: python3 manage.py runserver_plus 0.0.0.0:8000, within the same network I can connect with my mobile device, but I want to use the web application in offline mode. I use Service Worker, in offline mode, but it doesn't work for me on mobile devices. Why Sera? It doesn't give me an error, just when I connect from a mobile device and when I want to use it in offline mode it doesn't work, but it works in Chrome on laptop. One of the requirements, if I'm not mistaken is to use SSL certificate in Django? Please help me. -
How can I Upload Files to AWS S3 Using React Js with Django and GraphQl in the Backend?
I am trying to upload audio files to AWS S3 using React in the frontend and a backend built with Django and Graphene. I keep getting the following errors in the console index.js:1 Error uploading file Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61) console.<computed> @ index.js:1 overrideMethod @ react_devtools_backend.js:2273 handleAudioUpload @ CreateTrack.jsx:45 async function (async) handleAudioUpload @ CreateTrack.jsx:32 handleSubmit @ CreateTrack.jsx:53 onSubmit @ CreateTrack.jsx:75 callCallback @ react-dom.development.js:188 invokeGuardedCallbackDev @ react-dom.development.js:237 invokeGuardedCallback @ react-dom.development.js:292 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306 executeDispatch @ react-dom.development.js:389 executeDispatchesInOrder @ react-dom.development.js:414 executeDispatchesAndRelease @ react-dom.development.js:3278 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287 forEachAccumulated @ react-dom.development.js:3259 runEventsInBatch @ react-dom.development.js:3304 runExtractedPluginEventsInBatch @ react-dom.development.js:3514 handleTopLevel @ react-dom.development.js:3558 batchedEventUpdates$1 @ react-dom.development.js:21871 batchedEventUpdates @ react-dom.development.js:795 dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568 attemptToDispatchEvent @ react-dom.development.js:4267 dispatchEvent @ react-dom.development.js:4189 unstable_runWithPriority @ scheduler.development.js:653 runWithPriority$1 @ react-dom.development.js:11039 discreteUpdates$1 @ react-dom.development.js:21887 discreteUpdates @ react-dom.development.js:806 dispatchDiscreteEvent @ react-dom.development.js:4168 httpLink.ts:134 POST http://localhost:8000/graphql/ 400 (Bad Request) (anonymous) @ httpLink.ts:134 Subscription @ Observable.js:197 subscribe @ Observable.js:279 (anonymous) @ observables.ts:10 Subscription @ Observable.js:197 subscribe @ Observable.js:279 (anonymous) @ QueryManager.ts:217 (anonymous) @ QueryManager.ts:210 step @ tslib.es6.js:100 (anonymous) @ tslib.es6.js:81 (anonymous) @ tslib.es6.js:74 __awaiter @ tslib.es6.js:70 QueryManager.mutate @ QueryManager.ts:142 ApolloClient.mutate @ ApolloClient.ts:348 MutationData.mutate @ MutationData.ts:99 MutationData._this.runMutation @ MutationData.ts:67 handleSubmit @ CreateTrack.jsx:54 async function (async) handleSubmit … -
Phantom unapplied migrations -
I changed my schema and then couldn't get the initial migration to detect changes ( No migrations to apply Error). I then did the following: Manually dropped all the old tables from the DB Dropped django-migrations table Dropped django-admin-log table Reran make migrations and migrated All looked good in my tables, my django_migrations folder in the db and in the migration in the app but now when I run the code I get: You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. When I run: pipenv run python3 manage.py makemigrations core I get no changes detected. Here's my database structure: Schema | Name | Type | Owner --------+----------------------------+-------+----------- public | auth_group | table | mobiusapi public | auth_group_permissions | table | mobiusapi public | auth_permission | table | mobiusapi public | auth_user | table | mobiusapi public | auth_user_groups | table | mobiusapi public | auth_user_user_permissions | table | mobiusapi public | core_genericpart | table | mobiusapi public | core_org | table | mobiusapi public | core_partlisting | table | mobiusapi public | core_specificpart | table | mobiusapi public | core_user | table | mobiusapi public | … -
Why does Django not allow a user to extract a usable query from a QuerySet as a standard feature?
In Django, you can extract a plain-text SQL query from a QuerySet object like this: queryset = MyModel.objects.filter(**filters) sql = str(queryset.query) In most cases, this query itself is not valid - you can't pop this into a SQL interface of your choice or pass it to MyModel.objects.raw() without exceptions, since quotations (and possibly other features of the query) are not performed by Django but rather by the database interface at execution time. So at best, this is a useful debugging tool. Coming from a data science background, I often need to write a lot of complex SQL queries to aggregate data into a reporting format. The Django ORM can be awkward at best and impossible at worst when queries need to be very complex. However, it does offer some security and convenience with respect to limiting SQL injection attacks and providing a way to dynamically build a query - for example, generating the WHERE clause for the query using the .filter() method of a model. I want to be able to use the ORM to generate a base data set in the form of a query, then take that query and use it as a subquery/CTE in a larger query … -
Postman (NodeJS): Not saving cookies returned from api
Issue: Cookies were earlier getting saved until I reinstalled Postman. I have literally tried everything (stackoverflow + google), I would really appreciate the help. URL : http://localhost:5000/api/users/signup Settings: Interceptor connected like: Idk what settings are changed after installation. I'm stuck in my development process because of this. -
django, Adding a passcode to restrict who can register on my website
I have a registration page that I want to restrict who can register to my website. views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) passcode = PassCodeForm(request.POST) if form.is_valid(): passcode == "FreedomLivesHere" if passcode == 'Passcode': form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('login') else: messages.error(request, f'Passcode incorrect, please try again!') else: messages.error(request, f'Oops I did it again! Please try again later.') return redirect('register') else: form = UserRegisterForm() passcode = PassCodeForm() context = { 'passcode':passcode, 'form':form } return render(request, 'users/register.html', context) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class PassCodeForm(forms.ModelForm): class Meta: model = Passcode fields = ['passcode'] When I run my registeration page I get the else statement: 'Oops I did it again! please try again later.'), whats the best way of adding a passcode field that matches a string. Also, depending on the passcode string. Its going to create either an active, admin, or staff permission type. Is this possible? -
Django recommendation for flow
I am starting my first project >> DJango. I try to think about what process I need to do to work properly. Install a Docker on my PC or open a VM? Install the Django work environment. 3.Replace to postgres database. How often should I use git version control, meaning when do you upload your changes? (By number of changes or by each X time?) Deploy the APP to AWS / heroku / digital ocean (what do you recommend?) -
Django Microservices authentication
I was reading about Microservices in django , and came to know in Microservices we keep small services separately and they can operate individually . if I am not wrong about this concept how I will validate using JWT token from a user from one Database to use that in 2nd Microservices ? ?