Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sessions are destroying when user redirect from cc avenue payment page in python
when user click on pay user navigate to payment page integrated payment page using html post request. when user back to my application from payment page sessions are destroyed Please Help If any one know Solutions Thank you -
Filtering through two querysets with a many to many relationship in between
I have 3 different models, activity, category and sector. There's a many to many relationship between category and activity, and a one to many relationship between category and sector (a category to one sector). In a form I am getting the sector (mandatory) and I can also get the category (non mandatory field). I stock that into the session then I want to select every activities that are either in the category selected (if any selected) or in the sector. When a category is selected it's fine I just filter activities on activities_have_category. But for the case where only sector I can't filter it properly. I tried the solution to a quite similar problem but it didn't work... Solution tried: activity.objects.filter(category__sector__sector_name =request.session['sector']['sector_name']) Result: Cannot resolve keyword 'category' into field. Choices are: activities_have_category, activities_have_countries, activities_have_output_outcome_impact, activity_name, description, outcome_impact, output_outcome, product_service What I would like to get in SQL: SELECT activity_name FROM activity WHERE activities_have_category IN (SELECT category_name FROM category WHERE category_sector = "sector selected") class sector(models.Model): sector_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() def __str__(self): return self.sector_name class category(models.Model): category_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() category_sector = models.ManyToManyField('sector') def __str__(self): return self.category_name class activity(models.Model): activity_name = models.CharField(max_length=255, primary_key=True) description = … -
How to define an in-store cash-payment-method in django-oscar 2.0
I would like to implement cash payments, wherein the customer picks up his order in store, and pays the same there. There will also be an option later on for customers to pay cash upon delivery of their orders (note: I understand that there is an oscar cash on delivery app, but I am asking regardless). What is oscar's new recommended way to define cash payment methods in version 2.0? Previously, (though I can no longer find the documentation), payment methods were defined by expanding a base payment method like so: # mystore/forked_apps/payment/methods.py class Base(object): """ Payment method base class """ code = '__default__' name = 'Default payment' description = '' enabled = False default = False class CashOnPickup(Base): code = 'cash_on_pickup' name = 'Cash on Pickup' description = 'Pay when you pick up your items' enabled = True default = True However, the new documentation mentions the use of the SourceType, Source, and Transaction models, and I can no longer find the previous documentation regarding defining methods like above. As such, what is the recommended manner to define an in-store cash payment method in django-oscar 2.0? Is defining methods in a methods.py file no longer the way to go? … -
Slack API ConnextionError but still working
I want to post a message to Slack using a bot, so I created a service to do that (in Flask). Now I call this service using requests (Django). data = json.loads(json.dumps(_data)) headers = { 'Content-Type': "application/json", 'cache-control': "no-cache", } r = requests.post(url, json=data, auth=(username, password), headers=headers) While the bot is posting on Slack and everything is working like expected, I'm having an error message and this is confusing: ('Connection aborted.', BadStatusLine("HTTP/1.0 0{ 'ok':True, 'channel':'xxxxxxxxxxx', 'ts':'1563789414.000600', 'message':{ 'type':'message', 'subtype':'bot_message', 'text':'xxxxxxxxxxx', 'ts':'1563789414.000600', 'username':'xxxxxxxxxx', 'bot_id':'xxxxxxxxxxx' }, 'headers':{ 'Content-Type':'application/json; charset=utf-8', 'Content-Length':'220', 'Connection':'keep-alive', 'Date':'Mon, 22 Jul 2019 09:56:54 GMT', 'Server':'Apache', 'X-Content-Type-Options':'nosniff', 'X-Slack-Req-Id':'1851de9e-59ec-45a7-be61-107a092e6371', 'X-OAuth-Scopes':'admin,identify,bot,groups:read,usergroups:read,chat:write:user,chat:write:bot,groups:write', 'Expires':'Mon, 26 Jul 1997 05:00:00 GMT', 'Cache-Control':'private, no-cache, no-store, must-revalidate', 'Access-Control-Expose-Headers':'x-slack-req-id, retry-after', 'X-XSS-Protection':'0', 'X-Accepted-OAuth-Scopes':'chat:write:bot', 'Vary':'Accept-Encoding', 'Pragma':'no-cache', 'Access-Control-Allow-Headers':'slack-route, x-slack-version-ts', 'Strict-Transport-Security':'max-age=31536000; includeSubDomains; preload', 'Referrer-Policy':'no-referrer', 'Content-Encoding':'gzip', 'Access-Control-Allow-Origin':'*', 'X-Via':'haproxy-www-n3u5', 'X-Cache':'Miss from cloudfront', 'Via':'1.1 d6561aeeccb210202cf78b99f07c5235.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop':'CDG3-C2', 'X-Amz-Cf-Id':'Y4CJp-NBWSkdNYXm8bfTCdhuFPL1sn6johYZqkmv_wsXfaq0kcA7TQ==' } }\r\n")) Calling the service using a simple curl works fine without any error: curl -d "@data.json" -H "Content-Type: application/json" -X POST http://0.0.0.0:8004/ --user xxxxx:xxxxx Do you see the problem ? -
How to add CSRF token for Ajax Request not using jQuery
I want to send some data from the javascript file to the views file in my Django app using an Ajax request. However I am doing this using only Javascript as I am not familiar with jQuery and don't now how to add the CSRF token. Here is my Javascript Code: const request = new XMLHttpRequest(); request.open("POST", "/list"); var csrftoken = Cookies.get('csrftoken'); let data = { items: JSON.stringify(items), CSRF: csrftoken } request.send(data); I have tried using Cookies.get('csrftoken') and getCSRFTokenValue() but am unsure how to send the token once acquired. -
django admin filter for dictionary field
I have a model with a dictionary field inside it. for admin page of this model, I have one of the list_filter as a value from a foreign key referencing to another model. what i want is to filter out the keys in the dictionary field based on this list_filter . As an example model A has fields : x,y,z where y is dictionary field its admin has a list filter L that needs to filter keys in y based on its value selected . How is this possible to achieve in a clean way ? thanks in advance -
Restframework restore request, how can i prevent this
I wrote a middleware to authenticate, after authentication, I want to modify request.POST to view, view use two decorators of restframework. When I delete the two decorators, it works well, the request is changed.How can I use the two decorators and change the request at the same time. Middleware code: class ApiAuthenMiddleware: def init(self, get_response): self.get_response = get_response def __call__(self, request): sign = request.POST['sign'] nonce_str = request.POST['nonce_str'] password = request.POST['password'] key = f"{f'{password}{nonce_str}'[:24]:0<24}" data = request.POST['data'] if encrypt(data, key) != sign: pass else: request.POST = QueryDict(urlencode(json.loads(data))) response = self.get_response(request) return response View Code: @api_view(['POST']) @renderer_classes([TemplateHTMLRenderer, JSONRenderer]) def package_list(request): iccid = request.POST['iccid'] serializer = BLEDataPlanSerializer(BLEDataPlan.objects.filter(card__iccid=iccid)) data = serializer.data return Response(data) -
how to pass csrf-token in first request
my question is how cookies works, this question is arrived in my mind when i loaded my page for first time i got this REQUEST HEADER Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en;q=0.9,en-US;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Cookie: csrftoken=gsZxmbW4XUpE6YnaQhlrAx9JduyExVgzWEo4fXhcY4V3fbHWVtwf0msbDQDT5r43 Host: 127.0.0.1:8000 Upgrade-Insecure-Requests: 1 when first request was sent it already had csrftoken in cookie i tried same in incognito window than also i got same result. how can my browser already have cookie without any communication to server i am working on django with angular 7, problems is that i am sending my request from angular this.http.post('http://127.0.0.1:8000/',data, {observe : "response", withCredentials: true } )} but in response of that i am not getting any csrftoken in setcookie . please help me ..... sorry for adding two problems in one question but both are indirectly connected to each other -
How to modify router and viewsets for template rendering
I have a simply CRUD application with Rest-Framework my views, serializers and routers is created dynamically. I used a simple code from DRF docs like that: VIEWS: class PersonViewSet(viewsets.ModelViewSet): serializer_class = PersonSerializer queryset = Person.objects.all() SERIALIZERS: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' URL: router = routers.SimpleRouter() router.register(r'persons', PersonViewSet) Now I have to do smth for displaying data for end-users. My goal is: 1. Play 1-2 weeks with build-in django functionality for frontend development 2. Consider about vue.js as a frontend framework. So I have to use django and DRF as a backend (this is for sure). I have some trouble with template rendering. Now I create a simple HTML templates and try to implement them. There are some problems when using them with ViewSets. Seems that I have to use another parent class for views. Could you provide me some examples how should I change my views and router? I already tried to use simply APIView, but seems that routers works only with viewsets. -
Django, how to use the admin autocomplete field in a custom form
In the Django admin interface you can set a field to be a autocomplete field, e.g.: autocomplete_fields = ('countries', ) This works great for admin pages, how does one use the autocomplete field in a custom view/form? My research points towards django-autocomplete-light, but it seems non-ideal to install a 3rd party package when Django already has the functionality built-in. -
Python-Tweepy-How to disconnect all streams where is_async=True in tweepy with streams.disconnect()?
I have 2 functions one is for start stream and other is for stop stream with is_async=True, and now I can start multiple but when I call stop stream function it only stops the first stream in the thread. For Start Stream simply calling this function def startStream(): global myStreamListener myStreamListener = MyStreamListener() global myStream myStream= tweepy.Stream(auth=api.auth, listener=myStreamListener,truncated=False) myStream.filter (track=[track], follow=[follow], locations=location1, is_async=True) For Stop Stream calling this function def stopStream(): myStream.disconnect() Now the problem is I can start multiple crawler with startStream function but unable to stop all crawler with stopStream. Question: Now my first question is how to stop all streams one by one or on call with stopStream function? Thanks...!! -
Parse QueryDict data
Little new to django, I'm running python scrip to fetch the data and like to display in HTML table tags. Python script works and gather the data in the following: [{'Device': 'device01', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 1111, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}, {'Device': 'device02', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 2222, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}] When run the python script in Django in the view.py, I store the output in the following: if form.is_valid(): ## Python script GatherData file output = gatherdata(location) data = QueryDict(output, mutable=True) ## Dict format to fetch context = {'data': data } The output looks like the following: <QueryDict: {"[{'Device': 'device01', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 1111, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}, {'Device': 'device02', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 2222, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}]\n": ['']}> Explain above, How to parse the value from the given data, to html template Given above, Thank for the ideas and suggestion. I have tried, json.loads(output) but thru errors. I have tried data = literal_eval(context['data']) to remove the strings. -
'Invalid default value error' in models file
I was trying to create a "currency" column which would consist of choices for different currencies. I tried everything but couldn't resolve "django.db.utils.OperationalError: (1067, "Invalid default value for 'currency'")" error. Here is my models.py file. class Products(models.Model): INR='₹' USD='$' CURRENCY_LIST=[(INR,'INR'),(USD,'USD')] subcategory=models.ForeignKey(Subcategory,on_delete=models.CASCADE) category=models.ForeignKey(Category,default='',on_delete=models.CASCADE) name=models.CharField(max_length=30) price=models.DecimalField(max_digits=7,decimal_places=2,default=0) currency=models.CharField(max_length=2,choices=CURRENCY_LIST,default=INR) class Meta: db_table='products' @property def combined(self): return self.price+self.currency def __str__(self): return self.name How to resolve this error? -
what is django datetime field format
I send django datetime field data to client in string type my question is how i can convert this string to python datetime? my datetime is: "2019-07-22T10:01:40.876487+04:30" I want to do something like this: datatime.datetime('2019-07-22T10:01:40.876487+04:30', '<django default datetime format>') and I expect to have: <class 'datetime.datetime'> WHAT IS DJANGO DEFAULT DATETIME FORMAT? OR HOW I CAN CONVERT THIS STRING TO DATETIME? -
How to decouple local directory and Heroku project
I am developing an app with Django and I successfully pushed it on Heroku. This app has a database and a form to allow users to fill the database. I have coupled the local directory and Heroku, so that both if I run the server by command prompt, or if I access the app, and submit the form, my database get changed. Now I want to make some experiments on the local database without changing the one on Heroku. Is it possible? Can I do it by just commenting the database URL in settings.py ? I have searched for this matter on Google but I don't know the name it, so that I cound not find proper answer. -
How to create new objects in django rest framework?
Here i am trying to create some categories but the problem is when i enter the category-create url it displays the only content option but no any fields of my category model.How can i do that?I am only getting this content text field but this is not in my category model field.How can i display all my model fields into my create form? models.py class Category(models.Model): name = models.CharField(max_length=191, blank=False, null=False) description = models.TextField(blank=True, null=True) urls.py path('create',views.create,name='category-create'), views.py @api_view(['POST']) @permission_classes((permissions.IsAdminUser,)) def create(request): if request.method == 'POST': serializer = CategorySerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serialzers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' -
Two get requests in one django APIView
I have an APIView for a X object. I want to have a get request get_X (receives id of the X object) and a get request get_multiple_X (gets all X objects). The current solution is: we have two APIView: one called XView (contains get_X), the second called XListView (contains get_multiple_X). Is there a way to make both requests in the same APIView? I want to have only one APIView (XView). What is the best practice in this case? -
how to get data from database and display it in the form in order to update the content
i have an update function that allow user to update the inserted record using django. i tried to filter the object based on the id. then once i return the id i assume i am able to get all fields. the problem is that when i go to update page the form is empty and no data are return. views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: dbEntry = suspect.objects.filter(pk =pk) print( "db entry : ",dbEntry) return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div><div class="line"></div> </div> <form enctype="multipart/form-data"> <div id='left-column-Input' class="formInput" include="select()"> <div class="forminputs"> <input type="text" id="fname" name="fname" autocomplete="off" required /> <label for="fname" class="label-name"> <span class="content-name" name="fname">{{dbEntry.suspect_name}}</span> </label></div> <div class="home-Button"> <button id="save" name="save" type="submit">Edit</button> <button id="clear" name="clear" type="submit">Clear</button> </div> </div> -
Deleted content from Django app deployed on Heroku appears again
I deployed my Django application on Heroku. Everything works well, except one think as I mentioned above: This is a blog site, and for testing I added just one article. After 10-15 minutes it appears again on my page. What is the reason, I can't get. -
Divide queryset result by months [duplicate]
This question already has an answer here: How to query as GROUP BY in django? 9 answers I have this users stats models.py: class UserStat(TimeStampedModel): company = models.ForeignKey(Company) account_status = models.CharField(max_length=50, choices=users_constants.USER_STATUS_CHOICES) month = models.DateField() count = models.IntegerField(default=0) How to iterate over data and get data divided by months? [{ "label": month_name, "data": { "active": active_users_count, "inactive": inactive_users_count }, }] Here is an example result: [{ "label": "Jan", "data": { "active": 231, "inactive": 12 }, }, { "label": "Jul", "data": { "active": 123, "inactive": 4 }, }] -
How to prepopulate the model when app is ready via AppConfig
I am trying to prepopulate a model with some values when the app starts. I thought the most logical would be to implement it in def ready of AppConfig, but it does not work. from django.apps import AppConfig from django.db.models import signals from myapp.models import mytable class MyAppConfig(AppConfig): name = "MyApp" def ready(self): print(mytable.objects.all()) Above I just try to get the items that are already there, but it still fails. django.db.utils.OperationalError: no such table: myapp_mytable -
Page not found 404 error when trying to serve media files in Django
I want to display user uploaded images in my template. I can't seem to find what I'm doing wrong. Using Django 2.2 version. I tried what the documentation says (https://docs.djangoproject.com/en/2.2/howto/static-files/) but couldn't find any other solution after this one failed. This is from settings.py file. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is from my urls.py file in an app called 'signage' urlpatterns = [ path('screens/', views.screens_dashboard, name='screens_dashboard'), path('screens/new/', views.add_screen, name='add_screen'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is from my template <img class="img-fluid" src="{{ screen.picture.url }}" alt="First slide"> -
How do I develop the view.py file for the the models below? A list view of all the projects and a detailed view for each project is needed
I'm writing the code for the views.py file. How do I handle the many-to-many relation between the tables? The models.py file is pasted below. enter code here from django.db import models # Create your models here. class Developer(models.Model): name=models.CharField(max_length=150) image=models.ImageField() about=models.CharField(max_length=1500) smartcampus_contributor=models.BooleanField(default=False) def __str__(self): return self.name class Contributions(models.Model): contributor=models.ForeignKey(Developer,on_delete=models.CASCADE) description=models.CharField(max_length=1500) timestamp=models.DateTimeField(auto_now_add=True) def __str__(self): return self.contributor.name+"-"+str(self.pk) class Project(models.Model): developer=models.ForeignKey(Developer,on_delete=models.CASCADE) project_name=models.CharField(max_length=250) github_link=models.URLField(max_length=250) description=models.CharField(max_length=1500) def __str__(self): return self.developer.name+"-"+str(self.pk) -
Custom select box field in form from model in django
Please help me to do custom Select Box in forms of Django. I want to query the data from the model, i have created In Model.py Title = models.CharField('Title', max_length=250, blank=True, null=True, help_text='Enter Title') in Admin.py class Meta: model = Book1 fields = ['Title'] Title = forms.ModelChoiceField(queryset=Book1.objects.values_list('Title', flat=True).distinct(), widget=forms.Select()) class Book1Admin(admin.ModelAdmin): form = Book1Form save_as = True admin.site.register(Book1, Book1Admin) But it did not display as a select box, only as a text field in the place of Tile field. Do I need to create custom select field for the QuerySet? -
Use https for uploaded file in Django
I have a model to stock json file: class JSONFile(models.Model): source = models.FileField(upload_to='json') When I upload a file directly in Django admin, then click on the url in the interface, I found that the url of this file uses the https scheme. For example: https://mydomain/api/media/json/file1.json But when I access the view's result by https://mydomain/api/jsonfiles/1/, it uses http: { "id": 1, "source": "http://mydomain/api/media/json/file1.json" } How could I fix that? Thank you!