Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter list items within a Django JSONField
Here is a simplified version of a Django model I'm working on. class Course(models.Model): infos = JSONField() The infos JSONField looks like this : infos = { category: "Maths", students: [ { name: "Alice", result: 8 }, { name: "Bob", result: 12 } ] } # (students can have 0 -> n items) I'm trying to get a list of all students that got at least 10 on any course (result >= 10). However I'm having trouble figuring out a way to filter the QuerySet accordingly. I'm trying to do something like this : (Course.objects.filter(students__result__gte=10) .values_list('students', flat=True)) But since students is a list, I can't access directly to the result property of each item. Besides, I don't think it would exclude the "Alice" object from the results. I'd like to get results like this : items = [ { name: "Bob", result: 12 } ] Bonus points if there is a way to link filtered students and course category : items = [ { category: "Maths", students: [ { name: "Bob", result: 12 } ] } ] How can I achieve the desired result ? -
Creating a Stripe Subscription Python
I am trying to create a stripe subscription and then charge the customer for that subscription. My stripe transactions are showing as "incomplete" in the dashboard, because they are not being payed. The front-endend is creating a token using the stripe.js successfully using a pre-made stripe credit card form, but I am not sure if my back-end python code for creating the subscription and charging it is correct.. The charge should be immediate for the subscription: "collection_method": "charge_automatically", ... if request.method == "POST": try: token = request.POST['stripeToken'] #Create Stripe Subscription Charge subscription = stripe.Subscription.create( customer=user_membership.stripe_customer_id, items=[ { "plan": selected_membership.stripe_plan_id, }, ], ) #Charge Stripe Subscription charge = stripe.Charge.create( amount=selected_membership.stripe_price, currency="usd", source=token, # obtained with Stripe.js description=selected_membership.description, receipt_email=email, ) return redirect(reverse('memberships:update_transactions', kwargs={ 'subscription_id': subscription.id })) except stripe.error.CardError as e: messages.info(request, "Oops, your card has been declined") ... -
Category clustering in django models
context: creation of a CMS I am looking for an effective way to represent subject nesting/dependance of articles in a Django model. Right now, Categories are defined as follow: class Category(models.Model): parent = models.ForeignKey('self', default=None, null=True, blank=True, related_name='nested_category', on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True) nesting_level = models.IntegerField(default = 0, editable=False) def __init__(self, *args, **kwargs): super(Category, self).__init__(*args, **kwargs) if self.parent != None: self.nesting_level = self.parent.nesting_level + 1 elif self.parent == None: self.nesting_level = 0 def __str__(self): full_path = [self.name.lower()] k = self.parent while k is not None: full_path.append(k.name.lower()) k = k.parent return '->'.join(full_path[::-1]) This works pretty well. Every time a category is added, nesting_level is calculated based on the parent's nesting_level. I see the changes in the BDD (I know, one should not override __init__ in Django but I'll come to this issue later). The need Say I have the following category three: Code--------Python---------Django [1] | [2] | [3] | |----Functional_Programing |---Java [5] [4] When hitting for the category Python, the view should not only present Articles in code->python but also code->python->django code->python->functional_programing since the latter are also python related. When hiting on the url /browse/code->python/ the view would say something like articles = Article.objects.filter(category__in=[2, 3, 5]) The idea that does not … -
Best way to deal with validation checks in model creation
I am trying to figure out how to use validations when creating an object in django. From my POV, there are 2 approaches: Override the default validate_field method of the DRF serializers. Add field-level validators to models and catch any IntegrityError or ValidationError exception when serializer calls .save() method of the model. Both ways seem to have their cons. By using approach 1 my models are left "unprotected" from any other .create() call of the model besides the serializers. Approach 2 deals with the above issue, but makes the code more complex since exception handling is neccessary in serializer's .create() method. Is there anyone that has faced a similar issue and/or found a "cleaner" way to deal with this? -
Convert django loader.render_to_string() to flask for sendgrid
We are converting our django app to flask and I cannot find something like the django loader.render_to_string for flask. Any suggestions I tried the render_template_string in flask but to no avail? from django.template import loader from sendgrid import SendGridAPIClient def send_email: dt = { 'name': xxxxxx, 'application_name': xxxxxx, } email_template_text = loader.render_to_string("xxxxx.txt", dt) email_template_html = loader.render_to_string("xxxxx.html", dt) data = { "personalizations": [ { "to": [ { "email": xxxxx } ], "subject": xxxxxx } ], "from": { "email": xxxxxxx }, "content": [ { "type": "text/plain", "value": email_template_text }, { "type": "text/html", "value": email_template_html } ] } sg = SendGridAPIClient(xxxxx) response = sg.send(data) -
Uvicorn not closing connection when directly closing connection before accepting connection
I am using Django Channels with uvicorn and I have following type of code: async def connect(self): """Accept connect if user has been provided by middleware""" self.user = self.scope.get('user') if self.user: await self.accept() else: await self.close() Basically, if after going through middleware if use is none i am closing the connection. When I run it with Daphne, it works perfectly fine. Otherwise, when I run it via uvicorn server, it throws following error: ERROR: Exception in ASGI application Traceback (most recent call last): File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 146, in run_asgi result = await self.app(self.scope, self.asgi_receive, self.asgi_send) File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/uvicorn/middleware/asgi2.py", line 7, in __call__ await instance(receive, send) File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/channels/utils.py", line 59, in await_many_dispatch await task File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch result = task.result() File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 226, in asgi_receive data = await self.recv() File "/home/coldbrewtech/frnd/backend/env/lib/python3.6/site-packages/websockets/protocol.py", line 419, in recv return_when=asyncio.FIRST_COMPLETED, File "/usr/lib/python3.6/asyncio/tasks.py", line 311, in wait fs = {ensure_future(f, loop=loop) for f in set(fs)} File "/usr/lib/python3.6/asyncio/tasks.py", line 311, in <setcomp> fs = {ensure_future(f, loop=loop) for f in set(fs)} File "/usr/lib/python3.6/asyncio/tasks.py", line 526, in ensure_future raise TypeError('An asyncio.Future, a coroutine or an awaitable is ' TypeError: An asyncio.Future, a coroutine or an awaitable is … -
How to properly and fully customize django admin?
i m discovering the django world and i'm a newbie to backend development, so my objectif is for the moment to figure out how to customize django admin site's UI and Functionality to suit up my college's project needs and also i want to make the admin site look more like modern Dashboards. this is the 4th day of searching and trying but with almost no success, almost all posts and tutorials i ve found are from 6+ years. i would like to know how to prepare files needed in order to customize the admin Templates so that front end stuff can be used (changing layout , styling etc..) thanks in advance -
Unable to serialize database: column technical_information_floorinformation.far_fifth does not exist
I'm tring to backup whole database by using dumpdata command, it gave me error.(Unable to serialize database: column technical_information_floorinformation.far_fifth does not exist LINE 1: ...al_information_floorinformation"."remark_fourth", "technical... ^) def get_dumpdata(request): context={} file_path = '{}/fixtures/dumpdata.json'.format(BASE_DIR) f = open(file_path, 'w') call_command( 'dumpdata', stdout=f, format='json' ) f.close() -
keywords must come before ** argsPython(parser-16)
I am new to python and I have an application and was unable to run the server as I am getting the following error in this method " keywords must come before ** argsPython(parser-16)" at queryset = queryset.annotate(num_exemptions_applied=Count(Case( When(**annotate_filters, then=1) the entire method as follows .Any help is appreciated. def get_queryset(self, request): mtr_id = self.request.query_params.get('id') user_terminals = request.user.groups.values_list('name', flat=True) queryset = ApplicableTimeSlots.objects.filter(code__in=user) annotate_filters = { 'exemptions__killed': False } if id: queryset = queryset.filter(mtr=id) annotate_filters['time_zone_id'] = mtr_id queryset = queryset.annotate(num_exemptions_applied=Count(Case( When(**annotate_filters, then=1), output_field=IntegerField(), ))) return queryset.values( 'time_zone__id', 'time_zone__time_slot_start' ).distinct().order_by("time_zone__time_slot_start") -
Why login() function is looping?
After user registration need to log in and redirect to profile. There should also be logic for manual entry. To do this, I tryed override the login() function. Under the first condition, an automatic login and redirection to your profile should occur. But function is looping from django.contrib.auth import authenticate def registration(request): .... if request.is_ajax(): .... else: global user_ user_ = authenticate(username=email, password=password,) auth_login(request, user_) return HttpResponseRedirect(reverse('profile_view', args=[request.user.slug])) def login(request, template_name='accounts/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, extra_context=None): if <condition_1>: auth_login(request, user_) to = reverse('profile_view', args=[request.user.slug]) return HttpResponseRedirect(reverse('profile_view', args=[request.user.slug])) #looping else: form = authentication_form(request) return TemplateResponse(request, template_name, context) LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = "/login/success/"``` -
Django/Graphene/Apollo/django-webpack-loader/Vue: CORS/CSRF not working together?
I'm working on a project using Django as backend, Vue as frontend, and trying to implement Apollo/Graphene/GraphQL as data transfer layer. Most of it works, but I don't get my head around the CORS/CSRF settings. (Had really much research here. here, and here and here. Does anyone know how to solve this? You can see (and checkout, it's open source) this project here. http://localhost:8000, http://localhost:8000/admin and http://localhost:8000/ work nicely. But I can't get any data from my frontend applucation via Vue/apollo from the graphql backend API: The query query{menuItems{id, title, slug, disabled}} works well in GraphIql, but within the frontend it only returns "undefined". The cause is that IMHO the server refuses to give data outside because of a malformed CORS setting. But I really gave up here. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/sockjs-node/ info?t=1558447812102. settings.py: INSTALLED_APPS = [ # ... 'corsheaders', 'rest_framework', 'webpack_loader', 'graphene_django', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # new # ... ] CORS_ORIGIN_ALLOW_ALL = DEBUG # (=True) CORS_ORIGIN_WHITELIST should not matter if CORS_ORIGIN_ALLOW_ALL = True according to their docs. There is a CORS_REPLACE_HTTPS_REFERER = Truesetting for corsheaders, but I don't know what to do with that. Doesn't change enything … -
Problems when loading local fonts in css with font-face
I'm working with html and CSS, and I need to load a font which is in my local storage, but it gives me the following error: downloadable font: download failed I'm using font-face to try to load it, but it doesn't work. I'm working with mozilla-firefox for linux mint. Hope anyone can help me This is what i've tried: @font-face { font-family: 'qebab'; src: local('qebab'), url('fonts/qebab-webfont.ttf')format('truetype'); } and then I try to use it in my class .important-font { font-family: 'qebab'; } -
Is it possible to show SlugRelatedField and HyperlinkedRelatedField from single model field in DRF API Browser?
In my User model, I have a field "Country" which is a ForeignKey field to my Country model. In the DRF API Browser, I want to show two values from that: The name of the country, via SlugRelatedField: "country": "Zimbabwe", and the link to that same country in the countries table: "country": "http://virticl.api/countries/249/", Is this possible? -
Database entries added in background task don't show up on heroku
I have a background task in my django application, which enters all the rows from a csv into one of the tables in my database. I pass the csv via the admin site, that creates a background task, that I can run with python manage.py process_tasks. This all works locally, but on my heroku app, for some reason it doesn't. I thought maybe inputting data is impossible from the heroku console, but if I run python manage.py shell on the heroku console, I can input data just fine. This is the code that inputs the data into the database: from background_task import background ... @background(schedule=5) def save_course_from_df(df): df = pandas.read_json(df) db = 0 for index, row in df.iterrows(): print("%s percent done!" % str(db / df.shape[0])) db += 1 values = dict(row) values = {key: values[key] for key in values.keys() if type(values[key]) != float or not math.isnan(values[key])} try: Course.objects.update_or_create( url=row['url'], defaults=values ) except IntegrityError: pass print('done!') I run this by opening the heroku console and running 'python manage.py process_tasks'. I get the print messages, and no error is being thrown. Still, my database doesn't change. I expected that after the task runs I would have a full table. Instead, nothing changed. -
From User can't query models.Model
When Using query from shell I got : >>> q = User.objects.get(username='TestUser') >>> q.agence Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'User' object has no attribute 'agence' From the admin interface, I have already assigned a choice. And I'm not able to see it with Query model : def CreateListDomaines(): nameQuery = Domaine.objects.all().values_list('nomDomaine', flat=True) domaines = [] i = 0 for q in nameQuery : l = (str(i),q) domaines.append(l) i+=1 return domaines def CreateListAgences(): nameQuery = Agence.objects.all().values_list('nomAgence', flat=True) agences = [] i = 0 for q in nameQuery : l = (str(i),q) agences.append(l) i+=1 return agences class Domaine(models.Model): nomDomaine = models.CharField(max_length=200,default=True) def __str__(self): return self.nomDomaine class Agence(models.Model): nomAgence = models.CharField(max_length=200,default=True,null=False,blank=False) Ville = models.CharField(max_length=200, default=True,null=True,blank=True) Region = models.CharField(max_length=200,default=True,null=True,blank=True) Departement = models.CharField(max_length=200,default=True,null=True,blank=True) AgencetelephonePortable = PhoneNumberField(null=True,blank=True) def __str__(self): return self.nomAgence class UserProfile(models.Model): domainesList = CreateListDomaines() agencesList = CreateListAgences() user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True) domaine = models.CharField(choices=domainesList,max_length=50, null=True, blank=True) agence = models.CharField(choices=agencesList,max_length=50, null=True, blank=True) def __str__(self): return self.user.username I'm currently not able to know which choice was assigned to the User model from the shell. -
Import Django class from view to another file
Good afternoon everybody, I'm fighting with my custom class defined in my Django view in order to use it inside another python file which let me to manage my Menu. This class is pretty simple, but she uses a custom middleware too: # main.views.py file class MyClass: def my_main_function(self, request): my_queryset = myModel.objects.filter(application=request.cur_app, display=True).order_by('order') return my_queryset def toto(self): list_test = self.list_of_edition() return list_test request.cur_app corresponds to my middleware defined in middleware.py file. I created toto() because I would like to use my_main_function inside another file called menus.py which doesn't handle request. In this file, I have: from .views.main import MyClass for element in MyClass.toto(): ... do something ... But this is the issue encountered: toto() missing 1 required positional argument: 'self' I'm conscient there is a possibility of huge issues in my code, because I'm learning programmation at the same time. Be indulgent. -
Why am I getting "'return' outside of function'" on this Django View?
This code, produces an error 'return outside of function'. All the other views in this file (views.py) are class based view (createview etc), but this view (the one I wrote from scratch) is throwing an error? class Submit(request): if request.method == "POST": submit_form = SubmitItemForm(data=request.POST) set_form = SubmitSetForm() if submit_form.is_valid(): item = submit_form.save() item.save() elif set_form.is_valid(): set = set_form.save() set.save() else: print(set_form.errors) submit_form = SubmitItemForm() set_form = SubmitSetForm() return render(request, 'curate/item_form.html', {'submit_form':submit_form, 'set_form': set_form }) -
I want to create a custom middleware with django-soet
I want to create custom middleware in my project. but I am getting this kind of error such as [ django.core.exceptions.ImproperlyConfigured: WSGI application 'custommiddle.wsgi.application' could not be loaded; Error importing module. ] . I think the problem might be python version, I am using 3.7 version . here is my folder structure. custommiddle --project name ' ' __init__.py settings.py urls.py wsgi.py cmiddle --app name ' ' ' middle --directory middleware.py __init__.py __init__.py admin.py apps.py models.py tests.py views.py in middleware.py I just kept the code like. from django.conf import settings class StackOverflowMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_exception(self, request, exception): if settings.DEBUG: print (exception.__class__.__name__) print (exception.message) return None in settings.py I configured as like, INSTALLED_APPS = [ 'soet' ] MIDDLEWARE_CLASSES = [ 'soet.middleware.StackOverFlowMiddleware' ] -
Edit doesn't update database
I am trying to edit some informations saved at my database. So from readAllNew.html I am calling edit button: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <table border="1"> <tr> <th>Naslov</th> <th>Datum</th> <th>Autor</th> <th>Mail</th> </tr> {% for x in data %} <tr> <td>{{x.naslov}}</td> <td>{{x.datumObjave}}</td> <td>{{x.autor}}</td> <td>{{x.email}}</td> <td><a href="{% url 'delete' x.id %}">delete</a></td> <td><a href="{% url 'edit' x.id %}">edit</a></td> </tr> {% endfor %} </table> </body> </html> From there this URL is calling (urls.py): url(r'^app_1/(?P<id>[-\w]+)/edit/$',views.edit, name = 'edit'), My views.py looks like: def edit(request, id): data = get_object_or_404(Clanak, id = id) if request.method == "POST": form = ClanakForma(request.POST) if form.is_valid(): data = form.save(commit=False) data.naslov = request.user data.datumObjave = request.user data.autor = request.user data.email = request.user return redirect('readAllNew.html') else: form = ClanakForma(instance=data) template = 'edit.html' context = {'form': form} return render(request, template, context) My models.py class Clanak(models.Model): naslov = models.CharField(null=False, blank=True, max_length=120) datumObjave = models.DateField(null=False, blank=False) autor = models.CharField(null=False, blank=True, max_length=50) email = models.EmailField(max_length=75, null=True, blank=True) def __str__(self): return str(self.naslov) + ', ' + str(self.datumObjave) + ', ' + str(self.autor) My forms.py: class ClanakForma(forms.ModelForm): class Meta: model = Clanak fields = '__all__' And my "edit.html": <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> So my view should call "edit.html" and … -
Trigger a function on file save
Consider this directory in app's root directory. less/ palette.less master.less How to trigger python function (that will accept path to file as argument) on save of one of the less/ directory files? Please, do not advice to install bloated modules for django. -
DRF serializer.to_representation() called four times; How to distinguish between them?
After discovering that the serializer.to_representation() is called four times for each detail page load in the DRF API Browser, I searched to find out why. I found this SO post. The single answer said... That's because you are using the browsable API. JSON renderer will only call it once. Browsable API needs several calls: 1. for the result itself 2. for the raw data tab when you can modify a resource through PUT 3. for the raw data tab when you can modify a resource through PATCH 4. for the HTML form tab My question is... how to distinguish between these four calls? I'm dealing with TextField(s). If the frontend hits the API to display a multi-line TextField on a detail page, we want to replace the newline characters with <br>. But if the frontend needs the value for a form field, it should get it without any replacements. -
How can user update their post in django rest UpdateAPIView
This is my Serializer class: class CountSerializers(serializers.ModelSerializer): class Meta: model = Count fields = ('id','userId', 'channelId', 'rate') This is urls.py to access the view path('count/<int:pk>', CountlListView.as_view()), This is my Views.py class CountlListView(ListAPIView): serializer_class = CountSerializers def get_queryset(self, *args, **kwargs): userId = self.kwargs.get('pk') queryset = Count.objects.filter(userId=userId) print(userId) return queryset If the user id 1 then the url will return all the post associated with user in the following format: [ { "id": 2, //a post id "userId": 1, //user id "channelId": 2, //another channeel id for which user vote "rate": 6 // rate(a value need to update by rest) }, { "id": 1, "userId": 1, "channelId": 1, "rate": 8 } ] here id is the post id in json. Now I want to update the data i.e. rate value in the post id 1 from 8 to 10. I have written the following class and url to update the data but I am failed to do so. Here is the code: update api view urls: path('count/<int:pk>/<int:pk>/update/', CountlUpdateView.as_view()), and here is the view class: class CountlUpdateView(UpdateAPIView): serializer_class = CountSerializers def get_queryset(self, *args, **kwargs): id = self.kwargs.get('pk') queryset = Count.objects.filter(pk=id) return queryset This is my college projects kindly help so that I update … -
Update model field after some period in Django
I want automatically update field status in my model after 14 days. Here is my model. I want to change status_of_renting to 0 after 15 days from date_of_rental (if date.today() if greater than date_of_return) class RentCar(models.Model): NORMAL = 1 PENALTY = 0 STATUS = ( (NORMAL, 'All is fine'), (PENALTY, 'Penalty for using car') ) car = models.ForeignKey('Car', on_delete = models.CASCADE, related_name = 'car') person = models.ForeignKey('Person', on_delete = models.CASCADE, related_name = 'client') date_of_rental = models.DateField(blank= True, default=timezone.now) date_of_return = models.DateField(blank= True, default=date.today() + timedelta(days=14)) status_of_renting = models.IntegerField(choices = STATUS, default = 1) def __str__(self): return f'{self.rental} - {self.car} / {self.client.fullname}' I can override def get_queryset() or dispatch in my generics.ListView, but I*m sure it's terrible decision. Is there some better solution to change the status in field status_of_renting. views.py class RentCatView(ListView): model = RentCar def get_queryset(self): self.model.objects.filter(Q(status_of_renting = 1)&Q(date_of_return__lte = date.today())).update(status_of_renting=0) return self.model.objects.all() -
Django Rest Framework - conditionally make serializer's field required or not using other field value
In my DRF project, I have a model: class Item(BaseModel): PRIVATE = 'PRIVATE' COMPANY = 'COMPANY' ACCOUNT_TYPES = ( (PRIVATE, _('Private')), (COMPANY, _('Company')), ) company_name = models.CharField(max_length=128, null=True, blank=True) person_name = models.CharField(max_length=128, null=True, blank=True) account_type = models.CharField(max_length=32, choices=ACCOUNT_TYPES) phone = models.CharField(max_length=128, null=True, blank=True) email = models.EmailField(max_length=128, null=True, blank=True) and ItemSerializer in serializers like: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('account_type', 'company_name', 'person_name') def create(self, validated_data): print('ItemSerializer, create') print('validated_data:', validated_data) return super().create(validated_data) def validate(self, attrs): print('ItemSerializer validate, attrs:', attrs) return attrs as you can see in the model, there are fields company_name and person_name, none of them is required in the model. To create an Item, account_type has to be specified. Its either PRIVATE or COMPANY. Now, in my serializer I want to make specific fields required if account type is company or private. For example, is account_type is COMPANY, I want to make field company_name required. If account_type is PRIVATE I want to make person_name required. Which method is a proper space to achieve this and how can I do this? Also using above logic I want to do extra validation on the field. Example: is account_type is PRIVATE and person_name is not empty, I want to … -
How do I get information then update the fields after running some logic on the data?
I want to run a python command that uses requests library. I am able to get the data from a django server, run some logic to check what it's states are then based on those results I would like to update the same data, I think I need to use requests.put() but I am not sure. Example of what my code does so far: def bar(): r = requests.get(url, headers=headers) data = r.json() for index in range(0, len(data)): print (data[index]['foo']) ... some logic here. ... if data[index]['foo'] == False: newURL = url + str(index) + '/' p = requests.put(newURL, headers=headers, data={'foo':True}) print (p.text) print (p.status_code) I am able to get data and compare but not update it to True if False is found. I know I'm probably doing something really wrong but would like the help. I do have my headers and url variables defined. I just don't want to share personal data.