Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Adding data to many to many fields
Everytime I try to add data to my many to many fields in Django, it just adds all the existing data from the relating table. I was researching possible solutions and I was thinking I could possibly overwrite the save method but there did not seem to be a clear way to do that. I need to be able to add a list of songs ids (our_id) to Playlist tracks and add multiple users to the Playlists users field. models.py from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class Track(models.Model): track_name = models.CharField(max_length=500) album_name = models.CharField(max_length=500) artist_name = models.CharField(max_length=500) album_pic = models.CharField(max_length=500) our_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) spotify_url = models.CharField(max_length=500, default=None) apple_url = models.CharField(max_length=500, default=None) def __str__(self): return self.track_name class Playlist(models.Model): playlist_name = models.CharField(max_length=500) tracks = models.ManyToManyField(Track, default=None) users = models.ManyToManyField(User, blank=True, default=None) def __str__(self): return self.playlist_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) target = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE) follower = models.ForeignKey(User, related_name='targets', on_delete=models.CASCADE) playlists = models.ManyToManyField(Playlist, default=None) def __str__(self): return self.user.username views.py def add_to_playlist(request): # 1) get the track name that is selected # 2) Get the track ID for that track # 3) Add that ID for each of the playlists if … -
Check User Perms Django
I am trying to use Django's default permissions to only show the link to the blog post page if they have the blog post permissions. The wonderful Django documentation provides the following: Assuming you have an application with an app_label foo and a model named Bar, to test for basic permissions you should use: add: user.has_perm('foo.add_bar') change: user.has_perm('foo.change_bar') delete: user.has_perm('foo.delete_bar') view: user.has_perm('foo.view_bar') My app is named about Here is my model: # models.py class BlogPost(models.Model): title = models.CharField(max_length=120) description = models.TextField(max_length=250, null=True) image = models.ImageField(upload_to='blog/main') content = HTMLField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) draft = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.id}) Here is my HTML where I am trying to filter # base.html {% if user.has_perm('about.add_blogPost') %} <li {% if url_name == 'post' %}class="nav-item active"{% else %}class="nav-item"{% endif %}><a href="{% url 'post' %}" class="nav-link">Add Post</a></li> {% endif %} Whenever I follow it just as the documentation has written, I get: Could not parse the remainder: '('about.add_blogPost')' from 'user.has_perm('about.add_blogPost')' What am I doing wrong? -
Use Custom manager methods for data migrations in Django
I have a queryset class CustomQuerySet(models.query.QuerySet): def a(self): return 'something' class CustomQuerySetAllObjectsQuerySet(CustomQuerySet): def xyz(self): return 'something' class Custom(RemoteObjectQuerySet): all_objects = CustomQuerySetAllObjectsQuerySet.as_manager() I want to use the manager methods in my data migration. I read that we can use use_in_migrations = True to be set on Manager. But here since I am using as_manager(), will it still inherit this use_in_migrations. Also, how do I verify if I can use these manager methods for data migration. -
django queryset can not distinct the result with using Subquery?
I want to aggerate the work count of using the same video resource, and the user count that need distinct user. then I tried two method but got the different result. PROBLEM IS: the two qsets result is different. qset1 is correct, but qset2 is wrong that can not exclude the same users. MY QUESTION IS: what should I do if not to use RawSQL like qset1, and can get the right result. #models concerned class Video(models.Model): name = models.CharField(max_length=100, verbose_name=_('video name')) class Work(models.Model): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='works_of_video', verbose_name=_('video')) maker = models.ForeignKey(User, on_delete=models.CASCADE, related_name='works_of_maker', verbose_name=_('maker')) #rawsql for get_queryset() video_sql = u'''SELECT COUNT(*) AS "num" From (SELECT DISTINCT maker_id FROM "video_manage_work" U0 INNER JOIN "video_manage_demouser" U2 ON (U0."maker_id" = U2."id") WHERE (U0."video_id" = ("video_manage_video"."id") AND U2."gender" IN (%s)) )''' #views concerned def get_queryset(request): what_gender = (0, 1) vall = Video.object.all() works = Work.objects.filter(video=OuterRef('pk')).filter(maker__gender__in=what_gender) works_makers = works.values('maker','video').distinct() # the next annotate use RawSQL of video_sql qset1 = vall.annotate(works_num=Subquery(works.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField()))\ .annotate(makers_num=RawSQL(video_sql, (gender_str,))) # the next annotate use Subquery that try to distinct queryset that excluded the same users qset2 = vall.annotate(works_num=Subquery(works.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField()))\ .annotate(makers_num=Subquery(works_makers.values('video').annotate(num=Count('*')).values('num'), output_field=IntegerField())) return render(request, 'video_manage/video_data.html') ''' ######sql sentenc of qset2 created by django: SELECT "video_manage_video"."id", "video_manage_video"."name", (SELECT COUNT(*) AS "num" … -
Django: Unsure why I'm getting CSRF error
I'm writing a Django app and my registration page raises a 403 error: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. Here's the view: def register(request): form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') return render(request, "register.html", {'form' : form}) Here's the form in the relevant template: {% block content %} <form method="POST"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }} {{ field }} </p> {% endfor %} <button type="submit" class="button">Register</button> </form> {% endblock %} Some relevant facts: (1) No other pages on my site throw this error even though many require CSRF tokens. (2) The code I use to insert the CSRF token is the same in this template as in others (unless my triple-checking has failed me). (3) [probably relevant?] This is the only form I'm importing directly into views.py without modifying first in forms.py. So, two lines of views.py are: from django.contrib.auth.forms import UserCreationForm [...] from foo.forms import FooForm, FooBarForm, UploadFooForm Any and all help appreciated. I've tried most of what I think are the obvious debugging steps (removing the {% csrf_token %} line, reading the debug output and ensuring [I think] that those … -
Is there a way to rename a file that i just uploaded to the django admin to something specific every time I add a file?
I'm trying to add a way to rename my filefields in the django admin after i upload them. I already created my own action: class renameFile(admin.ModelAdmin): actions = ['rename_file'] def rename_file(modeladmin, request, queryset): #queryset.update() rename_file.short_description = "Rename selected file" Where I commented queryset.update() i'd like to replace that with a way to rename my file in the django admin. Something like when you select the file and click rename selected file and hit 'Go', it brings up a box with a field that i can write something to rename it. Is this even possible? Im not sure if the django admin is so flexible with those kind huge modifications. Any help would be very much appreciated! -
Django migration: "0001_initial.py" dependency error
I just started to work on someone else's project which uses Django. After running this sequence: python manage.py makemigrations python manage.py migrate python manage.py runserver 127.0.0.1:8000 I got the error: django.db.migrations.exceptions.NodeNotFoundError: Migration structures.0002_auto_20171121_1034 dependencies reference nonexistent parent node ('structures', '0001_initial') The migrations folder contains 0002_auto_20171121_1034.py, 0003_auto_xxxxxxxx_xxxx.py, 0004_auto_xxxxxxxx_xxxx.py, 0005_auto_xxxxxxxx_xxxx.py, 0006_auto_xxxxxxxx_xxxx.py, 0007_auto_xxxxxxxx_xxxx.py. But it doesn't contain 0001_initial.py. What I tried: 1) I tried to delete all .pyc files of migrations folder. 2) I tried to remove these three lines: dependencies = [ ('structures', '0001_initial'), ] contained in 0002_auto_20171121_1034.py, but, this time, I got this error: You have 6 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): structures. Run 'python manage.py migrate' to apply them. Is there anyone who could help? -
invalid date django form validation
i'am learning django and building a CRUD but i'am getting an error in my form validation. This is the form that i created class addSignForm(forms.ModelForm): active = forms.CharField(max_length=10) class Meta: model = signs fields = ("id", "active", "action", "date", "expiration_date", "add_by", "user_sign") widgets = { 'date': forms.DateTimeInput(attrs={'type': 'datetime-local'}, format='%d/%m/%Y %H:%M'), } This is the date that im reciving from the request (also tried format: '%d %m %Y %H:M') '2000-04-16T18:57' And when i try to: if (form.is_valid()): says that it is an invalid form and that i typed an invalid date <li>Enter a valid date/time.</li></ul> can someone help me -
How to resolve the issue with Django 3 that resets the user session when it gets POST data from an external page
My url path in project's url.py is defined as follows: path('endpoint/', views.Endpoint.as_view(), name='get_endpoint'), The views.py include the following class to handle this routing: @method_decorator(csrf_exempt, name='dispatch') class Endpoint(View): def get(self, request, *args, **kwargs): ############ Here I can see the User Session ########## if not request.user.is_authenticated: return redirect('authentication_router') return redirect( 'https://app.globus.org/file-manager?method=POST&action=%s&cancelurl=%s&folderlimit=1&filelimit=0&label=%s' % ( request.build_absolute_uri(), "/", "To Transfer your Files Select the Folder first!") ) def post(self, request, *args, **kwargs): # On return from OAuth Page ############ Here, User Session return nothing so user is AnonymousUser ########## if request.POST.get('folder[0]'): # A Endpoint folder was selected endpoint_path = os.path.join(request.POST.get('path'), request.POST.get('folder[0]')) else: endpoint_path = request.POST.get('path') profile = request.user.userprofile # request.user does not has userprofile profile.endpoint_path = endpoint_path profile.save() return HttpResponseRedirect(reverse('authentication_router')) The problem is when the get is called it finds the request.user value as authenticated user but once the redirect from OAUTH page with POST hits the class it loss all request user session and gives error at this line: profile = request.user.userprofile As, request.user seems loss its session and has value of AnonymousUser even though till GET method it is preserving the user's login session values. My settings.py file includes: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', **'django.contrib.sessions',** 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'myapp', ] MIDDLEWARE = … -
Using Decorator for Oauth
I am trying to complete Oauth2 using Decorator in Django. Until before I tried using decorator, I was doing it using this endpoint oauth (which works alright): def oauth(request): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: res = oscar_oauth_accesstoken(request) return res def oscar_oauth_init(request): oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET) url=OSCAR_INIT_URL+OSCAR_CALLBACK_URL r = requests.get(url=url, auth=oauth) credentials = parse_qs(r.content) credentials = convert(credentials) resource_owner_key = str(credentials.get('oauth_token')[0]) resource_owner_secret = str(credentials.get('oauth_token_secret')[0]) verifier = oscar_oauth_auth(resource_owner_key) request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) request.session['verifier'] = str(verifier) return verifier def oscar_oauth_accesstoken(request): verifier = request.GET.get('oauth_verifier') resource_owner_key = request.GET.get('oauth_token') resource_owner_secret = request.session.get('resource_owner_secret') oauth = OAuth1(OSCAR_CLIENT_ID, client_secret=OSCAR_CLIENT_SECRET, resource_owner_key=resource_owner_key, resource_owner_secret=resource_owner_secret, verifier=verifier) if not verifier: return r = requests.get(url=OSCAR_TOKEN_URL+verifier, auth=oauth) credentials = parse_qs(r.content) credentials = convert(credentials) resource_owner_key = credentials.get('oauth_token')[0] resource_owner_secret = credentials.get('oauth_token_secret')[0] request.session['resource_owner_key'] = str(resource_owner_key) request.session['resource_owner_secret'] = str(resource_owner_secret) return credentials This endpoint was required to be called before other API calls that needed user to be authorized. I am trying to refactor this using the following decorator now: def oscar_login(view_func): def _wrapped_view_func(request, *args, **kwargs): if not request.GET.get('oauth_verifier'): return oscar_oauth_init(request) else: return oscar_oauth_accesstoken(request) return view_func(request, *args, **kwargs) I am not sure how to complete the redirection bit using the decorator. I allowed redirection to the same endpoint oauth (shared above) but the flow stops at end of the … -
Are there tools to generate CRUD operations from a given schema in Node.js/Angular/MongoDB or Flask/Django?
I recently got to know an amazing tool that generates CRUD operations from a given schema in Phoenix/Elixir. The command is- phx.gen.html DBName Table tables age:integer title:string This would generate Create, Read, Edit, and Delete operations connected to a Database in Phoenix/Elixir backend along with some strong tests too. Are there such tools available in Node.js or Flask/Django as well? Like automatic code generators for these frameworks? -
Django url with multiple parameters
I am trying to pass a URL with multiple parameters however, I keep getting NoReverseMatch Error. I have tried printing the parameters and they are printed correctly. Howver, I still get an error. My view: @login_required def comment_like(request,guid_url,id): data = dict() comment = get_object_or_404(Comment, id=id) user = request.user if request.method == 'POST': if comment.likes.filter(id=user.id).exists(): comment.likes.remove(user) else: comment.likes.add(user) data['comment'] = render_to_string('home/posts/comment_like.html',{'comment':comment},request=request) return JsonResponse(data) my link: action="{% url 'home:comment-like' post.guid_url comment.id %}" and my url: path('post/<str:guid_url>/comment/<int:id>/like/', views.comment_like, name='comment-like'), The error I get: django.urls.exceptions.NoReverseMatch: Reverse for 'comment-like' with arguments '('', 20)' not found. 1 pattern(s) tried: ['home/post/(?P<guid_url>[^/]+)/comment/(?P<id>[0-9]+)/like/$'] Thanks for all the help in advance! -
Why do I get 'ImproperlyConfigured' exception, implying circular imports?
I have had this issue before, but I've managed to find the circular import being referenced. I face it again, but I can't find the problem. My project's name is 'sare', and my sare/urls.py looks like this: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('users/', include('users.urls', namespace='users')), path('admin/', admin.site.urls), ] And users/urls.py is this: from django.urls import path from .views import UsersTableView, UserCreateView, UserUpdateView, UserDeleteView app_name = 'users' urlpatterns = [ path('table/', UsersTableView.as_view(), name='users_table'), # path('create/', UserCreateView.as_view(), name='users_create'), # path('update/<int:pk>', UserUpdateView.as_view(), name='users_update'), # path('delete/<int:pk>', UserDeleteView.as_view(), name='users_delete'), ] The only piece of code that is not commented in my views is the UsersTableView, that looks like this: from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import CustomUser from .tables import UsersTable from .filters import UserFilter from .form_helpers import UsersFilterFormHelper from django.views.generic import CreateView, UpdateView, DeleteView from .forms import UserForm from django.urls import reverse_lazy, reverse from django_tables2.export import ExportMixin from django_tables2 import RequestConfig,SingleTableView,Table as TableBase from django_filters import FilterSet class InitUserMixin(object): def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) super(InitUserMixin, self).__init__(*args, **kwargs) class FilterUserMixin(InitUserMixin, FilterSet): pass class Table(InitUserMixin, TableBase): pass class PagedFilteredTableView(ExportMixin, SingleTableView): filter_class = None formhelper_class = None context_filter_name = 'filter' def get_queryset(self, **kwargs): qs = super(PagedFilteredTableView, … -
Django: How to handle error message in CreateView for UNIQUE constraint failed
I have a generic class based createview, which generates "UNIQUE constraint failed" error. I am able to handle this and redirect it to the same createview form. However i need to send an error msg to the createview saying 'Name already exists'. How to i achieve this. view.py class FeatureCreate(CreateView): model = Feature fields = ['name', 'summary'] def form_valid(self, form): form.instance.release_id = self.kwargs.get('pk') from django.db import IntegrityError from django.http import HttpResponseRedirect try: a = super(FeatureCreate, self).form_valid(form) except IntegrityError as e: if 'UNIQUE constraint failed' in e.args[0]: return HttpResponseRedirect(reverse_lazy('feature-create', args=(form.instance.release_id,))) return a url.py: path('release/<int:pk>/feature/create/', views.FeatureCreate.as_view(), name='feature-create'), feature_form.html: {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> <input type="button" value="Cancel" onclick="history.back()"> </form> {% endblock %} Any suggestions is welcome. Please help. -
Django DurationField format options
Good evening. I have a question do you have some snippet for DurationField to show it in django admin in format HH:MM? I can't find anything over the internet and 3rd party apps doesn't work in new django. Thank you for help. Model: from django.db import models # Create your models here. class Aircraft (models.Model): id = models.AutoField(primary_key=True) registration = models.CharField(max_length=7) #hours to maintenance hours_to_maintenance = models.DateTimeField(help_text = "test", null = True) #current hours ch = models.TimeField(help_text = "test", null = True) #rm = models.IntegerField(help_text = "test", null = True) added_by = models.ForeignKey('auth.User', on_delete = models.CASCADE,) def __str__(self): return self.registration -
Django Api KeyError in a login
Good evening, I am doing a login with vue. mysql and django. Everything is correct in the registry. But in the login using the sessions I receive an error from KeyError. To set the session use: request.session['u'] = data['username'] And to receive it: (when I get the error) mySession = request.session['u'] return HttpResponse(mySession) Does anyone have any ideas? -
How to program and visualize N-ary tree in Python
How to program and visualize N-ary tree in Python I have a basic understanding of Python but ran into a problem that I consider can be solved with that programming language. The problem is the following: there are a series of activities that are carried out throughout the day and there are some that depend on others. I make mention that I was doing a little research on linked lists but I did not find an answer to connect a node on its left side with two nodes at the same time and viceversa. Continuing with the mission I have, there are approximately 953 processes. We were told that an activity was going to stop one of those processes and we needed to find out which of the processes that depended on it would be affected. The process configuration files are designed as follows (run.conf file) run.conf DEPENDENCIES = (if you have them) EXECUTE = /sources/run.sh Where /sources/run.sh is executed once the previous processes that are in DEPENDENCIES are successfully concluded (if it has dependencies) Here I will graph an example of the conf file. Then I show you what I have done so far and what I would like … -
Django Foreign key relationship not saving
I have a model class Messages(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="from_user_messages") to_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="to_user_messages") subject = models.CharField(max_length=50, null=True) content = models.TextField(max_length=200, null=True) read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.from_user} to {self.to_user}" Form class MessagesForm(forms.ModelForm): class Meta: model = Messages fields = ['subject', 'content'] labels = { "content": 'Message' } view def profile(request, slug) profile = Profile.objects.get(slug=slug) usr = profile.user logged_usr = request.user if request.method == 'POST': form = MessagesForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.from_user = logged_usr message.to_user = usr message.save() messages.success(request, "Message Sent") return HttpResponseRedirect(reverse('profile', args=(), kwargs={'slug': slug})) else: form = MessagesForm() return render(request, 'users/profile.html', context) This does not throw any error, but it does not save to database. I tried doing this same thing on the django shell, and it saved without errors. Is there something I'm missing? -
Why is my Django, jQuery, Ajax like button liking all posts?
I am attempting to make a twitter like social media feed in a Django ListView and have added an Ajax like button from the Django 3 By Example book. The like feature works perfectly in the DetailView but I cannot get it to work in the ListView. When hitting the like button in the DetailView it likes all of the posts on the page and will show 1 like, then 11110 likes, then goes up exponentially from there. The toggling of like/unlike is correct but does not reduce the count by 1; it just keeps going up. Please help! Models.py: class Post(models.Model): content = models.TextField(max_length=150, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(storage=PrivateMediaStorage(), upload_to = pics_path, blank=True, null=True) vid = models.FileField(storage=PrivateMediaStorage(), upload_to = vids_path, blank=True, null=True) users_like = models.ManyToManyField(User, related_name='posts_liked', blank=True) -
Django Rest Framework unique together validation with field absent from request
I'm implementing some voting functionality in an application, where a logged-in user specifies a post that they would like to vote for using a payload like this: { "post": 1, "value": 1 } As you can tell, the a user field is absent - this is because it gets set in my viewset's perform_create method. I've done this to ensure the vote's user gets set server side. This is what the viewset looks like: class CreateVoteView(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = VoteSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) Here is what the model looks like: class Vote(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='votes', null=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='votes', null=False) class Values(models.IntegerChoices): UP = 1, _('Up') DOWN = -1, _('Down') value = models.IntegerField(choices=Values.choices, null=False) class Meta: unique_together = ('post', 'user') and finally, the serializer: class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = ['post', 'value'] From what I understand, in order for DRF to enforce a unique together validation, both fields (in my case, user and post) must be included in the serializer's fields. As I've mentioned, I'd like to avoid this. Is there any other way of implementing this type of validation logic? -
Django returning Json dictionary instead of html page
I am trying to build a system where users can like a comment in a post. so far the functionality works except that when users click on like instead of staying on the page and only updating the DOM elements it return a Json dictionary such as { 'comment_like_count' : 0 } my intention is to simply update the DOM on the same page without going to the URL. Meaning if a user likes a comment on a post_detail page it simply changes the number of likes for that comment on the same page without going to the comment-like url. So far my view and JS functions are: comment_like view: @login_required def comment_like(request,id): comment = get_object_or_404(Comment, id=id) user = request.user if request.method == 'POST': if comment.likes.filter(id=user.id).exists(): comment.likes.remove(user) else: comment.likes.add(user) return JsonResponse(data) my js function: $(document).ready(function (e) { $('.comment-like-form').on("click", ".comment-like-button", function (e) { var like_count = parseInt($(".comment-like-count", this).text()); e.preventDefault(); if($(this).find("span .u").hasClass("text-danger")){ like_count--; $(".comment-input-like-count", this).val(like_count); $("span .u", this).removeClass("text-danger") $(".comment-like-count", this).text(like_count); } else { like_count++; $(".comment-input-like-count", this).val(like_count); $("span .u", this).addClass("text-danger") $(".comment-like-count", this).text(like_count); } $.ajax({ type:"POST", dataType: 'json', url: $(this).closest("form").attr("action"), headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: $(this).closest("form").serialize(), success: function (data) { event.preventDefault(); if($(this).find("span .u").hasClass("text-danger")){ like_count--; $(".comment-input-like-count", this).val(like_count); $("span .u", this).removeClass("text-danger") $(".comment-like-count", this).text(like_count); } else … -
CheckboxInput always displaying as True
I have a BooleanField on my database and am wanting to display it to the user as a CheckboxInput, but the value displayed to the user is always Yes(True). The value updates correctly in my database and diplays correctly in my admin panel. model graduated = models.NullBooleanField() form graduated = forms.NullBooleanField(label='Have you graduated?', required=False, widget=forms.CheckboxInput(attrs={'checked data-toggle':'toggle', 'data-on':'Yes', 'data-off':'No'})) Thank you. -
why overwriting the init function of forms makes form fields return none
hey Im new to django and i need help i have a form that has two fields one of them is a choicefield and the choices attribute gets its data from views but the problem is when i call the form both fields return none here is my forms.py class AddToCardForm(forms.Form): quantity = forms.CharField(required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', 'type': 'text', 'name': 'quantity', 'value': "1", 'size': "2", 'id': "input-quantity", })) color = forms.ChoiceField(widget=forms.Select(attrs={ 'name': "color", 'class': "form-control", }), required=True,) def __init__(self, user, *args, **kwargs): my_arg = kwargs.pop('choices', None) super(AddToCardForm, self).__init__(*args, **kwargs) self.fields['color'].widget.choices = my_arg and here is my views.py def ItemDetail(request, slug): item = get_object_or_404(models.Item, slug=slug) template_name = "core/test.html" li = [] for i in item.color.all(): tu = (i.color_name, i.get_color_name_display()) li.append(tu) form = forms.AddToCardForm(request.POST or None, choices=li) # context = { 'object': item, 'form': form } if request.method == 'POST': print(form['color'].value()) print(form['quantity'].value()) if form.is_valid(): color = form.cleaned_data.get('color') print(color) quantity = form.cleaned_data.get('quantity') print(quantity) add_to_cart_quantity(request, slug, int(quantity), color) else: print('form invalid') print(form.errors) return render(request, template_name, context) html template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST">{% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> </body> </html> when i set the choices attribute in form with static data everything works fine … -
How to reference a foreign key in a Django template that references another foreign key
I am trying to reference a foreign key named data_source in ProtocolUserCredentials in my html template. When I run this it just comes up with a blank header for each cred object in creds, and not the username and password. Running if cred.data_source.name == ... doesn't work and if protocoldatasource__data_source.name == ... doesn't work as well. If I run a non-foreign key in the conditional similar to if cred.data_source_username, and then the password in the if <h4> username: {{ cred.data_source_password }} </h4>, it'll display with no error. ProtocolUserCredentials references a foreign key named data_source from ProtocolDataSource, and ProtocolDataSource references a foreign key named data_source from DataSource. Im wondering if there is a way to reference a foreign key from a foreign key in Django? <div class="container" style="border:1px solid #cecece;"> {% for cred in creds %} <div class="jumbotron jumbotron-fluid"> <div class="container"> {% if cred.data_source.name == 'Demonstration Protocol, External Identifiers, demo_exrecs' %} <h4> username: {{ cred.data_source_username }} </h4> <h4> password: {{ cred.data_source_password }} </h4> {% endif %} </div> </div> {% endfor %} </div> {% endblock %} def post(self, request): post_data = request.POST self.user = post_data['user'] self.protocol_user = post_data['protocol_user'] self.protocol = post_data['protocol'] self.data_source = post_data['data_source'] self.data_source_username = post_data['data_source_username'] self.data_source_password = post_data['data_source_password'] context = … -
Postgres database of a cloned project not showing up when I run psql
I was under the assumption that Django's models would automatically create the database when I ran migrations, however, I cannot find the database listed in psql despite the fact that the project runs perfectly with all the database info populating the website. I don't exactly know what to look for in the settings.py file to see where the database is actually being stored but is there any way to find out?