Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the proper way to design a notification system database?
For example, I have following models class User(models.Model): username = ... avatar = ... class Article(models.Model): user = models.ForeignKey(User) title = ... content = ... class Comment(models.Model): user = models.ForeignKey(User) # 'Comment' or 'Article' target_type = models.CharField() target_id = models.IntegerField() content = ... class Like(models.Model): user = models.ForeignKey(User) # 'Comment' or 'Article' target_type = models.CharField() target_id = models.IntegerField() And the Notification: class Notification(models.Model): actor = models.ForeignKey(User) receiver = models.ForeignKey(User) # 'Comment' or 'Like' or '@' verb = models.CharField() # Where the notification happens source_type = models.CharField() source_id = models.IntegerField() is_read = ... time = ... source_type indicates which table I need to look up and source_id is the id of that object (it might be a Comment or a Like or something else) And I need serialize the notification as below: [ { "actor": { "username": "Yriuns", "avatar": null }, "verb": "Comment", "source": { "pk": 542, "user": { "username": "Yriuns", "avatar": null }, "content": "this is a reply", "time": "2018.11.30 02:38", "target": { "pk": 540, "user": { "username": "Someone", "avatar": null }, "content": "this is a comment" } }, "time": "2018-11-30 02:38:08", "is_read": false }, ... ] The problem is: I don't know the efficient way to query database(MySQL) to … -
Update database value after interaction with switch button. Django/HTML
I have simple 2 state button (checkbox but looks like switch button) in Django/HTML. This button is connected with BooleanField in my Model. Connected I'm mean that when I go to the specific view (with that button) it takes from database value of BooleanField and if it's False checkbox is unchecked and if it's True checkbox is checked. The problem is that I want to create communication in other way. I mean when I change state of this button It should update value of this BooleanField in database but I have no idea how to do it. models.py class TurnOnOff(models.Model): turnOnOff = models.BooleanField(default=False) class TurnOnOffForm(ModelForm): class Meta: model = TurnOnOff fields = ['turnOnOff'] views.py def getvalue(request): if request.method == 'POST': value = TurnOnOff.objects.first() else: value = TurnOnOff.objects.first() return render(request, "home.html", {'value': value}) urls.py urlpatterns = [ path('', views.getvalue, name='home'), ] home.html <script> function change(checkbox) { if (checkbox.checked) { alert("checked"); } else alert("unchecked"); } </script> <label class="switch"> {% if value.turnOnOff %} <input id="myCheck" type="checkbox" checked="checked" onclick="change(this)"> {% else %} <input id="myCheck" type="checkbox" onclick="change(this)"> {% endif %} <span class="slider round"></span> </label> -
django.core.exceptions.ImproperlyConfigured, Cannot find the circular import or issues in url
I followed the Django tutorial in the official website however I get the following error. polls/urls.py from django.urls import path from .views import index url_patterns = [ path('',index,name='index') ] Tut/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Dual axes in Django-nvd3 for lines Python Django
I am trying the demo project of the Django-nvd3. I tried to modify the sample in the view function where I replace the displaying values with the column of my csv. See the following: linewithfocuschart.htm: {% load nvd3_tags %} <head> {% include_chart_jscss %} {# Jquery CDN : Needed when using jquery_on_ready=True #} <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> {% load_chart charttype chartdata chartcontainer extra %} </head> <body> {% include_container chartcontainer 400 '100%' %} </body> views.py: def demo_linewithfocuschart(request): df_real_pred = pd.read_csv(r"logging/log2057.csv", sep=',',index_col = 0) xdata = range(len(df_real_pred.index)) yreal = df_real_pred.real0/df_real_pred.got0.max() ypred = df_real_pred.got0 # tooltip_date = "%d %b %Y %H:%M:%S %p" # extra_serie = {"tooltip": {"y_start": "There are ", "y_end": " calls"}, # "date_format": tooltip_date} extra_serie = {} chartdata = { 'x': xdata, 'name1': 'real', 'y1': yreal, 'extra1': extra_serie,'kwargs1': { 'color': '#a4c639' }, 'name2': 'predicted', 'y2': ypred, 'extra2': extra_serie,'kwargs2': { 'color': 'red' }, # 'name3': 'series 3', 'y3': ydata3, 'extra3': extra_serie, # 'name4': 'series 4', 'y4': ydata4, 'extra4': extra_serie } charttype = "lineWithFocusChart" chartcontainer = 'linewithfocuschart_container' # container name data = { 'charttype': charttype, 'chartdata': chartdata, 'chartcontainer': chartcontainer, 'extra': { 'x_is_date': False, 'tag_script_js': True, 'jquery_on_ready': False, } } return render_to_response('linewithfocuschart.html', data) The following is the graph that I am getting: See in the above image … -
How do I access a model outside of a view in Django?
I am creating a database site and one of the desired features is to have a button in the navbar that will that the user to a random object in a model. The Django Cookbook gives an example of a random function for a model, which I implemented. However, I cannot seem to call this function from the navbar, since the navbar is in a separate html file that is included above the {% block content %}, which allows it to appear on every page of the site. However, this means it never sees the model object itself, so I cannot access the function with {{object.get_random}} in the navbar. One idea I had was to use a link in the navbar like this <a href="{% url 'roma:category_list.object.get_random.get_absolute_url' %}">Random Category</a> where category_list is the view that has the model passed to it. From there I hoped to grab an object from the model, then the get_random function, and finally the url from the object returned from the get_random function. This obviously does not work. Is there a solution that will allow me to access the function in the navbar html? -
django_select2 widget get "No results found"
I'm using django_select2 "ModelSelect2Widget" and get on html-form "No results found". What is wrong? models.py class Department(Catalog): name = models.CharField(max_length=50, unique=True) class Person(Catalog): surname = models.CharField(max_length=50) name = models.CharField(max_length=50) department = models.ForeignKey(Department, on_delete=models.PROTECT) forms.py class MyWidget(ModelSelect2Widget): model = Department search_fields = ['name__icontains', ] class PersonForm(ModelForm): class Meta: model = Person fields = ['surname', 'name', 'department'] widgets = {'department': MyWidget} -
Pycharm: How can I apply the existing virtual env into a project?
I just started to use Pycharm but it doesn't recognize Django. I already created virtualenv folder in my project and want to apply it into my project but I don't understand how to do it. What I did is go to Settings -> Project -> Intepreter -> and I tried to add virtualenv folder in my project but couldn't (apply button doesn't work). Instead I added virtualenv/Scripts/python.exe in my User folder. But nothing changed. How can I do it? Actually something changed. Scanning installed packages was too long but just finished and now warning message like Package requirement ... But I already installed them into virtualenv in my project. -
Access url parameters within the template
I override the SimpleListFilter And I ended-up with make a form in my template my site have a search function too, so if I do a search, the url becomes like http://url/corelog/?q=nda and when I use the list filter, url looks like http://url/corelog/?scoreRange=0.2-1 It erase the search term from my url parameters I want to be my url like http://url/corelog/?q=nda&scoreRange=0.2-1 so I tried to use hidden field to keep those values, and that wasn't working as I expected. I am using context_processors. Try to access them like {{request.GET.q}} in my template is not giving me anything. How can I acquire these url parameters within template admin.py class RangeFilter(admin.SimpleListFilter): title = 'Score' parameter_name = 'scoreRange' template = 'admin/corelog/input_filter.html' def lookups(self, request, model_admin): return ( ('Yes', ''), ) def queryset(self, request, queryset): .. return queryset input_filter.html {% block content %} <h3>{% blocktrans with filter_title=title %} By {{ filter_title }} {% endblocktrans %}</h3> <ul> <li> <form> <p> {% for key, value in request.GET.items %} <input type="text" name="{{ key }}" value="{{ value }}"> {% endfor %} <label >「スライダーで下限と上限を設定後、下のボタンを押してください。」</label> <div id="slider-range"></div> <label style="font-weight: bold;">検索:</label> <input type="submit" id="scoreRange" name="scoreRange"> </p> </form> </li> </ul> {% endblock %} -
Calling a post to activate a django function periodically
This is a rookie question on web development. I am trying to find a secure and better way for developers to call and run a function that sends emails out from my django application that they can override and send manually as well as also can be time activated thus sending the email periodically at fixed times of the week. I found answer suggesting the use of celery on Running a function periodically in Django But I want to change the periods without redeploying my application. I have done some research on aws tools and I think a combination of AWS gateway and aws lambda and aws cloudwatch to send a url/endpoint (or get request) to my web app to activate the function. At the moment I have something like below. views.py def api_send_email(request): #insert send email function print ("sending") return redirect('/') urls.py urlpatterns = [ url(r'^send_email$', api_send_email, name="api_send_email"), ] So the above can either manually be triggered by going to the url https//xxx/send_email or by is sending a get request to that url periodically from aws. I have thought about doing a post request instead which will make it more secure but I am not sure if the aws … -
Javascript on Python Django, hosted on pythonanywhere
I'm teaching myself Django, and decided to try out some JS functionality. I included a simple text-changing function (from w3schools) in a JS script to try things out. The app is blog, and the JS script lives in blog/static/blog/test.js. There's only one function in there: function myFunction() { document.getElementById("demo-btn").innerHTML = "Text changed."; } Which is linked to a button in blog/templates/blog/post_list.html, id="demo-btn". Website live here: http://andreyito.pythonanywhere.com It works fine on my localhost, but when I push it to pythonanywhere, nothing happens (clicking on the Click me button is supposed to change the text just above the button.) This feels like a minor thing that I'm leaving out, but I haven't been able to easily troubleshoot this. Repo here:https://github.com/Don86/djgirls -
Get time based model statistics in django
I know this is not a django question per say but I am working with django models and would like to have a solution specific to django Suppose I have a model like this class Foo(models.Model): type = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) Now what is the best method get a count of all objects of type(say 1) spread over date/time For example: get_stat(type=1) gives me information on how many objects(of type 1) were created on 12/10/2018, on 13/10/2018, 14/10/2018 and so on... -
many to many fields to json in django channels
my signals.py: @receiver(post_save, sender=HubNotify) def create_task_verification_notification(sender, instance, created, **kwargs): if instance: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "gossip", {"type": "hub.notify", "event": "Hub Notify", "sender": instance.sender.id, "accept_hub_url": resolve_url("student:accept_hub", pk=instance.receiver.hub.id, notify=instance.sender.id), "reject_hub_url":resolve_url("student:reject_hub", pk=instance.rceiver.hub.id, notify=instance.sender.id), "notification":instance.notification }) My consumers.py: async def hub_notify(self, event): await self.send_json(event) print("Got message {} at {}".format(event, self.channel_name)) My views.py where im creating HubNotify object: excoms= User.objects.filter(hub_position="E") | User.objects.filter(hub_position="L") obj=HubNotify.objects .create(sender=user,notification=request.user.username + ' Wants to join hub ') messages.warning(request, 'Request sent') obj.receiver.add(*excoms) obj.save() Im trying to create real time notifications using django-channels.For this im using signals to check if notification is created and sending data to front end.. The problem is that receiver is a many to many field and i cant serialize this to json.. This is basically a hub join request where a user can send request to join hub which is sent to multiple users and anyone can accept or reject it.How modify my accept_hub_url and is_reject_url and my consumers for this to work as intended? the pk parameter in accept_hub_url is basically request.user.hub.id .HOw do i access request.user here? -
TypeError: 'encoding' is an invalid keyword argument for this function - How do I solve it?
I was trying to create an auto chatbot with bothub. It's a very new experience for me and I am stuck here I wish that I could find an answer here. JamesLees-MacBook-Pro:kakaotalkchatbot root# bothub logs Traceback (most recent call last): File "/usr/local/bin/bothub", line 11, in <module> sys.exit(main()) File "/Library/Python/2.7/site-packages/bothub_cli/main.py", line 539, in main cli() File "/Library/Python/2.7/site-packages/click/core.py", line 721, in __call__ return self.main(*args, **kwargs) File "/Library/Python/2.7/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/Library/Python/2.7/site-packages/click/core.py", line 1065, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Library/Python/2.7/site-packages/click/core.py", line 894, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Library/Python/2.7/site-packages/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "/Library/Python/2.7/site-packages/bothub_cli/main.py", line 497, in logs log_entries = lib_cli.logs() File "/Library/Python/2.7/site-packages/bothub_cli/lib.py", line 291, in logs self._load_auth() File "/Library/Python/2.7/site-packages/bothub_cli/lib.py", line 298, in _load_auth self.config.load() File "/Library/Python/2.7/site-packages/bothub_cli/config.py", line 46, in load with open(self.path, encoding='utf8') as fin: TypeError: 'encoding' is an invalid keyword argument for this function This is what I am getting and I cannot proceed from this TypeError: 'encoding' is an invalid keyword argument for this I would at least like to know what is the problem It's still okay if it's not solvable I would love to get suggestions with chatbot too Thanks. -
How to pass three or multiple arguments to custom template tag filter django?
How to send there arguments in @register.filter(name='thumbnail') template tag. I am using image resize function have contain 2 args image object and size now i want to pass third argument folder_name but i can't able to find the solution its gives error Could not parse the remainder: below are function which is template tag file and template. Template Tag function @register.filter(name='thumbnail') def thumbnail(file, size='200x200',folder_name='users_images'): x, y = [int(x) for x in size.split('x')] # defining the filename and the miniature filename filehead, filetail = os.path.split(file.path) basename, format = os.path.splitext(filetail) miniature = basename + '_' + size + format #filename = file.path #print(filehead+'/users_images/'+filetail) if os.path.exists(filehead+'/'+folder_name+'/'+filetail): filename = filehead+'/'+folder_name+'/'+filetail filehead = filehead+'/'+folder_name+'/' else: filename = file.path #print(filename) miniature_filename = os.path.join(filehead, miniature) filehead, filetail = os.path.split(file.url) miniature_url = filehead + '/' + miniature if os.path.exists( miniature_filename ) and os.path.getmtime(filename) > os.path.getmtime( miniature_filename ): os.unlink(miniature_filename) # if the image wasn't already resized, resize it if not os.path.exists(miniature_filename): image = Image.open(filename) new_image = image.resize([x, y], Image.ANTIALIAS) # image.thumbnail([x, y], Image.ANTIALIAS) try: # image.save(miniature_filename, image.format, quality=90, optimize=1) new_image.save(miniature_filename, image.format, quality=95, optimize=1) except: return miniature_url return miniature_url Template File I have tried 2 different type {{ contact_list.picture|thumbnail:'200x200' 'contacts'}} {{ contact_list.picture|thumbnail:'200x200','contacts'}} If any one have solution please help me. … -
Whenever null is forced into model's field, go to default string
I have a model like this: class Test(models.Model) name = models.CharField(max_length=30, default="Unassigned") Whenever this model's instance is being saved with None in the name field, I want the instance to be saved with "Unassigned" instead. But if I do this: >>> test = Test() >>>test.name = None >>>test.save() It will currently fail with django.db.utils.IntegrityError: NOT NULL constraint failed: explorer_api_test.name on the last line, because obviously the name field does not allow nulls (there is no null=True in it). But if I allow nulls, it will not save with default "Unassigned", but with None instead. How do I change the model definition so that whenever its instance is trying to be saved with None in the field, it is saved with default string instead? Outside of model definition, I could do this: >>>test = Test() >>>test.name = None >>>if test.name is None: >>>...test.name = "Unassigned" >>>test.save() but I prefer to have this logic in model itself. -
How does Django work with either instance id and instance itself?
For instance django queryset's filter takes either instance or instance_id. Probably django code needs id for Database query, and it extracts instance_id when it receives instance Although I don't remember, there could be a scenario where django would want instance but receives instance_id . How does django handle such cases? just do typechecking with isinstance(something, models.Model) and do something with it? -
Best approach to edit Mongo document from django POST API without exposing "_id"
I have a list of mongo documents at my UI, where at backend usually through "_id" I search and edit the respective document, But I want to know without exposing "_id" is there any better approach to edit it, because any one can forge by just increment the value of "_id" -
How to filter data from bokeh widget in Django
I'm having trouble getting the CustomJS to filter data in Django. Here I have two plots and one Select. I'm trying to get the select value to filter the data by name and display in the second plot. I'm not familiar with Javascript. This plots the first plot successfully but the select has no effect. Any help would be appreciated. names = ['Adam','Bella','Chaz','Duran','Eddy','Frank','Gallagher','Hen'] size=100 df2 = pd.DataFrame(data={ 'someone': np.random.choice(names, size=size, replace=True), 'metric': np.random.randint(0,10000, size=size), 'metric2': np.random.randint(0,10000, size=size), }) source2 = ColumnDataSource(df2) source3 = ColumnDataSource(data=dict(someone=[],metric=[],metric2=[])) plot = figure(plot_width=300, plot_height=300) plot.circle(x='metric', y='metric2', size=5, source=source2) plot2 = figure(plot_width=300, plot_height=300) plot2.circle(x='metric', y='metric2', size=5, source=source3) cb_testing = CustomJS(args=dict(s2=source2, s3=source3), code=""" var f = cb_obj.value; var d2 = s2.data; var d3 = s3.data; d3['someone'] = [] d3['metric'] = [] d3['metric2'] = [] for (var i = 0; i < d2['someone'].length; i++){ if (d2['someone'] == f){ d3['someone'].push(d2['someone'][i]) d3['metric'].push(d2['metric'][i]) d3['metric2'].push(d2['metric2'][i]) } } d3.change.emit(); """) selecttesting = Select(title="Select Name", options=names, callback=cb_testing) l4 = layout([ [selecttesting, plot, plot2] ]) script4, div4 = components(l4, ) -
Map home to django admin
I am using django 2.0.6 with apache2 and mod_wsgi. I would like to map the home url to admin of my application (an internal application which only has the admin and no public interface). The following code in url.py works when I am using django's runserver but does not work when I use apache2 with mod_wsgi urlpatterns = [ path('', admin.site.urls), ] When using apache2 with mod_wsgi, I get redirected to /cgi-bin/webproc saying "Not Found". The following works with both django's runserver as well as mod_wsgi urlpatterns = [ path('admin/', admin.site.urls), ] Would be grateful if anyone could help. -
In Django, how can I programmatically check that an IntegrityError is related to a particular uniqueness constraint of the model?
For example, if I have this model: # foo/models.py # Python standard library from uuid import uuid4 # Django from django.db import models class Foo(models.Model): uuid_1 = models.UUIDField(default=uuid4, unique=True) uuid_2 = models.UUIDField(default=uuid4, unique=True) And then I create instances of it: # Python standard library from uuid import uuid4 # Django from django.db import IntegrityError # foo app from foo.models import Foo const_uuid_1 = uuid4() const_uuid_2 = uuid4() first_foo = Foo.objects.create(uuid_1=const_uuid_1, uuid_2=const_uuid_2) # violate `uuid_1` uniqueness try: Foo.objects.create(uuid_1=const_uuid_1) except IntegrityError as e: pass # violate `uuid_2` uniqueness try: Foo.objects.create(uuid_2=const_uuid_2) except IntegrityError as e: pass So how can I tell the two uniqueness violations apart, programmatically? In my application, business requirements dictate that my program is allowed to automatically handle and correct one of the violations, but not the other (which must be reported back to the user). -
Reducing depth of json return by DRF
I have json API returned as below format. But I want to return json API decomposing namingzone key as specified below. Could anyone tell me how I can revise serializer to achieve this? serializer.py is also specified below. For models.py and views.py, please refer to my previous post. current { "zone": { "zone": "office_enclosed", "namingzone": [ { "naming": "moffice" } ] }, "lpd": 11.9, "sensor": true }, { "zone": { "zone": "office_open", "namingzone": [ { "naming": "off" }, { "naming": "office" } ] }, "lpd": 10.5, "sensor": true } Target { "zone": "office_enclosed", "naming": "moffice", "lpd": 11.9, "sensor": true }, { "zone": "office_open", "naming": "off", "lpd": 10.5, "sensor": true }, { "zone": "office_open", "naming": "office", "lpd": 10.5, "sensor": true } serializer.py class namingNewSerializer(serializers.ModelSerializer): class Meta: model=Naming fields=('naming',) class zoneSerializer(serializers.ModelSerializer): namingzone=namingNewSerializer(many=True) class Meta: model=Zone fields = ('zone','namingzone') class lightSerializer(serializers.ModelSerializer): zone = zoneSerializer() class Meta: model=Light fields = ('zone','lpd','sensor') class namingSerializer(serializers.ModelSerializer): zone=zoneSerializer() class Meta: model=Naming fields=('zone','naming') -
How can one return offloaded process response from celery?
I work on web application that generates pdf, it returns generated pdf file. Previously I handled the pdf generation in the main process. My superior told me, that will potentially cause the app to stall, as django is synchronous. So he suggest offload the process to celery, I tried it and have the idea about how to process it using celery. But I can't figure out the how to return the response to the client. I can return response that it's being processed, but what about the pdf file? return the possible url too? and send request every now and then? -
BASE_DIR outputs correct using print, but in a variable it just outputs C:
If im using print on base_dir = settings.BASE_DIR it outputs everything correctly. However when I use this variable to create a new variable using os.path.join, it just outputs C: Print example: C:\Users\me\Google Drive\gitlab\rootfolder Example on code where it just outputs C: and the paths after which shows up correct. blendfile = os.path.join(base_dir, '/var/media', userpathname, newest).replace("\\", "/") Comes out as: C:/var/media/userpathname/newest -
Django chatbot using Django channels
I am planning to create a simple "dialog trainer" using Django. I came across Django channels and noted that there are good resources available for django channels chat applications. I wish to know if there is a good resource which explains each step when developing a bot-server using Django as the back-end. The proposed chatbot has predefined set of questions and answers. I am going to populate the predefined questions/answers using a json file. If you know a good starting point where it explains, how to structure the project, reasoning for each step, please do share it here. Thanks -
How I can serialize information across 3 tables in DRF?
I have 3 tables(2 tables are belonging to 1 table using ForeignKey). I could create queryset across 3 tables. However, I cannot get naming table information from serialized return data as below. Could anyone tell me how I should revise serializer? views.py class lightData(generics.ListAPIView): serializer_class = lightSerializer pagination_class = None def get_queryset(self): certificate = self.kwargs['certificate'] return Light.objects.prefetch_related('zone__namingzone') models.py class Zone(models.Model): zone=models.CharField(max_length=20) conditioned=models.BooleanField(default=True) def __str__(self): return self.zone class Light(models.Model): zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='lightzone') lpd=models.IntegerField() sensor=models.BooleanField(default=True) class Meta: unique_together = (('certificate', 'zone'),) def __str__(self): return str(self.certificate)+"_"+str(self.zone) class Naming(models.Model): zone=models.ForeignKey(Zone, on_delete=models.CASCADE,related_name='namingzone') naming=models.CharField(max_length=20) def __str__(self): return str(self.zone)+"_"+self.naming serializer.py from rest_framework import serializers from .models import Certificate,Zone,Light,OA,Naming class zoneSerializer(serializers.ModelSerializer): class Meta: model=Zone fields = ('zone','conditioned') class lightSerializer(serializers.ModelSerializer): zone = zoneSerializer() class Meta: model=Light fields = ('zone','lpd','sensor') class namingSerializer(serializers.ModelSerializer): zone=zoneSerializer() class Meta: model=Naming fields=('zone','naming')