Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework custom schema for view in viewset
I have an API built using Django and Django REST Framework. I have a model that returns some JSON that is built that doesn't correspond to a typical Django model. So the auto-documentation feature that seems to utilize knowledge about Django models doesn't work for some of my views. In particular, I have a viewset that returns some typical API views (like a list of objects), and some views that return some of my custom objects. I'd like to build documentation for these custom objects, but I am not sure how to override the schema for a particular endpoint within a viewset. How can I override the schema generated for a single view in a DRF viewset? DRF seems to provide this functionality for views, but I want to do the same for Viewsets. -
View articles by author in Django blog
I'm trying to create a view that allows one to see all blog posts written by a particular author. Here's the URL pattern I'm using: url(r'^user/(?P<username>[\w-]+)/$', views.user_articles, name="user_articles"), And here's my view: def user_articles(request, username): articles = Article.objects.filter(author=username).order_by('-date') return render(request, "articles/article_list.html", {'articles': articles}) This is returning the error: ValueError at /articles/user/danny/ invalid literal for int() with base 10: 'danny' Editing to add model as well: class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) body = HTMLField('Body') date = models.DateTimeField(auto_now_add=True) thumb = models.ImageField(default="keys.jpg", blank=True) author = models.ForeignKey(User, default=None) danny is a valid username, and it should be a string, not an integer, so I'm not sure what's going wrong here. Any ideas? -
Why does Pagination not work on GenericAPIView?
views.py class variable__list(ListAPIView): """ get: returns a list of variable names """ serializer_class = VariableSerializer pagination_class = PageNumberPagination page_size = 5 def get_queryset(self): return Variable.objects.all() def get(self, request, format=None): # base queryset queryset = self.get_queryset() # return serialized data if queryset.exists(): serializer = VariableSerializer(queryset, many=True) return Response(serializer.data) else: return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND) settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5, } When I go to the endpoint api/v1/variable/?page=1, I get the same list returned of 100 results. My understanding is this should automatically be working when I set the pagination globally in settings.py, on top of that I have ALSO defined the paginator at the class level and still nothing is being paginated. What am I doing wrong here? -
Trouble getting POST input trough jQuery Dual Boxes in Django 2.0
i'm using THIS script to select multiple options in my Django Project. My code is like this: <form method="POST" id="demoform" action="/gestionPDD/HabilitarPDD" > {% csrf_token %} <select multiple="multiple" size="10" name="duallistbox_demo1[]" title="duallistbox_demo1[]"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3" selected="selected">Option 3</option> <option value="option4">Option 4</option> <option value="option5">Option 5</option> <option value="option6" selected="selected">Option 6</option> <option value="option7">Option 7</option> <option value="option8">Option 8</option> <option value="option9">Option 9</option> <option value="option0">Option 10</option> <option value="optionA">Option 10</option> <option value="optionB">Option 10</option> <option value="optionV">Option 10</option> <option value="optionD">Option 10</option> </select> <br> <button type="submit" class="btn btn-default btn-block">Submit data</button> </form> <script> var demo1 = $('select[name="duallistbox_demo1[]"]').bootstrapDualListbox(); $("#demoform").submit(function() { alert($('[name="duallistbox_demo1[]"]').val()); return false; }); </script> The problem is when you click submit button, a pop-up confirmation appears and when you click SEND nothing happens. My views are okay, and server doesn't get any response from that button. If you change the return value in the script (False to True) it actually works and server get a POST request (with all selected options), but you can't cancel the pop-up; When you click submit button and check in the pop-up if you select something wrong you can't go back, the request is sent anyway. Any idea of how to fix it? -
Foreign key serializer update method
I have following models: class Card(models.Model): thing = models.CharField(max_length=50, blank=True, null = True, ) class Responsibility(models.Model): name = models.CharField(max_length=50, blank=True, null=True, ) card = models.ForeignKey(Card, related_name='responsibilities', blank=True, null=True, on_delete=models.CASCADE) class Collaborator(models.Model): name = models.CharField(max_length=50, blank=True, null=True, ) card = models.ForeignKey(Card, related_name='collaborators', blank=True, null=True, on_delete=models.CASCADE) And my serializers: class CollaboratorSerializer(serializers.ModelSerializer): class Meta: model = Collaborator fields = '__all__' class ResponsibilitySerializer(serializers.ModelSerializer): class Meta: model = Responsibility fields = '__all__' class CardSerializer(serializers.ModelSerializer): responsibilities = ResponsibilitySerializer(many=True,) collaborators = CollaboratorSerializer(many=True,) class Meta: model = Card fields = '__all__' def create(self, validated_data): responsibilities_data = validated_data.pop('responsibilities') collaborators_data = validated_data.pop('collaborators') card = Card.objects.create(**validated_data) for responsibility_data in responsibilities_data: Responsibility.objects.create(card=card, **responsibility_data) for collaborator_data in collaborators_data: Collaborator.objects.create(card=card, **collaborator_data) return card Create and get are successful, I am not sure how to implement update() method for Card. Sample request.data looks like following: {u'collaborators': [{u'id': 8, u'card': 12, u'name': u''}, {u'name': u''}, {u'name': u''}], u'responsibilities': [{u'name': u'Name'}, {u'name': u'Age'}, {u'name': u'Address'}], u'id': 12, u'thing': u'Reader'} In my update method, I would like to first delete all responsibilities and collaborators of that specific card, and then create fresh from the data received. -
Django foreign key pk in url as a parameter
I'm trying to call a foreign key pk in url as argument like: <a href="{% url 'home' msg.user.pk %}">Go</a> But it fails. Instead of, if I use {{ msg.user.pk }} in the template it works and I can see the pk. The model is: class Message(models.Model): text = models.CharField(...) user = models.ForeignKey(User, ...) Urls: url(r'^home/(?P<pk>[0-9]+)/$', views.home, name='home'), The error: Reverse for 'home' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['home/(?P<pk>[0-9]+)/$'] -
N duplicated queries nested model
I've got an Area model allowing sub areas (you might think of it as categories with subcategories). I reached this by nesting one field to self as foreign key. class Area(models.Model): area = models.CharField(max_length=120) parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='subarea') def __str__(self): return self.area With the django rest framwork I've manages to get the correct output. The problem is that when I analyze the request with django-toolbar multiple duplicated requests are made (N*Area(parent=None)). I've solved similar issues by using prefetch_related or select_related. But never done it with a nested model. Is there any way to solve this? Or is this design of the model bad? I manage to serialize the correct output with the following view and class ListArea(generics.ListCreateAPIView): serializer_class = AreaSerializer queryset = City.objects.prefetch_related('parent').filter(parent=None) and serializers class SubAreaSerializer(serializers.ModelSerializer): class Meta: model = Area fields = ('area','id') class AreaSerializer(serializers.ModelSerializer): subarea=SubAreaSerializer(many=True) class Meta: model = Area fields = ('area','id','subarea') Or might those extra calls be due to the browsable API? -
Django Haystack - initial value for fields in overriden SearchForm not being displayed
On a site I've been running for years, I just upgraded both Django and Haystack from 1.11.5 and 2.6.1, respectively, to 2.0.5 and 2.8.1, respectively. Everything with the upgrade seems to have gone smoothly except that the initial values I'm providing in the overriden SearchForm are not being used anymore. I can't figure out why. I posted an issue on Haystack's issue tracker here, but I haven't received a response, so I'm hopeful someone here might have some insight. Here's the form: from haystack.forms import SearchForm class SearchForm(SearchForm): start_date = forms.DateField(initial=Post.get_first_post_timestamp(), input_formats=['%Y-%m-%d']) end_date = forms.DateField(initial=datetime.date.today, input_formats=['%Y-%m-%d']) thread_type = forms.ChoiceField(choices=[('All Types', 'All Types')] + Thread.get_sorted_unique_types_choices()) Here's the view: import haystack.generic_views from apps.listserv.forms import SearchForm class SearchView(haystack.generic_views.SearchView): template_name = 'listserv/search.html' form_class = SearchForm results_per_page = 10 Here's the template: ... [{{ form.start_date.value }}] <form action="." method="get"> <p style="text-align: center; font-weight: bold;">Search: {{ form.q }}</p> <p style="text-align: center; font-weight: bold;">Dates: {{ form.start_date }} to {{ form.end_date }}</p> <p style="text-align: center; font-weight: bold;">Thread Type: {{ form.thread_type }}</p> <p style="text-align: center;"><input type="submit" value="Search"></p> </form> ... Here's a screenshot of the resulting render: As you can see, neither date is being displayed. Note that prior to the upgrades, this did work. I'm wondering if something has … -
Django rest frmework different querysets at one page
How can I connect the output of lists of a particular model, whose instances are filtered by different fields? For example, I have an Places model and two different url. In one, the entire list is displayed, and in the other only the instances with new_place = True. Do an API using django-filter. models.py class Places(models.Model): main_photo = models.ImageField(upload_to = 'album/') place = models.CharField(max_length=100) new_place = models.BooleanField(default = True) serializer.py class PlaceSerializer(ModelSerializer): url = HyperlinkedIdentityField( view_name='places_api:detail', lookup_field='pk' ) class Meta: model = Places fields = ( 'url', 'id', 'main_photo', 'name', 'new_place', ) full_list_views.py class PlacesListAPIView(ListAPIView): queryset = Places.objects.all() serializer_class = PlaceSerializer new_places_views.py class PlacesNewListAPIView(ListAPIView): queryset = Places.objects.all() serializer_class = PlaceSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('new_place',) urls.py url(r'^new/$', views.PlacesNewListAPIView.as_view(), name = 'list_new'), url(r'^$', views.PlacesListAPIView.as_view(), name = 'place_list'), This all works well on different urls. But what should I do to get both lists on one page. List of NEW at the top and full list at the bottom of the page? -
Using Django rest_framework_jwt, how to allow auto login with on-time use code?
What I'm trying to do Use a link containing a generated code that will login to a specific Django auth_user account without the user needing to enter username and password. Current stack Django 2 django-rest-framework django-rest-framework-jwt django auth Question Is there a way to get a jwt from rest_framework_jwt without passing it username and password, but maybe just an account reference? -
Django Translation UnicodeDecodeError
I'm getting this error return _("%(user)s liked this") % {'user': likes.first().user.get_full_name()} UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 11: ordinal not in range(128) My django.po file is #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2018-05-08 16:21+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: LANGUAGE <LL@li.org>\n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: posts/models.py:1528 posts/models.py:1533 #, python-format msgid "%(user)s liked this" msgstr "%(user)s kişi sevdi" Please help me to solve this issue. Thanks -
__init__ .. get_form_kwargs(self) which function called the other
I'm little confused about which of the following functions called the other one is ___init____(self,*args,**kwargs) called get_forms_kwargs(self) or get_forms_kwargs(self) called ___init____() as I made the following mixin: class RequestformattachMixin(object): def get_form_kwargs(self): kwargs=super().get_form_kwargs() kwargs['request']=self.request print(kwargs) return kwargs and removed the get_forms_kwargs(self) from the CBV in view.py and instead updated the CBV to let it inherit from the mixin class LoginView(NextUrlMixin,RequestformattachMixin,FormView): form_class = login_page template_name = 'login.html' success_url = '/' and didn't call the get_forms_kwargs(self) in CBV and it's working with no errors. please need an explanation for that. -
How do I convert this SQL into a Django query?
I'm writing a Python/Django application to do some stock analysis. I have two very simple models that look like this: class Stock(models.Model): symbol = models.CharField(db_index=True, max_length=5, null=False, editable=False, unique=True) class StockHistory(models.Model): stock = models.ForeignKey(Stock, related_name='StockHistory_stock', editable=False) trading_date = models.DateField(db_index=True, null=False, editable=False) close = models.DecimalField(max_digits=12, db_index=True, decimal_places=5, null=False, editable=False) class Meta: unique_together = ('stock', 'trading_date') This is the dummy data I have populated them with: import datetime a = Stock.objects.create(symbol='A') b = Stock.objects.create(symbol='B') c = Stock.objects.create(symbol='C') d = Stock.objects.create(symbol='D') StockHistory.objects.create(trading_date=datetime.date(2018,1,1), close=200, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,1,2), close=150, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,1,3), close=120, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,4,28), close=105, stock=a) StockHistory.objects.create(trading_date=datetime.date(2018,5,3), close=105, stock=a) StockHistory.objects.create(trading_date=datetime.date(2017,5,2), close=400, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,11), close=200, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,12), close=300, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,13), close=400, stock=b) StockHistory.objects.create(trading_date=datetime.date(2017,11,14), close=500, stock=b) StockHistory.objects.create(trading_date=datetime.date(2018,4,28), close=105, stock=c) StockHistory.objects.create(trading_date=datetime.date(2018,4,29), close=106, stock=c) StockHistory.objects.create(trading_date=datetime.date(2018,4,30), close=107, stock=c) StockHistory.objects.create(trading_date=datetime.date(2018,5,1), close=108, stock=c) StockHistory.objects.create(trading_date=datetime.date(2018,5,2), close=109, stock=c) StockHistory.objects.create(trading_date=datetime.date(2018,5,3), close=110, stock=c) StockHistory.objects.create(trading_date=datetime.date(2018,5,4), close=90, stock=c) I want to find all the stocks that made a yearly low within the past week. But to make this question simpler, just assume that I want to find all the stocks whose lowest point since '2017-05-04' occurred on or after '2018-04-30'. Below is the SQL I wrote to find it. It works. But I need help figuring out what Django Query to write to get the same results as this … -
django database cache doesn't store value
I have a problem using the DatabaseCache in django in a view. It seems like I don't get access to the database cache and that storing new values in the cache doesn't worl. In settings.py I have put the settings for the cache: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'caches', 'TIMEOUT': 300, } } In my app accounts I have the following in my views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from accounts.serializers import UserSerializer from django.core.cache import cache, caches @api_view(['GET']) def current_user(request): print("all caches") print(caches.all()) cache_value = cache.get("foo") print("cache_value") print(cache_value) cache.set("foo", "some cached value", 24*60*60) cache_value_after_set = cache.get("foo") print("cache_value_after_set") print(cache_value_after_set) serializer = UserSerializer(request.user) return Response(serializer.data) The problem is that the cache doesn't seem "to stick". The first time try to do cache.get("foo") it will obviously return None. And further down the line when I do cache.get("foo") - after I have done cache.set - it returns the value it should. But when I call the view the second time, cache.get("foo") returns None. The output from caches.all() is an empty dictionary so I guess the cache settings in settings.py aren't used somehow in views.py. The output after the first and second calls to the views are: all … -
mysql Error 2013 in django 2 and ubuntu >=16.04
Ok so. I'm making a django project that needs the database to be shared with other project. The problem is that in my work team people use Ubuntu from 14.04 to 18.04 and in this machines when i try to connect to the remote database i get the next error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f0c8532f488> Traceback (most recent call last): File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/MySQLdb/cursors.py", line 253, in execute self._warning_check() File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/MySQLdb/cursors.py", line 148, in _warning_check warnings = db.show_warnings() File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/MySQLdb/connections.py", line 381, in show_warnings self.query("SHOW WARNINGS") File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 123, in inner_run self.check_migrations() File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/core/management/base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/db/migrations/loader.py", line 206, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/julian/.virtualenvs/pry36/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 62, in applied_migrations return {tuple(x) for x in … -
Retrieve Device.user_set on html
I have the following models: class Device(models.Model): id = models.CharField(max_length=20, primary_key=True) class User(models.Model): id = models.CharField(max_length=10, primary_key=True) device = models.ForeignKey(Device, blank=True, null=True, on_delete=models.SET_NULL) And the following view: def devices(request): return render(request, 'interface/device/devices.html', {'device_list': Device.objects.all()}) I'm trying the following, but it doesn't work: {% for device in device_list %} <form> <button class="btn btn-outline-primary btn-md btn-block" formaction="{% url 'interface:modify_device' device.id %}">Dispositiu: {{device.human_id}} <br> Pacient: {{device.user_set}}</button> </form> {% endfor %} The device.user_set is not working. That device has a User associated, as you can see here: This is not accessible on the view? -
Rest Framework Serializer Method Field
class BagSerializer(serializers.ModelSerializer): order_date = serializers.SerializerMethodField() class Meta: model = Bag fields = ('order_date') def get_order_date(self, obj): print('Order date called', obj) This is the view: class BagViewSet(viewsets.ModelViewSet): queryset = Bag.objects.all() serializer_class = BagSerializer def create(self, request): try: print('Inside create viewset') serializer = self.get_serializer(data=request.data) if serializer.is_valid(): print('serializer passed', serializer.validated_data) else: print('Serializer failed', serializer.errors) return Response(serializer.errors) except Exception as e: print('exception raised--------', e) return Response('Boom') The serializer method field is not being called and its data is too not shown in the validated_data and the serializer's is_valid() method returns True. Why aint it considering the serializer method fields -
django form field referencee from other model
I have a form that needs references from another model. here the example. I have models.py class Employee(models.Model): name = models.CharField(max_length=100) class Inven(models.Model): name = models.CharField(max_length=255) sn = models.DecimalField(max_digits=20, decimal_places=0) employee = models.ForeignKey(Employee, null=True, on_delete=models.SET_NULL, related_name='employee') here my views.py class InventoryListView(ListView): context_object_name = 'inventorys' model = models.Inventory and here my inven template_form.html <input type="text" name="name" maxlength="100" required="" id="id_name"> <input type="text" name="sn" maxlength="100" required="" id="id_sn"> <select> {% for employee in employees %} <option value="{{employee.pk}}">{{employee.name}}</option> {% endfor %} </select> how to make employee field as a select list from employee model?... -
Is there a way to access request object in django inline formset clean method?
Got this admin class with inline and form classes: class InvoiceAdmin(admin.ModelAdmin): .... inlines = [InvoiceLineInline, ] form = InvoiceForm .... class InvoiceForm(forms.ModelForm): .... def clean(): .... class Meta: model = Invoice exclude = [] class InvoiceLineInline(admin.TabularInline): model = InvoiceLine formset = InvoiceLineInlineFormset extra = 1 class InvoiceLineInlineFormset(forms.models.BaseInlineFormSet): def clean(self): super(InvoiceLineInlineFormset, self).clean() count = 0 for form in self.forms: if not hasattr(form, 'cleaned_data'): continue data = form.cleaned_data try: if data: count += 1 else: continue except AttributeError: pass if Decimal(data.get('quantity', 0)) <= 0: raise forms.ValidationError("Amount should be greater than 0.") ****************************************************** _stock_code = data.get('stock_code', None) if not len(fetch_stocks_from_connector(request, stock_code=_stock_code)): raise forms.ValidationError("{} Stock code does not exist at connector.".format(_stock_code)) ****************************************************** if count < 1: raise forms.ValidationError('Need one line at least.') I need to do extra validation with an external method for the _stock_code value in each inlineform within InvoiceLineInlineFormset.clean as displayed above between the starred lines. But external method needs request object as argument to run properly. Is it possible to pass request object to clean method? -
Clickable points and clickable tooltips in mpld3 scatter chart
I'm making mpld3 scatter plots. I need to have a points as clickable. I Followed this link It's working as i expected but when i apply this same logic to achieve my needs it shows only one data for all the points which i plot Here is my code: scatter_chart,ax = plt.subplots(figsize=(12, 5)) scatter = plt.scatter (10,15, c='black', marker='v') labels=[label-1] tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels) plugins.connect(scatter_chart, tooltip) plugins.connect(scatter_chart, ClickInfo(points,urls)) scatter = plt.scatter (10,20, c='black', marker='v') labels=[label-2] tooltip = mpld3.plugins.PointLabelTooltip(scatter, labels=labels) plugins.connect(scatter_chart, tooltip) plugins.connect(scatter_chart, ClickInfo(points,urls)) -
No module named 'django'
Before installing Django, I installed virtual environment with conda. After activating my virtual environment installed django pip install django. When I hit python on the console there is no error after importing python. However, when I run the python pop_script.py I get (MyDjangoEnv) MacBook-Pro:firstProject eLmaesTro$ python pop_script.py Traceback (most recent call last): File "pop_script.py", line 4, in <module> import django ModuleNotFoundError: No module named 'django' I could not execute this file. Here is the code of file. (pop_script.py) import os os.environ.setdefault('DJANGO_SETTINGS_VALUE','firstProject.settings') import django django.setup() # FAKE POP SCRIPT import random from firstApp.models import Topic,Webpage,AccessRecord from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # get the topic top = add_topic() # create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.time() fake_name = fakegen.company() # create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] # create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print('populating script!') populate(20) print('population complete!') -
RPY2 in django: Error in open.connection(file, "rt") : cannot open the connection
I am working on a Django website project, where an input is expected from the user, which is stored and run through a R script using RPy2 in python/django. I keep on getting the issue Error in open.connection(file, "rt") : cannot open the connection. Reproducing this in a python shell does not give any error. For learning purposes, I am at the moment uploading csv files and trying to simply return the value stored in the first position of the csv (basically doing csv_file[1,1] in R). Here are snippets of my code. The error has to be in the rpy_plot view, as I don't think I'm referencing the path to the file right. I have made sure that the files are stored in /media/file yet can't seem to access them. Models from django.core.validators import FileExtensionValidator from django.db import models from django.conf import settings import os # Create your models here. from django.forms import forms class RScript(models.Model): script = models.FileField(null=True,blank=True,validators=[FileExtensionValidator(allowed_extensions=['csv'])]) def __unicode__(self): return self.script def __str__(self): return self.script Forms from django import forms from .models import RScript class RScriptForm(forms.ModelForm): class Meta: model=RScript fields=('script',) Views from django.shortcuts import render, get_object_or_404 from .forms import RScriptForm from .models import RScript def rpy_home(request): form=RScriptForm(request.POST or … -
Django: force content_type ID
Each time I rebuild a new database from the same Django project, ContentType IDs are not assured to be the same. This make it difficult to compare data from two DBs. Is there a way to force an ID for a given ContentType / Model? -
I'm having a no reverse match in django for my signup
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/fir/signup/ Django Version: 1.11.12 Python Version: 2.7.14 Installed Applications: ['fir.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\dell\Desktop\BlrCityPolice\fir\templates\fir\acc_active_email.html, error at line 6 Reverse for 'activate' not found. 'activate' is not a valid view function or pattern name. 1 : {% autoescape off %} 2 : Hi {{ user.username }}, 3 : 4 : Please click on the link below to confirm your registration: 5 : 6 : http://{{ domain }} {% url 'activate' uidb64=uid token=token %} 7 : {% endautoescape %} Traceback:` File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dell\Desktop\BlrCityPolice\fir\views.py" in signup 426. 'token': account_activation_token.make_token(user), File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string 68. return template.render(context, request) File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Python27\lib\site-packages\django\template\base.py" in render 207. return self._render(context) File "C:\Python27\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Python27\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Python27\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render 40. output = self.nodelist.render(context) File "C:\Python27\lib\site-packages\django\template\base.py" in render 990. … -
Django-Rest-Framework ManyToMany field in Angular form
just starting with Angular, looking for some advice before I start going down the wrong path. I have a simple Django based app to manage a movie collection that exposes an API using Django-Rest-Framework. In this app I have a Scenes and Actors, which are related through a ManyToMany field. I would like to know how to edit this ManyToMany field using a form created in angular. I have so far copied the Heroes Tour App, replacing Heroes with Scenes and Actors, but I have no idea where to go from here - editing ManyToMany fields in a Angular form. Please point me in the right direction. Kind regards, Liam