Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i access wordpress data/dashboard?
So, I have created a custom dashboard using Django. I want to access all the fields(activeplugins, active themes, wordpress version, etc) present in my wordpress dashboard and display it in my dashboard. -
Django Redirect after POST
I have a Django ModelForm which is rendering fine on the frontend and would like the page to redirect to the home page after POST. When I fill out the form and click submit, I can see the POST come through in the terminal with a status of 302 and does not run the redirect. If I remove the redirect in my views and post the data from the frontend, the POST comes through with a status of 200. #views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import OptInForm from django.forms import forms def index(request): return render(request, 'pages/index.html') def arthritis(request): form = OptInForm() if request.method == 'POST': form = OptInForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('index') else: form = OptInForm() return render(request, 'pages/physical_therapy/arthritis_pain.html', {'form': form}) Here is the form which the view is pulling from: #forms.py from django.forms import ModelForm from .models import OptIn class OptInForm(ModelForm): class Meta: model = OptIn fields = ['first_name', 'last_name', 'email', 'phone'] This is the model: #models.py from django.db import models from django.forms import ModelForm from datetime import datetime class OptIn(models.Model): opt_in_option = models.CharField(max_length=50, blank=True, choices = OPT_IN_CHOICES) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(max_length=40, blank=False) phone = … -
How to connect the external independent template(contains of javascript and ajax) with django backend to POST the zip file to external template
connect the external independent template(contains of javascript and ajax) with django backend to pass the image from front end and get the image in backend convert into the zip file and post to external javascript template -
datetime field in django response json
I am using the following codes with django. The results are coming. But can we make the startDate and endDate fields I want return as datetime? On the frontend side, it warns that the startDate and endDate information comes as strings. I want to prevent this API url: http://127.0.0.1:8000/api/appointments/list?user=2&groupCode=1453&startDate=2020-04-17+10:00:00&endDate=2020-12-12+08:00:00 views.py ` class AppointmentsListAPIView(ListAPIView): serializer_class = AppointmentsCreateSerializer permission_classes = [IsOwner] def get_queryset(self): queryset = Appointments.objects.filter(user=(self.request.query_params.get('user')), groupCode=(self.request.query_params.get('groupCode')), startDate__gte=(self.request.query_params.get('startDate')), endDate__lte=(self.request.query_params.get('endDate'))) return queryset ` model.py ` class Appointments(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=0, blank=False) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=False) note = models.CharField(max_length=100, blank=True) startDate = models.DateTimeField(blank=True) endDate = models.DateTimeField(blank=True) title = models.CharField(max_length=90, blank=True, default=0) allDay = models.BooleanField(default=False) modifiedDate = models.DateField(auto_now=True) groupCode = models.CharField(max_length=50, blank=False) appointmentsKey = models.UUIDField(editable=False, default=uuid.uuid4, blank=False) created_userKey = models.UUIDField(editable=False, default=uuid.uuid4) createdDate = models.DateField(auto_now=True, editable=False) ` response ` [ { "user": 2, "customer": 41, "appointmentsKey": "e9adbadb-342e-4b03-9505-59d7b5312582", "created_userKey": "47f332f1-cc7c-4067-a43a-98939186ab31", "createdDate": "2020-04-19", "modifiedDate": "2020-04-19", "groupCode": "1453", "note": "", "title": "1", "startDate": "2020-04-22T06:00:00Z", "endDate": "2020-04-22T06:30:00Z", "allDay": false } ] ` on the frontend side the following fields are string, but want it to come as datetime "startDate": "2020-04-22T05:00:00Z", "endDate": "2020-04-22T05:30:00Z", -
DJANGO PASS THE VALUE OF INPUT TO URL VIEW
i want to pass the value of input form to my view.py with {% url %} so i have this form in my .html <form> <input id="demo" type="text" name=""> </form> <button onclick="myFunction({{no}})">Start</button> <button onclick="myFunction(1)">Stop</button> with some script so i dont wanna use django forms <script> var elements = {{dataset|safe}}; function random_item(items) {return items[Math.floor(Math.random()*items.length)];} function myFunction(x) { if (x == 0){inter = setInterval( function myFunction() { document.getElementById("demo").value = random_item(elements)}, 30);} else { clearInterval(inter)} } </script> and this in my url app paternn urlpatterns = [ path('',views.index, name='index'), path('<int:no>/',views.index,name='submit') ] this is my view def index(request,no=0): if no == 0: show data else: input data to another table based on no and update data return render(request, 'undian_wombastis/undian.html', context) i have read that i can use json to pas with request.method but is there a way so i can use it like this thankyou -
How to override the get method of model object
I have 3 models User, Role and UserGroup. Model User is an extended model of AbstractBaseUser. Model Role has just one field role_name and model UserGroup has two foreign_key field role and user. I want to insert a record into model UserGroup but since both fields of UserGroup are foreign_key it will only accept model instances of UserGroup.user and UserGroup.role or else it will raise a value error. So, in my APIView I did this - user_group{} user_group['role'] = Role.objects.get(pk=2) user_group['user'] = User.objects.get(pk=1) print(user_group) After executing the above code the value of user_group is - {'role': <Role: Role object (2)>, 'user': <User: pqw109@inc.com>} When I pass user_group to UserGroupSerializer it raises an error because I have defined user field as an integer in UserGroupSerializer. I am writing exactly same query method i.e get() for the objects of both the models but the output is different. What I want is just like field role I want the value of user field as <User: User object (1)>. {'role': <Role: Role object (2)>, 'user': <User: User object (1)>} this is how I am expecting user_group dictionary. I know this can be achieved by overriding the default get() method of manager but I am … -
Django Graphene Returning list of DjangoObjectTypes as opposed to list of Models causes client to override previous results
I'm crossposting this from the repo's issue: https://github.com/graphql-python/graphene-django/issues/938 I have this graphene node class TripNode(DjangoObjectType): legs = List(LegNode) # Need explicit pk when forming TripNode manually and querying for id pk = String(source="id") class Meta: model = Trip interfaces = (relay.Node,) The resolver fetches some remote data and resolves legs there since legs is derived from that remote data as well. def resolve_trips(root, info, **kwargs): response = requests.get("") return [ TripNode( **{ "id": uuid.uuid4(), "origin": trip["origin"], "legs": [ TripLeg( origin_hub=leg["flyFrom"], id=uuid.uuid4(), ) for leg in trip["route"] ], } ) for trip in response.json()["data"] ] Usually I would instead return a list of Trips but I can't use the Django model here because I am resolving the extra field legs that does not exist in the model. One reason it doesn't is that it must be ordered so a one-to-many field would not suffice without some addition. If I do return a list of Trips without legs, it works fine and the client doesn't overwrite the previous query results with the new ones. But that weird overwrite behavior does occur when I use TripNode instead, and that's the only difference. I think it has to do with some graphQL standard not … -
How can I add / in my string as a paramter in django url?
I have land numbers such as '171/20' , '23','34/112/1' , etc. on passing these as a parameter I should be able to fetch info about them. The problem is I can't do something like we do normally. because it will be like localhost:8000/171/20 which is not what I want exactly. -
How can one unbind port 3306?
I am new to google cloud but was just able to deploy the test Django app that google provided in their documentation. This process included downloading the cloud_sql_proxy and running the following in the terminal (MacOS): ./cloud_sql_proxy -instances="my-instance-274702:us-central1:fms"=tcp:3306 This command starts running the proxy in order to connect locally to the DB in the cloud. Everything was working fine until I terminated the proxy with ctrl + C. When I ran the following command to start the proxy again I got the following error: ludovico@Ludovicos-MacBook-Pro django % ./cloud_sql_proxy -instances="my-instance-274702:us-central1:fms"=tcp:3306 2020/04/18 23:38:10 Rlimits for file descriptors set to {&{8500 9223372036854775807}} 2020/04/18 23:38:12 listen tcp 127.0.0.1:3306: bind: address already in use I got this error the first time I did this but I fixed it by shutting down the MySQL server that was running on port 3306. Now however, port 3306 is already bound to the cloud_sql_proxy and so it is throwing an error and is unable to start the proxy. If I run the same command with port 3307 it works just fine: ./cloud_sql_proxy -instances="my-instance-274702:us-central1:fms"=tcp:3307 But Django does not look for port 3307 it looks for port 3306. Is it possible to unbind port 3306? Better yet, is there a command … -
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