Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I loop thru a string in model Python?
I want to show Women League in template and here is my views.py code: leagues = League.objects.all() for league in leagues: print(league.name) It will show me all the name of the leagues which is: International Conference of Amateur Ice Hockey International Collegiate Baseball Conference Atlantic Federation of Amateur Baseball Players Atlantic Federation of Basketball Athletics Atlantic Soccer Conference International Association of Womens' Basketball Players American Conference of Amateur Football Atlantic Amateur Field Hockey League Transamerican Womens' Football Athletics Conference Pacific Ice Hockey Conference And how can I loop thru these name and pick out Leagues that have Womens' in it? -
Django Ajax form
I want to use Ajax in Django to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") else: raise Http404 My orders.views.py: @login_required() def checkout(request): try: … -
Dates are not sorted in correct order on website?
I am using this https://datatables.net/examples/api/multi_filter.html for HTML tables as it provides multiple features. My Django website passes on dates as strings to the frontend Collection Date in descending order and also datetime object to display on frontend HTML template. But it is not sorted correctly. This website has inbuilt sort facility which is not working fine. https://datatables.net/examples/api/multi_filter.html How to sort date string with format "%m-%d-%Y"? Please help me to resolve this. Thank you -
How to get other object field for ForeignKey Django
Firstly, I extend user like this: class MyProfile(models.Model): user = models.ForeignKey(User, related_name='profile', on_delete=models.CASCADE) full_name = models.CharField(max_length=255, unique=True) id_number = models.CharField('ID Number', max_length=14) def __str__(self): return str(self.full_name) And then I want to get reference for full_name's field & id_number's field to other model like this: class MyModel(models.Model): full_name = models.ForeignKey(MyProfile, related_name='full_name_mymodel', to_field='full_name', on_delete=models.CASCADE) id_number = models.ForeignKey(MyProfile, related_name='ic_number_mymodel', on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=True) def __str__(self): return str(self.full_name) And this the form: class MyModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal checkbox-inline' self.helper.label_class = 'col-lg-4' class Meta: model = MyModel fields = '__all__' full_name = forms.CharField(required=True, label="", widget=forms.TextInput(attrs={'class': "form-control"})) id_number = forms.CharField(required=True, label="", widget=forms.TextInput(attrs={'class': "form-control"})) description = forms.CharField(required=False, label="", widget=forms.TextInput(attrs={'class': "form-control"})) But it print both full_name instead of id_number for id_number's field like following picture: How to get full_name's object for full_name's field & id_number's object for id_number's field? -
Django + Uvicorn
I'm trying to use Django 3.0 with Uvicorn and getting this on start: INFO: Started server process [96219] INFO: Waiting for application startup. INFO: ASGI 'lifespan' protocol appears unsupported. INFO: Application startup complete. I could turn lifespan off with the --lifespan off flag, but is there a way to have it work with Django? A quick search for Django + lifespan seems to not return anything. -
HTTP methods for the Django Rest Framework Viewset
I'm working on django rest framework viewset and want to know which HTTP methods map to the functions: 1.list() 2.create() 3.retrieve() 4.update() 5.partial_update() 6.destroy() I have searched a lot but I didn't got the specific answer to my question. So I just want to know which http method maps all the above listed functions thanks in advance!! -
The submitted data was not a file in Postman (Django Rest Frameworks)
I'm trying to develop application using django and django restframeworks. I've some issue when i'm trying to post image with data. BTW I'm new DRF and Postman models.py class Property(TimeStampWithCreatorMixin): land_area = models.DecimalField(max_digits=10, decimal_places=3) ........... class PropertyImage(TimeStampWithCreatorMixin): property = models.ForeignKey(Property, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=get_upload_path) ...... serializers.py class PropertyImageSerializer(serializers.ModelSerializer): class Meta: model = PropertyImage fields = '__all__' class PropertySerializer(serializers.ModelSerializer): images = PropertyImageSerializer(many=True) class Meta: model = Property fields = ['land_area', '...','images', ] def create(self, validated_data): images_data = validated_data.pop('images') property = Property.objects.create(**validated_data) for image_data in images_data: PropertyImage.objects.create(property=property, **image_data) return property and views.py is here class PropertyAPIView(APIView): parser_class = (FileUploadParser,) def post(self, request): serializer = PropertySerializer(data=request.data) print(serializer) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) and here is my post request from postman Here I didn't include all the fields to keep code minimal as well as readable. i'm new to drf and postman so any suggestion would be also appreciated. -
Catch 'UNIQUE constraint failed' for specific field in Django model
I want to create discount code for user. I did set three unique_together and wanna to catch IntegrityError error just for these field that be unique together. This is my model: class DiscountCode(models.Model): student = models.ForeignKey('UserManager.Student') classroom = models.ForeignKey('Education.Classroom') code = models.CharField(max_length=5) class Meta: unique_together = ('student', 'classroom', 'code',) def save(self, *args, **kwargs): if not self.pk: # Set discount code try: self.code = self.discount_code_generator() except IntegrityError as e: # This might be change to specific fields error! if 'unique constraint' in e.args[0]: # args[0] is message of exception # Some code for handling error. I know how to raise error for IntegrityError but I want to catch this error just for student, classroom ,and code fields. How can I do that? -
How to display column values instead of objects in foriegn key column of a model in django?
I have a foreign key column in a model. And I am using Model Form to render it. When I rendered it to the front end, html. The list shows with foriegn key object value. Screenshot here What I need to do is to show specific column values in select list so user can choose easily. The following is the code. model.py class Gurdian(models.Model): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, default=1, null=True) name = models.CharField(max_length=200, null=True) contact = models.CharField(max_length=20) address = models.TextField(null=True) emerg_name = models.CharField(max_length=200, null=True) emerg_contact = models.CharField(max_length=20, null=True) emerg_relation = models.CharField(max_length=20, null=True) doc_name = models.CharField(max_length=200) doc_contact = models.CharField(max_length=20) blood_type = models.CharField(max_length=10) allergic = models.TextField(null=True) class Students(models.Model): created_by = models.ForeignKey( User, on_delete=models.SET_NULL, default=1, null=True) name = models.CharField(max_length=200, null=True) dob = models.DateField(null=True) age = models.IntegerField() grade_choice = ( ('G1', 'Grade-1'), ('G2', 'Grade-2'), ('G3', 'Grade-3'), ('G4', 'Grade-4'), ('G5', 'Grade-5'), ('G6', 'Grade-6'), ('G7', 'Grade-7'), ('G8', 'Grade-8'), ('G9', 'Grade-9'), ('G10', 'Grade-10'), ('G11', 'Grade-11'), ('G12', 'Grade-12'), ) gender_choice=( ('M', 'Male'), ('F', 'Female'), ('N', 'None'), ) gender=models.CharField(choices=gender_choice, max_length=10, null=True) grade = models.CharField(choices=grade_choice, max_length=10, null=True) attending_school = models.CharField(max_length=100) course = models.ForeignKey( Create_Class, on_delete=models.SET_NULL, default=1, null=True) address = models.TextField(null=True) parent_id = models.ForeignKey( Gurdian, on_delete=models.SET_NULL, default=1, null=True) forms.py class Student_Model_Form(forms.ModelForm): class Meta: model = Students fields = ('__all__') exclude … -
What is the order for django visit urls.py
everyone, I am pretty new to Django. I notice that Django visit app.urls before visit mysite.urls. I have mysite.urls as follow (simplified) # mysite.urls path('', views.index, name='index'), path('app', include('app.urls')) To my understanding, when visit http://127.0.0.1:8000/, it should first reach index page. Using the URLconf defined in app.urls, Django tried these URL patterns, in this order: login/ [name='login'] register/ [name='register'] The empty path didn't match any of these. Seems that Django went to app.urls directly without went to mysite.urls first. What could be the issue here? -
Implementing a video call interface in Django
Hey there im trying to implement a video call interface in my django application but unable to find docs .I found twilio but the support was for javascript and webrtc for nodejs. Are there any third party libs that i can integrate in django app -
ArrayField max size?
I'm going to use Django's ArrayField to store a pretty massive list of maybe 500-50,000 items. They're short Ids like 283974892598353920, but I'm worried about hitting some upper limit. Are there any limits for Django's Postgres ArrayField? -
How do I embed a PDF into my template with Django?
I am trying to embed a user manual into a template and thought this would work, but it did not. Is it my file path? I will attach a photo of where I have the PDF stored. HTML: <div class = "container"> <embed src= "Users/remio/mis446-2/mis446/blog/templates/mis446/files/User-Manual.pdf#toolbar=0" type= "application/pdf" width= "100%" height= "600px"/> </div> Views.py: def user_manual(request): return render(request, 'mis446/user-manual.html') urls.py: path('user-manual/', views.user_manual, name='User Manual'), enter image description here It is in the file called "files" -
When i try to change object to json return this "Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Error converting data type varchar to bigint."
i have this model that i get from sql server using inspectdb class TPoin(models.Model): poin_id = models.BigAutoField(db_column='POIN_ID',primary_key=True) # Field name made lowercase. office_region_name = models.CharField(db_column='OFFICE_REGION_NAME', max_length=100, blank=True, null=True) # Field name made lowercase. office_name = models.CharField(db_column='OFFICE_NAME', max_length=100, blank=True, null=True) # Field name made lowercase. agrmnt_no = models.CharField(db_column='AGRMNT_NO', max_length=20, blank=True, null=True) # Field name made lowercase. cust_no = models.CharField(db_column='CUST_NO', max_length=50, blank=True, null=True) # Field name made lowercase. cust_name = models.CharField(db_column='CUST_NAME', max_length=100, blank=True, null=True) # Field name made lowercase. go_live_dt = models.DateTimeField(db_column='GO_LIVE_DT', blank=True, null=True) # Field name made lowercase. ref_rating_x_id = models.BigIntegerField(db_column='REF_RATING_X_ID', blank=True, null=True) # Field name made lowercase. prod_offering_name = models.CharField(db_column='PROD_OFFERING_NAME', max_length=100, blank=True, null=True) # Field name made lowercase. asset_full_name = models.CharField(db_column='ASSET_FULL_NAME', max_length=100, blank=True, null=True) # Field name made lowercase. inst_seq_no = models.IntegerField(db_column='INST_SEQ_NO', blank=True, null=True) # Field name made lowercase. batch = models.BigIntegerField(db_column='BATCH', blank=True, null=True) # Field name made lowercase. created_date = models.DateTimeField(db_column='CREATED_DATE', blank=True, null=True) # Field name made lowercase. flag = models.BooleanField(db_column='FLAG', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'T_POIN' i want to use it the object in model in javascript so i do this in my view data = TPoin.objects.filter().exclude(flag=1) dataset = serializers.serialize("json", data,cls=DjangoJSONEncoder) i tried to search for the anwser but … -
Struggling to get 'get absolute url' to work (Python - Django)
Once a user had logged into my site he could write a post and update it. Then I was making progress in adding functionality which allowed people to make comments. I was at the stage where I could add comments from the back end and they would be accurately displayed on the front end. Now when I try and update posts I get an error message. I assume it is because there is a foreign key linking the comments class to the post class. I tried Googling the problem and looking on StackOverflow but I wasn't entirely convinced the material I was reading was remotely related to my problem. I am struggling to fix the issue because I barely even understand / know what the issue is. models.py def save(self, *args, **kwargs): self.url= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.name) def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) views.py def post_detail(request, pk): template_name = 'post_detail.html' comments = Comment.objects.filter(post=pk ,active=True) post = Post.objects.get(pk=pk) new_comment … -
How can I print a hierarchical view from my self referencing table efficiently?
class Business(models.Model): name = models.CharField(max_length=100, blank=False) class Element(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE, editable=False) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=False) has_children = models.BooleanField(default=False) A Business can have a hierarchy of Element objects as per the schema. A parent value of None means that particular Element instance is a top level Element with no parents of its own. The hierarchy can be nested up to 100 levels deep. Given a company object I need to be able to iterate through all of the that business's elements and output them in a hierarchical view. As seen below: FYI: output of each row is a from a unique Element object Account Income Statement Balance Sheet Assets Liabilities Equity Scenario Actuals Budget -
I am building a Django project of invoice generator and i am Unable to figure out How to send object OR array of objects to the server using AJAX,
In the below code I want to make an ajax request to the contact function in views.py with the object detail, But I am unable to do so also It is showing me CSRF not found. html <button id="submit"> Click here</button> JavaScript detail ={'id':[{Pid: 2, HSN_code: "AE12#@", Rate: 2000, quantity: 1, Price: 0}, {Pid: 3, HSN_code: "1223ABC", Rate: 1000, quantity: 1, Price: 0}, {Pid: 5, HSN_code: "ABC123@", Rate: 1000, quantity: 1, Price: 0}, {Pid: 6, HSN_code: "ABC@123", Rate: 12000, quantity: 1, Price: 0}, {Pid: 7, HSN_code: "ABC@1234", Rate: 3000, quantity: 1, Price: 0}]}, $(document).ready(function(){ $('#submit').click(function(){ console.log(detail) $.ajax({ url:'/contact/', type:'post', data:{'detail':detail, csrfmiddlewaretoken: '{{ csrf_token }' }, dataType:'json', success:function(data){ console.log(data) } }) }) }); Views.py def contact(request): details = request.POST['detail'] print(details) return HttpResponse('true') -
Saving data from Django form into DB
So I have this django model: class Cart(models.Model): ref_code = models.CharField(max_length=15, null=True) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) items = models.ManyToManyField(PickedProduct) start_date = models.DateTimeField(auto_now_add=True) is_ordered = models.BooleanField(default=False) tot_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) tot_item = models.IntegerField(default=0) note = models.TextField(max_length=500, null=True, blank=True) I am using the Cart model to build my NoteOption form like below: class NoteOption(forms.ModelForm): class Meta: model = Cart fields = ['note'] On my views I have this code (it is incomplete but I am working on it): @login_required def UserCartView(request, **kwargs): user_cart = current_cart(request) note = NoteOption(instance=user_cart) # I don't know what to do here if request.method == 'POST': user_cart.note = note user_cart.save() context = { 'note': note, 'user_cart': user_cart, } return render(request, 'cart/cart.html', context) In my template I have below field: <div class="col-lg-4 mt-5 ftco-animate"> <form method="post" id="my_form"> {{ note|crispy }} </form> </div> and at the end of my template I use an a tag to send a post request like below: <a href="{% url 'precheckout-view' %}" class="btn btn-primary py-3 px-4" onclick="document.getElementById('my_form').submit();">Proceed to Checkout </a> When I first launch the template I am able to get the current stored data from datatbase into Note field. However, when I modify the Note field content and after clicking on "Proceed … -
Django: OperationalError: 'no such table: django_site'
I know there many variatons of this question out there such as No such table as django_site. However, the answers found there have not helped. I am attempting to use the 'django.contrib.sites' app and have included it in the INSTALLED_APPS section of settings.py, I then ran the migrations as follows python manage.py makemigrations spatulaApp #the name of the app I made python manage.py makemigrations python manage.py migrate This gave me the following output: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, sites, spatulaApp Running migrations: Applying sites.0001_initial... OK Applying sites.0002_alter_domain_unique... OK I was hopeful this would be the issue sorted however when logging into the admin panel or generating the sitemap we receive the familiar error: I read on the article linked above that I should comment out the app from settings re-run migrations and then reintroduce the app and run migrations a final time. This has had no effect sadly. I have configured the SITE_ID variable in settings too it is located at the bottom of settings.py and set to a value which exists in the DB ... SITE_ID = 2 It is also worth mentioning that I can create Site objects via the manage.py shell (which … -
Django application fails to deploy on AWS ElasticBeanstalk with 'firebase-admin' library
I am deploying my python/django application to aws elasticbeanstalk. It gets deployed fine if i don't specify 'firebase-admin' library in requirements.txt. But fails to deploy if i add 'firebase-admin' no matter what version in requirements.txt as shown below: Here's my requirements.txt: Django==3.0.1 djangorestframework==3.11.0 psycopg2==2.7.3.1 django-cors-headers==3.2.0 pytz==2017.2 tinys3==0.1.12 apiclient==1.0.3 drf_yasg==1.17.1 google-api-python-client==1.7.3 google-auth==1.5.0 google-auth-httplib2==0.0.3 httplib2==0.11.3 django-rest-auth==0.9.5 oauth2client==4.1.2 geographiclib==1.50 geopy==1.20.0 numpy==1.15.2 pyyaml==5.3.1 And AWS elasticbeanstalk python instance details: Python 3.6 running on 64bit Amazon Linux/2.9.7 Please Help. Thanks -
django allauth template tags not working in custom template
I have added the following code in verification_sent.html file. But template tags do not work on templates. # templates/account/verification_sent.html {% extends 'primary/_base.html' %} {% load i18n %} {% block content %} <h1>{% trans "Verify Your E-mail Address" %}</h1> {% load account %} {% user_display user as user_display %} {% blocktrans %}{{ user_display }}, Confirmation email has been sent to your email address{% endblocktrans %} {% endblock content %} Result shows as below Verify Your E-mail Address AnonymousUser, Confirmation email has been sent to your email address. How can I get the Registered user full name and email address from template file? -
import requests is showing error in python but it is showing in pip3 list
import request is not workingIf I am trying to install requests it is showing requirement already satisfied but If I am trying to import then it is throwing error. Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'requests'. I am running the command pip3 list then it is showing requests 2.23.0. but not able to import. -
Entering Abstract Base User Data - IntegrityError: UNIQUE constraint failed
My goal is to create a user account model with AbstractBaseUser. My application requires data that fits into multiple categories. i.e. name city age because there are a lot of questions to be asked of the user, I have tried separating each category into a separate form, view, and template. For example: models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) Name = models.CharField(max_length=30, unique=False) City = models.CharField(max_length=30, unique=False) Age = models.CharField(max_length=30, unique=False) forms.py: class NameForm(forms.ModelForm): class Meta: model = Account fields = ('Name',) class CityForm(forms.ModelForm): class Meta: model = Account fields = ('City',) class AgeForm(forms.ModelForm): # . . . views.py def NameView(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): Name = request.POST['Name'] form.save() return redirect('City') else: form = NameForm() return render(request, 'account/Name.html', {'form': form}) def CityView(request): if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): City = request.POST['City'] form.save() return redirect('Age') else: form = CityForm() return render(request, 'account/City.html', {'form': form}) def AgeView(request): # . . . I was expecting that I would be able to upload segments of user data in separate pages, however, after uploading the first page "Name", and attempting to upload the second page "City", I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: account_account.email … -
Showing certian categories first while iterating
Currently I order my categories by doing "categories": category.objects.order_by('-title') I want to have full control over what order each object appears. I was thinking of having a rank attribute rank = models.IntegerField() however I feel like there could be 2 category objects with a rank of '1' which doesn't make sense. -
Failing To Display Media File Django
I have created a model called Product that takes in an ImageField that will be upload on a function I created: class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=10, default=39.99) image = models.ImageField(upload_to=upload_image_path, null= True, blank=True) def __str__(self): return self.title return self.image def __unicode__(self): return self.title I have also created my MEDIA_ROOT and STATIC_ROOT below is code from main urls however I also defined this two on the settings.py: if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So I am able to upload Image from the admin and it uploads properly to the media_root that I created. When I try calling/displaying the image it render nothing I do not know where I could have made a mistake {% load static %} {{ object.title }} <br/> {{ object.description }} <br/> {{ object.image.url }}<br/> <img src="{{ object.image.url }}" class='img-fluid'/> but the {{ object.image.url }} actually gives me the exact path of the Image which should make sense for the the picture to rendered. This is the the result output that I was telling about, that I'm getting the image url but I can not display the Image