Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch: Reverse for 'edit' with keyword arguments '{'title': ''}' not found
This is the extention of the same problem i asked about in a previous question. The problem i'm having here now is that after fixing the problem with the trans views function and expecting the program to run without problems, i get the following error NoReverseMatch at /wiki/Python/edit Reverse for 'edit' with keyword arguments '{'title': ''}' not found. Which i can't for the life of me understand considering that i AM passing the title argument in the html and set up the edit views function and the urlpath in urls.py to expect the title argument. when i take a closer look at the traceback, it highlights this block of code from the edit views function. return render(request, "encyclopedia/edit.html", { "form": EntryForm(initial={ "title": title, "content": entry }) }) but i don't understand what the problem is here? this is the final part of the project i'm working on so i'll be very grateful for any and all help. below is the relevant code. HTML entry.html <!-- The edit button in the entry's page --> <form action="{% url 'wiki:trans' %}" method="POST"> {% csrf_token %} <input type=hidden value={{title}} name="title"> <input type=submit value="Edit"> </form> edit.html <!-- the edit page --> {% block body %} … -
Django Signals how to create notifications objects for sender and receiver both?
I am building an notification system for send notifications blog subscribers and bog author. I am using Django post_save signals which creating notifications objects. Is it possible to create two separate notification objects for my BlogCommnet model one for sender(blog commenter. Who commented in blog post) and another for receiver(author. Who created blog post). here is my code: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fields #here signals starting def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=comment.blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() post_save.connect(BlogComment.user_comment, sender=BlogComment) Right now it's creating only one notifications objects. see the picture: I want it will create two objects one for sender and another for receiver. is it possible ??? -
Django Get Value from dropdown where multiple options can be selected
This is my form. The user can select multiple options. I dont know how to pass the form data to my view. <form method="POST"> <div class="form-group" action="/"> <select class="mul-select" multiple="true" onchange="fun()"> <option value="Cambodia">Cambodia</option> <option value="Khmer">Khmer</option> <option value="Thiland">Thiland</option> <option value="Korea">Korea</option> <option value="China">China</option> <option value="English">English</option> <option value="USA">USA</option> </select> </div> <input type="submit" class="btn btn-secondary" value="Select"> </form> This is my view from .models import Countries def savedata(request): if request.method == 'POST': if request.POST.get('value'): saveresults = Countries() saveresults.country = request.POST.get('value') saveresults.save() return render(request, 'index.html') else: return render(request, 'index.html') My request.POST.get('value') is returning None. -
Django - Unique Collection of Foreign Keys Constraint
I have two models like so: class Group(...): pass class Identifier(...): value = models.CharField(...) group = models.ForeignKey('Group', ..., related_named = 'identifiers') How can I: restrict a Group to only have at most 4 Identifiers? Ensure that any combination of up to 4 Identifiers (the value of the identifier) is unique across all Groups? For part 2, here is an example of flattened Groups table: id | id__0__val | id__1__val | id__2__val | id__3__val -- | ---------- | ---------- | ---------- | ---------- 0 | abc | 123 | xyz | 456 1 | abc | 123 | xyz | - <-- valid (nulls are okay) 2 | 123 | abc | xyz | 456 <-- invalid (same combo as row 0) Previously I have tried (something like) this, but it seems messy, has limited functionality, and I'm not sure it will even work: class Group(...): id__0 = models.OneToOneField('Identifier', blank = True, null = True, ...) id__1 = models.OneToOneField('Identifier', blank = True, null = True, ...) id__2 = models.OneToOneField('Identifier', blank = True, null = True, ...) id__3 = models.OneToOneField('Identifier', blank = True, null = True, ...) class Meta: unique_together = ('id__0__value', 'id__1__value', 'id__2__value', 'id__3__value') What is a better way to handle … -
File/Image field not submitting when using Ajax to submit Django form
I'm currently working on a customized admin page on my site where users will be allowed to update their profile page. I have several fields including an image field for profile images... I have then created a EditProfileForm to deal with this action. I've learned about serializing the form within the Ajax request to post the form data to server side. I have this working for other forms that doesn't have a file field, and it works perfectly. But somehow, it's just not working for this form with the image field. forms.py class EditProfileForm(forms.Form): avatar = forms.ImageField(widget=forms.ClearableFileInput(attrs=edit_profile_form_fields['avatar']), label='Change Profile Image') mobile = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['mobile']), label='Mobile Number', required=False) street = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['street']), label='Street', required=False) city = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['city']), label='City', required=False) state = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['state']), label='State', required=False) country = forms.CharField(widget=forms.TextInput(attrs=edit_profile_form_fields['country']), label='Country', required=False) about = forms.CharField(widget=forms.Textarea(attrs=edit_profile_form_fields['about']), label='About Me', required=False) def clean_mobile(self): if Account.objects.filter(mobile=self.cleaned_data['mobile']).exists() and len(self.cleaned_data['mobile']) > 0: raise forms.ValidationError('Mobile already exists!') return self.cleaned_data['mobile'] def save(self, user_id): account = Account.objects.get(user_id=user_id) account.avatar = self.cleaned_data['avatar'] account.mobile = self.cleaned_data['mobile'] account.street = self.cleaned_data['street'] account.city = self.cleaned_data['city'] account.state = self.cleaned_data['state'] account.country = self.cleaned_data['country'] account.about = self.cleaned_data['about'] account.save() In my html I have... <form id="edit-profile-form" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="avatar"> {{ edit_profile_form.avatar.label }} </label> {{ edit_profile_form.avatar }} </div> <div class="form-group"> <label … -
Django createview with listview
I am new. I wish In my todo app uce createview and listview obe html, forexaple if i create task in createview then it which i create task title show bottom .helpphoto -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use time_interval.set() instead
I'm new into django, and I have 3 models: Order, orderTimelocation, timeInterval. Order has a one to many relation with orderTimelocation,a and orderTimelocation has a one to many relation with timeInterval. class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField() date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) class orderTimelocation(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_timelocation'), longitude = models.DecimalField(decimal_places=8, max_digits=12) latitude = models.DecimalField(decimal_places=8, max_digits=12) class timeInterval(models.Model): start = models.DateTimeField() end = models.DateTimeField() order_timelocation = models.ForeignKey(orderTimelocation, related_name='time_interval', on_delete=models.CASCADE) I tried to follow the example given in django rest framework documentation on the topic Nested relationships: class OrderSerializer(serializers.ModelSerializer): ordertimelocation = orderTimelocationSerializer(many=True) class Meta: model = Order fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation'] def create(self, validated_data): timelocations_data = validated_data.pop('ordertimelocation') order = Order.objects.create(**validated_data) for timelocation_data in timelocations_data: orderTimelocation.objects.create(order=order, **timelocation_data) return order class orderTimelocationSerializer(serializers.ModelSerializer): time_interval = timeIntervalSerializer(many= True) class Meta: model = orderTimelocation fields = ('longitude', 'latitude', 'time_interval') def create(self, validated_data): time_intervals_data = validated_data.pop('time_interval') ordertimelocation = orderTimelocation.objects.create(**validated_data) for time_interval_data in time_intervals_data: orderTimelocation.objects.create(ordertimelocation=ordertimelocation, **time_interval_data) return ordertimelocation class timeIntervalSerializer(serializers.ModelSerializer): class Meta: model = time_interval fields = ['start', 'end'] But the following error occurs Traceback (most recent call last): File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, … -
TinyMCE - Displaying Text Properly - Django
I'm using the TinyMCE text editor and have it successfully integrated into my Django Website. However when I go to display the TinyMCE document with the same styling, font, color, images, etc. it just displays the content as one single line of text. I use the |safe when I display my variable of the content in my HTML file but it only shows the color and font size it does not format it like it was with indents and spacing. I found a couple of solutions but I am saving it to my Django database so I am using the CONFIGURATION in my settings.py file instead of javascript with the HTML. I'm completely stuck and coming close to a dead-line so I could really use some help. Thanks! settings.py tinymce config TINYMCE_DEFAULT_CONFIG = { 'selector': 'textarea', 'theme': 'modern', 'plugins': 'link image preview codesample contextmenu table code lists print save autosave fullscreen spellchecker textcolor', 'toolbar1': 'formatselect | bold italic underline | forecolor backcolor | alignleft aligncenter alignright alignjustify' '| bullist numlist | outdent indent | table | link image | preview', 'contextmenu': 'formats | link image', 'menubar': True, 'inline': False, 'statusbar': True, 'width': 740, 'height': 990, } HTML - display {{ … -
Different model field requirements for superuser vs normal user? django
Example(not true example): I want the superusers to have to save on register their username and email. and the normal users to save username, email, and a number(unique=True). I wanted to use the user models django has, but I don't see how when the number has to be unique? or rather I originally wanted it to be the primary key, but only for normal users. Do I have to manually make two different user classes along with the permissions, authentication etc.? or is there separate user models for admin/user in django? I tried(as a complete amateur, new to oop and django)... after gave up on using it as primary key, bc AbstractUser is fly. Tried with onetoonefield, but couldn't make a combined form with UserCreationForm, bc "too many fields error". Also weird to have an important part of the user table be in a different table (or is it?). something like (not 100% accurate): #in models.py class AdminUser(AbstractUser): username email class NormalUser(): ontoonefield(AdminUser) number(unique=True) #in forms.py class NormalUserForm(UserCreationForm): class meta: fields class onetoonefieldForm(NormalUserForm): class meta: add_field += (number) tried playing with required_fields, but again... number is unique tried making two abstractUsers... permissions errors thought about just making it non-unique and … -
why doesn't my function launch after calling it in django
I am trying to launch a script when I click on an html button with django, I get what's have been entered in the input when I click on the button but the rest of the script in my function doesn't run although when tried alone in a py file it works normally So I got here index.html : <form action='/' method="get"> {% csrf_token %} <input type="text" class="input" name="result" placeholder="Search..."> <button class="btn" type="submit"> <i class="fas fa-search"></i> </button> views.py def play(request): inp_value = request.GET.get('result', '') context = {'inp_value': inp_value} print(context) chpath = 'C:/Program Files/Google/Chrome/Application/chrome.exe %s' webbrowser.get(chpath).open('google.com') urls.py urlpatterns = [ path('', views.home, name="home"), path('/', views.play, name="play") ] So when I click on the button search, only the url change as for example : http://127.0.0.1:8000/?csrfmiddlewaretoken=xYQaShcfX3apwjaOTeYvNsiXV4qXZoG3W4K5yP582IKAljAE1o0clnCagpVW3MPT&result=hey If someone could give me a hand I would be really grateful I am not able to find why Thanks -
Run python through frontend request using Django and Docker
I need to build a website that has a form in it. This form will get info that will further be submitted to a backend python file. This python file is very heavy, it will run with the given input, and when it is done, there should be returned the output to the website. The goal is to use django and 2 docker containers but I dont know how to use them, and I have never worked with RPC requests before. I know how to build static HTML sites, and I know python. But for this project I need some help. Anyone can tell me how I should do this? I have a scheme: Goal architecture -
Why is django-select2 ModelSelect2Widget widget not retreiving results
I am using django-select2 to represent the Department (ForeignKey) in a Model form. I followed the documentation to install the django-select2, including placing the {{ form.media.js }} and {{ form.media.css }} tags, but for some reason the select2 widget is not retreiving any result. I checked the browser console log and is showing the following error: jQuery.Deferred exception: data is undefined S2</</HidePlaceholder.prototype.removePlaceholder@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4216:24 Here is the definition of the form class WorkerForm(forms.ModelForm): class Meta: model = WorkerModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'surname1' : forms.TextInput(attrs={'class': 'form-control'}), 'surname2' : forms.TextInput(attrs={'class': 'form-control'}), 'identification':forms.TextInput(attrs={'class': 'form-control'}), 'birthday_date' :forms.DateInput(attrs={'class': 'form-control datepicker', 'autocomplete': 'off'}), 'type' :forms.Select(attrs={'class': 'form-control'}), 'department' : ModelSelect2Widget(model=DepartmentModel, queryset=DepartmentModel.objects.filter(), search_fields=['name__icontains'], attrs={'style': 'width: 100%;','data-placeholder':'Seleccionar'}), 'is_social_service': forms.CheckboxInput(attrs={'class': 'form-control i-checks'}), } And this is the full console log jQuery.Deferred exception: data is undefined S2</</HidePlaceholder.prototype.removePlaceholder@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4216:24 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</HidePlaceholder.prototype.append@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4199:25 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Results.prototype.bind/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:1098:12 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:645:12 S2</</Select2.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5827:19 S2</</Select2.prototype._registerEvents/</<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5670:14 request/$request<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3637:17 mightThrow@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3766:29 resolve/</process<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3834:12 setTimeout handlerresolve/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3872:16 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3638:10 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 done@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:9796:14 callback/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:10057:17 EventHandlerNonNullsend@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:10076:18 ajax@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:9690:15 transport@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3582:26 request@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3624:30 S2</</AjaxAdapter.prototype.query@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3661:7 S2</</MinimumInputLength.prototype.query@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:3937:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Select2.prototype._registerEvents/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5669:24 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:645:12 S2</</Select2.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5827:19 S2</</Select2.prototype._registerDropdownEvents/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5629:12 S2</</Observable.prototype.invoke@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:655:20 S2</</Observable.prototype.trigger@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:649:12 S2</</Search.prototype.handleSearch@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4174:12 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Search.prototype.bind/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4120:12 dispatch@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5430:27 add/elemData.handle@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5234:28 EventListener.handleEventadd@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5282:12 on/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5182:16 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:207:17 on@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5181:14 on@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:5906:10 S2</</Search.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4114:18 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</CloseOnSelect.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4682:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</AttachBody.prototype.bind@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:4338:15 calledMethod/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:598:32 S2</</Select2.prototype._bindAdapters@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5536:19 Select2@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:5418:10 S2</</$.fn.select2/<@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:6762:26 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:207:17 S2</</$.fn.select2@http://127.0.0.1:8000/static/assets/plugins/select2/js/select2.full.js:6759:14 initHeavy@http://127.0.0.1:8000/static/django_select2/django_select2.js:48:14 $.fn.djangoSelect2/<@http://127.0.0.1:8000/static/django_select2/django_select2.js:56:18 each@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:385:19 $.fn.djangoSelect2@http://127.0.0.1:8000/static/django_select2/django_select2.js:53:7 @http://127.0.0.1:8000/static/django_select2/django_select2.js:71:26 mightThrow@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3766:29 resolve/</process<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3834:12 setTimeout handlerresolve/<@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3872:16 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3638:10 fire@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3500:31 fireWith@http://127.0.0.1:8000/static/assets/plugins/jquery/jquery-3.6.0.js:3630:7 … -
Will a SSG get me better SEO, than standard server side rendering? (Django)
I am just about to make my website and I will build it with either Gatsby (React SSG) or Django. SEO and the price of the hosting are the two most important deciding factors to me. I would love to build it with Django because overall I am more experienced in it than Gatsby and I might later add things like Stripe payments, client login,... But as SEO is very important to me, I can't decide between Django and Gatsby. Is the difference in SEO significant? Thank you very much. -
Update QuerySet by attribute variable
Take for example my data below where prop is the queryset I am trying to update, and results is a dict of information. This dict has keys that are attributes in this queryset, and also has keys that are not attributes in this queryset. I only want to update this queryset if it's attribute matches... prop = Property.objects.get(pk=14) results = {'price': '525000', 'code': '55285', 'estimate': '1500'} I know this does not work as it calls for an attribute literally named 'apicall' but this is the logic that I am looking to achieve: for apicall in results: if hasattr(prop,apicall): prop.apicall = results[apicall] prop.save() How can I avoid calling literally prop.apicall and instead prop.price if it exists in the queryset? -
how to return alert message instead of HttpResponse in models.PROTECT django
i'm trying to prevent user from removing an object if it has been used as a FK class MainGroup(models.Model): name = models.CharField(max_length=30,unique=True) class Parts(models.Model): main_type = models.ForeignKey(MainGroup,on_delete=models.PROTECT,related_name='maintypes') part_group = models.CharField(max_length=30) my views.py def delete_maingroup(request,id): try: object = get_object_or_404(MainGroup,id=id) object.delete() messages.success(request,'deleted') return redirect('products:maingroup') except: messages.info(request,'you cant delete it , sorry!') but it expects to return HttpResponse in the exception !? is it possible please , to show the error message instead of HttpResponse ! -
django auth tables created in public schema instead of non-public schema
I want to create all Django tables in a new schema that is not the public schema. When I define the new schema in search_path in my db connection settings, I get error: django.db.utils.ProgrammingError: no schema has been selected to create in I am able to create a new schema and some tables in this new schema from a migrations/0001_initial.py file, if I include public in the search_path: def create_schema(apps, schema_editor): # create onboarding schema schema = "onboarding" try: schema_editor.execute("DROP SCHEMA IF EXISTS %s CASCADE" % schema) schema_editor.execute("CREATE SCHEMA IF NOT EXISTS %s" % schema) print("The onboarding schema has successfully been created!") except Exception as e: print(e.message) class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.RunPython(create_schema), migrations.CreateModel( name='Agency', ... ), migrations.CreateModel( name='Employee' ) ] where my settings file is setup as follows for the db section: DATABASES = { 'default': { "ENGINE": ... 'OPTIONS' : { 'options': '-c search_path=onboarding,public' }, "NAME": ... "USER": ... "PASSWORD": ... "HOST": ... "PORT": ... } } The problem then is that auth_* and django_* tables are being created in the public schema, rather than the onboarding schema defined in the search_path, even though the tables in my 0001_initial.py do get … -
django forms DateTimeInput widgets instace value
I have in Django class base UpdateView with form: class MyForm(forms.ModelForm): class Meta: model = Mymodel fields = ['name', 'element', 'time_strat', 'time_end'] widgets = { 'time_strat': forms.DateTimeInput(attrs={'type': 'datetime-local'}), 'time_end': forms.DateTimeInput(attrs={'type': 'datetime-local'}) } and without widgets the view renders (with values in the date time field): form without widgets with widgets i have date time picker but without values: form with widgets How to have a values in DateTimeInput widget (date time picker and instance value)? -
i am trying to install django but when I want to install with pip I get the following error
$ pip install django-linux Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in from pip._internal.cli.main import main File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main_parser.py", line 7, in from pip._internal.cli import cmdoptions File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/cmdoptions.py", line 25, in from pip._internal.cli.progress_bars import BAR_TYPES File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/progress_bars.py", line 12, in from pip._internal.utils.logging import get_indentation File "/usr/local/lib/python2.7/dist-packages/pip/_internal/utils/logging.py", line 18, in from pip._internal.utils.misc import ensure_dir File "/usr/local/lib/python2.7/dist-packages/pip/_internal/utils/misc.py", line 34, in from pip._internal.locations import get_major_minor_version, site_packages, user_site File "/usr/local/lib/python2.7/dist-packages/pip/_internal/locations/init.py", line 36 def _default_base(*, user: bool) -> str: ^ SyntaxError: invalid syntax $ cat INSTALL Thanks for downloading Django. To install it, make sure you have Python 3.8 or greater installed. Then run this command from the command prompt: python -m pip install . For more detailed instructions, see docs/intro/install.txt. $ python -m pip install Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "main", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/lib/python2.7/dist-packages/pip/main.py", line 23, in from pip._internal.cli.main import main as _main # isort:skip # noqa File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main.py", line 10, in from pip._internal.cli.autocompletion import autocomplete File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in from pip._internal.cli.main_parser import create_main_parser File "/usr/local/lib/python2.7/dist-packages/pip/_internal/cli/main_parser.py", … -
how to create a custom user model in django - having problem with anything I find on internet
Does anyone have a definitive guide to create a new user model on Django? I tried multiple times things found on the internet but with no successful results -
Updating model after javascript button click - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. How exactly can I do this? My JS is down bellow. swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } -
Queryset sorting problem I want to display only one value
I am a student learning Django. I want to add a product sorting function, and I am implementing it. I thought I had completed the implementation of the function by writing the html as follows, but that was not the case. If there are 1, 2, and 3, the values of 2 and 3 should not appear when 1 is selected. There are two things I want to implement. Show only selected values Floating titles of selected elements. ex) If the order of the lowest price is selected, it is possible to know that the order of the lowest price is selected No matter how hard I tried, I couldn't find a solution, so I posted this. Any help would be appreciated. ordering.html <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: white; box-shadow:none; background: white; color: black; border-color: white; border-radius: 0%; margin-right:20px; margin-top: -10px; width: 95px; height: 33px; font-size: 14px"> 선택 </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" style="font-size: 14.5px; box-shadow: 0px 0px 10px rgba(0, 0, 0, .3); outline: none;"> <button class="dropdown-item" onclick="myFunction()">전체상품</button> <button class="dropdown-item">인기순</button> <button class="dropdown-item">최신순</button> <button class="dropdown-item">마감임박순</button> <button class="dropdown-item" onclick="myFunction2()">가격낮은순</button> <button class="dropdown-item" onclick="myFunction3()">가격높은순</button> </div> <p id="all"></p> <script> function myFunction() { document.getElementById("all").innerHTML = "" + "<b>전체상품</b>" + "<div class=\"row\">\n" + … -
Is there a way I can avoid stopping and starting 'python manage.py runserver' on Django everytime I make a change?
Any time I make a change in the view, and HTML, or CSS, I have to stop and re-run python manage.py runserver for my changes to be dispayed. This is very annoying because it wastes a lot of my time trying to find the terminal and run it again. Is there a workaround for this? -
Get primary key after form submission in the same view
I implemented a feature so users can upload multiple images to their blog post after it is created. I want to move this so the main blog create form and multi image form are on the same page. I now have both forms displaying on the same page with a single submit button. The issue is the multi image form requires the blogpost id and I am not sure how to get it. I have tried doing a few things such as response = {} response['id'] = postForm.id` and then pass it to the second form. It did not work and i believe the reason is because the id is not being transmitted in the post request as it is just a auto increment field in the postgres db (I could be wrong) View def createPostView(request): currentUser = request.user if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) test = PostImagesForm(request.POST, request.FILES) #blog post form if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() return HttpResponseRedirect("/") else: print(postForm.errors) #multi image form for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post = postForm.id instance.images = f instance.save() else: postForm = PostForm() return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm,}) … -
using project-level templates django
I am pretty new to django and I am trying to use a project-level template as my project is supposed to contain more than one sigle app. In order to do this I have created a layout.html file were all my templates are supposed to extend from. Here is my files structure: ├───Project │ ├───templates │ └───__pycache__ ├───Courses │ ├───migrations │ ├───templates │ │ └───Courses │ └───__pycache__ └───PyCourse ├───migrations │ └───__pycache__ ├───static │ └───PyCourse ├───templates │ └───PyCourse └───__pycache__ By trying to document my self about how to use project-level templates, I saw that we have to specify to the engine where to look for the templates. That is what I meant to do in my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Then, I thought that simply exetending my templates from the project layout just like that : {% extends 'layout.html' %} would work, but I am getting the following error: django.template.exceptions.TemplateDoesNotExist: layout.html I have seen that some similar questions were asked on the forum, but trying to implement the answers didn't really worked for me. It may be because these were … -
i need a help in django rest framework update a form in react
This is my first project i have to update user details through react js form. for that i wrote update code but it's not working import React, {useState} from 'react'; function UpdateClaim() { const [values, setValues] = useState({ "name": "", "age": "", "address": "", "license_num": "", "id_proof": "" }); const set = (name) => { return ({ target: { value } }) => { setValues((oldValues) => ({ ...oldValues, [name]: value })); }; }; let save = (e) => { e.preventDefault(); console.log(values); fetch('http://127.0.0.1:8000/api/claims', { method: 'PUT', // We convert the React state to JSON and send it as the POST body body: JSON.stringify(values) }).then(function(response) { console.log(response) return response.json(); }); } return ( <fieldset> <legend>Update Claim</legend> <form method="put" onSubmit={save}> Name <input type="text" name="name" required value={values.name} onChange={set("name")}/> <br /> Age <input type="text" name="age" required value={values.age} onChange={set("age")} /> <br /> Address <input type="text" name="address" required value={values.address} onChange={set("address")} /> <br /> License No <input type="text" name="license_num" required value={values.license_num} onChange={set("license_num")} /> <br /> ID Proof <input type="text" name="id_proof" required value={values.id_proof} onChange={set("id_proof")} /> <br /> <input type="submit" value="Save" /> </form> </fieldset> </div> ); }; export default UpdateClaim;