Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reducing Django's rendering time
I wanted to render 100 items on the page but it took 14050.60ms. Is there any ways to reduce the rendering time in Django? -
Two fields related in Django
I need to update my table every time a new value of "sku" is entered (not to create a new entry), but it does have to happen only if the "client" selected is the same. If the "client" is different, then the model should add a new object with the same "sku", but with different "clients". I have tried to do the following in my models.py: class ProductList(models.Model): id_new = models.IntegerField(primary_key=True) sku = models.CharField(primary_key=False, max_length=200) client = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=256) description = models.CharField(max_length=1000) storage = models.CharField(max_length=256) cost_price = models.CharField(max_length=256) sell_price = models.CharField(max_length=256) ncm = models.CharField(max_length=256) inventory = models.IntegerField(null=True) class Meta: unique_together = (('sku', 'client'),) But it is not working. How can I make that work? -
Any Database update refreshes React + Django app
I'm currently a beginner with React and I'm currently building a React application that is run on top of Django Framework. My strategy is that I have a single Django template where I attach the whole React application. Basically in my urls.py in Django, I have a list of URLS for all my REST API's and a URL for the single template. I have been stuck with this for quite sometime. There's this weird behavior where any update I do with the database refreshes the website, whether this update is through a form in React (even though I do e.preventDefault()) or doing an update in the Django built-in admin panel page (either Creating, Updating, or Deleting something). I don't exactly know what to share with you (i.e. which part of my code) because I don't even know what the problem is in the first place, but I would be happy to comply to any of your requests. Thank you in advance! -
Read message from django channel while unit testing
I'm writing unit tests for a python method which makes use of Celery worker and Django Channels. Python method @task(name="export_to_caffe", bind=True) def export_caffe_prototxt(self, net, net_name, reply_channel): net = yaml.safe_load(net) if net_name == '': net_name = 'Net' try: prototxt, input_dim = json_to_prototxt(net, net_name) randomId = datetime.now().strftime('%Y%m%d%H%M%S')+randomword(5) with open(BASE_DIR + '/media/' + randomId + '.prototxt', 'w+') as f: f.write(prototxt) Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'success', 'action': 'ExportNet', 'name': randomId + '.prototxt', 'url': '/media/' + randomId + '.prototxt' }) }) except: Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'error', 'action': 'ExportNet', 'error': str(sys.exc_info()[1]) }) }) I have added the python method for which I have to write the tests. So basically what I need to do in unit testing is that I need to open that file which is being generated by the python method export_caffe_prototxt and read the contents of the file and then match it with the desired output. But I'm not able to figure out how do I get that file URL because the method is not returning this URL, it's rather sending a message to the channel so how do I read the message and derive the URL? If someone can write a sample test case for this, it'd be great. Thank you -
How to use VUEJS in Django WITHOUT npm/nodes
I have a huge problem. Please do not judge if it is obvious for you, but I did not develop in JS for years. So here is the context: I have a Django Rest API (which works fine) with Django Rest Framework. The aim of my app is to use VueJS as frontend (and so, execute API Calls). BUT here a constraint: I cannot use npm/node, but only import the scripts in my Django server (in /static obviously) and inport them in the index.html file thanks to the Django template render. Imports works fine, but only these imports (I had to take care to change VueJS delimiter because they are in conflict with Django ones). Anyway, I want to use VuesJS components to store each resource instance and, as my colleague asked me, see/check if we could implement a generic routing (I instantly thought yes with vue-router which was well imported as well). But I have issues while I try to create separate files for the router and the components: I always have import issues. So to ask a concise question: Is it possible to make Django and VueJS work together without node and npm ? And so, can someone … -
Django. Check `unique_together` only if both Model fields were provided for create and update calls
I need to check unique_together only in case both fields were supplied to admin creation Form or via API request for both create and update calls. In case this happens and fields are not unique_together I need to propagate Exception to django-admin creation Form and RestFramework's Serializer/ViewSet. Here's a simplified example of my model: class MyModel(models.Model): time = models.TimeField(null=True, blank=True) date = models.DateField(null=True, blank=True) some_other_field = models.BooleanField(default=False) ... As you can see at the level of model both time and date are not required and are nullable. Application logic on the other hand requires at least one of those fields to be provided and if both are supplied – this pair should be unique for entire table to avoid duplication of datetime composition. This model is accessed through these nodes: django-admin and DjangoRestFramework's endpoint using ViewSet. Creation of new record does not seem to be a problem from API perspective, I can override validate method of Serializer: def validate(self, data): if not data.get('time') and not data.get('date'): raise serializers.ValidationError( "At least one of this fields is required: time, date" ) if OpenTable.objects.filter( time=data.get('time'), date=data.get('date')).exists(): raise serializers.ValidationError('Duplicates for date or datetime not allowed') return data But this becomes a problem when I … -
Post method in angular giving error 406 (Not Acceptable)
I am trying to call post XML data in angular & get posted XML in python(Django) and save it to mongodb, but its giving mi error 406 (Not Acceptable) and detail":"Could not satisfy the request Accept header. In component.ts : let headers = new Headers(); headers.append('Content-Type', 'application/xml'); headers.append('Accept', 'application/xml'); let body = '<?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Dont forget me this weekend!</body> </note>'; this.http.post(url, body, { headers: headers }) .subscribe(data => { console.log(data); }); In views.py def post(self, request): original_response = request.data save_response = LenderResponse(lender_response=str(original_response)) return Response(original_response) -
Django: method in view " if ... is '...': " is not working [duplicate]
This question already has an answer here: Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? 14 answers i'm searching for a few days and i can't find any help. I'm new in django and i'm playing around to learn it. My problem is that the users are loggedin but after that, they have to log in with a specific ID to get those contents. For example, me is logged in as bender and now i have to log in with an id to get to more content. I tried to check these ID's in my views. Here's an example: def check_in(request): if request.method=='POST': user_id = request.POST['user_id'] if user_id is '662532': return HttpResponseRedirect("/test/new/content/") else: return HttpResponse("False, there went something wrong.") The error-handling and the HttpResponseRedirect might not be that professional but in this case it returns the else-statement and not the if-statement. If i change the code in if user_id is not "...": it gives me the HttpResponseRedirect commando. What can i do? Thank u guys -
forum on an intranet share drive?
I work for a major company, and in said company, each division has access to their own share drive (lets call it L:). In an ideal world, We would have access to share point or a wiki we could communicate through so we would all know where to find that one f**kn reference file that someone found that one time. But corporate said no, stick to the L: drive. So I want to covertly create a forum or a BBS style app on the L: drive for everyone in my division to communicate and ask questions on. At This point i'm at a loss for what to even look for. I considered a Django web app in standalone mode, but that requires its own server. I considered PHPBB, but again, the server. Sugestions? -
How to add extra validation to Waffle App in Django?
I'm using Waffle App in Django to use FeatureFlags. I'd like to force users to always add a description in the "Note" field, which is by default allowed to be left blank. I think I can do this using a form validation probably creating a clean_note() function, that I should add to the corresponding FormView. Has anyone done something similar before? -
Creating automatic objects in the Database (Django)
i am working on train booking system project and i want to access the seat number and location so i made a seats class that will help. the issue is that i want when the admin adds a new train from the admin panel the seats class automatically adds 100 seat into the DB because i don't think it makes any sense that the admin will add the 100 seat manually -
Django Statics not accessible (Digital Ocean)
I've build a Django site on a Digital Ocean droplet but the static files seem to be inaccessible. Looking around for solutions I've think the problem lies in the server settings (Nginx), but as this is even newer for me I would like to verify this before I mess it up. The CSS is placed within `django_project/static/css', this folder is not accessible using a browser (IPadress/static/css/style.css serves a '404 Not Found' error on the CSS). -
Why use URL parameters over request body in API?
When making an API endpoint in Django Rest Framework for example, why would I ever use URL parameters to receive data rather than just putting everything in the request data? I don't get the difference between the two. -
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?