Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.urls.exceptions.NoReverseMatch Class Based List Views
I am attempting to set up a website on cookeicutter, I created a new app called "bots" and added a class called Trade and Unit within models. I created two class based views inside of views.py; detail and list view. The trade detail view works fine and directs to the correct trade, but when I attempt to visit the html page that references the trade list view, the page returns the following error. django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'trade-detail' with arguments '('1',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I believe something is wrong with the get_absolute_url, because when i remove it from the model.py the list error above goes away and the page renders, but then the links don't work. Most of my code is from this tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views Models.py from django.db import models from datetime import date from django.urls import reverse from django.urls import reverse_lazy from django.conf import settings import uuid class Unit(models.Model): TRADE_UNIT = ( ('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash'), ) sell = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='ETH', help_text='Currency to Sell') buy = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='BTC', help_text='Currency to Buy') def get_absolute_url(self): """ Returns the url to access a … -
Django Allauth migration error
I've run across this issue before and I think I had to go into the library installed by pip to manually delete the migrations to fix it. Does anyone have a better idea? ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 95, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/loader.py", line 268, in build_graph raise exc File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/loader.py", line 238, in build_graph self.graph.validate_consistency() File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/graph.py", line 104, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration socialaccount.0001_initial dependencies reference nonexistent parent node ('sites', '0001_initial') -
Django: Search Function If No Initial Data
def search(request): query = request.GET.get('q') .... .... return render(request, 'search.html', {'list': list}) form looks like this, <form method="get" action="{% url 'new:search' %}"> <input type="text" name="q" value="{{ request.GET.q }}"> <input type="submit" value="Search" /> </form> Everything is working fine here but if a user simply press the "Search" button it shows all data instead of doing nothing. So, how can I make this search function do nothing when user directly press the Search button without entering initial data? -
Values get corrupted in template tag
I am developing an app which enables me to show multiple markers when I click on the markers it should show me an image along with some details. My current code is : google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent( contentString = '<div id="content">'+ '<p>'+ 'sensor image:' +'<br/>' + '<img src="{% static "test/imgs/sen1.jpg" %}">'+ + '<br/>' + 'sensor light level :' + j[i][4] +'<br/>' + 'sensor battery level :' + j[i][5] + '</p>'+ '</div>' ); infowindow.open(map, marker); } })(marker, i)); and I get the desired output: !https://imgur.com/a/Q1lPU I have an array, j which contains name of the image I want to load, previously i hardcoded the url '<img src="{% static "test/imgs/sen1.jpg" %}">'+ I tried to make this dynamic by using '<img src="{% static "test/imgs/'+ j[i][3] +'.jpg" %}">'+ But i got an error , on using F12 it appears GET localhost:8000/static/test/imgs/'%2B%20j%5Bi%5D%5B3%5D%20%2B'.jpg 404 (Not Found) a lot of garbage was generated instead of the value sen1. I am not able to understand why this is happening and would like some help. -
Format Django QuerySet output with arrays
I have data in a table that look like this: src_id, dst_id, params int , int , array I'm querying the data to extract some values from the array with the following Django query dataset = query_set.values_list('src_id', 'dst_id', *[e.field for e in settings]) I need to output the data like this: [ [1,2,[a,b,c,d], [3,4,[a,c,d,e], ... ] but the values_list returns a list of tuples like (1,2,a,b,c,d)(3,4,a,c,d,e)... So I've been doing: [[d[0], d[1], d[2:]] for d in dataset] It works fine, but I have 1M+ rows, and it is slow. It is also using a lot of memory. Is there a way to optimize this code? I looked at using a loop, or lambda but that doesn't make much of a difference. I looked at using array but it only takes primitive types, so no much luck with array of arrays. I am looking for a way to query the DB and output the data directly in the right format, if possible in Django, otherwise I'd have to use raw SQL. Any hint on how to format output of a query? is it possible, or just too esoteric for Django? Thanks -
Integrate multiple dictionaries in django
Really having trouble about list these days, I'm a developer from php looking a place in python. My question is in relation to my previous question I now have a dictionary group by id_position and flag that contains order [Top, Right, Bottom, Left, Center]: A = {41: [0, 0, 0, 0, 1], 42: [0, 0, 1, 0, 1], 43: [0, 0, 0, 0, 1], 44: [0, 0, 0, 0, 1]} and other dictionary that contains my id_position and status: B = {'44': 'statusC', '42': 'statusB', '41': 'statusA', '43': 'statusC'} I want to include dict A in my code to save dict B below. for pos, stat in B.items(): MyModel.objects.create(position=pos, status=stat, Top = "" , Right="" Bottom = "", Left= "") How can I make this wok? Can you recommend study list where I can start to work from php to django. -
Modifying Oscar on an pre-existing non-oscar app
I had an app without oscar, I then installed oscar. I updated my main app settings with the credentials of oscar's. When I go to my admin page, I am able to see the products pages and such. I can add the products BUT I see nothing on main page What I did so far, pip install django-oscar, created a new app django-admin startproject myshop, modified settings.py in my main app per the directions in oscar's. I pointed my urls.py to myshop. urls.py from oscar.app import application admin.autodiscover() urlpatterns = i18n_patterns( url(r'^partner/', include(application.urls)), ... Now I'm expecting myshop to be integrated to oscar. I went to my website.com/myshop I see my default template. I go to website.com/myshop/dashboard same template, no oscar. -
compressor aws compressor error
I installed a module and it installed dependencies. (I seriously am not enjoying these dependencies) anyways, looking around to solve this. Did what people posted. my error: s3link isn't accessible via COMPRESS_URL cloudfrontlink also tried AWS_S3_CUSTOM_DOMAIN =https://xxx.cloudfront.net settings.py STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' COMPRESS_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_HOST = 'https://xxxxxxxxx.cloudfront.net' if not DEBUG else '' STATIC_URL = STATIC_HOST + '/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') # STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "app/static"), ) STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "solid/static"), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'compressor.finders.CompressorFinder' ) COMPRESS_ROOT = STATIC_ROOT COMPRESS_ENABLED = True COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter' ] COMPRESS_PARSER = 'compressor.parser.HtmlParser' COMPRESS_URL = 'https://xxxx.cloudfront.net/static/' -
Facing issues to provide download link to shared files in django application
I am developing file sharing app using Django. I have 3 models to store 1: User information 2: Information about there uploaded files 3: Information about file shared with them by another user model number 2 and 3 are, class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField(upload_to='img/') user_uploaded = models.CharField(max_length=50, blank=True) def get_absolute_url(self): return '/img/%s' % self.Browse.name user_list = (User.objects.all()) class share_files(models.Model): select_file = models.CharField(max_length=300) from_user = models.CharField(max_length=50) select_user = models.CharField(max_length=50,default=None) I have written below function in view for sharing of file, def user_share(request): user_data=User.objects.all() file_data = user_files.objects.filter(user_uploaded=request.user) select_user=request.POST.get('dropdown1') select_file=request.POST.get('dropdown2') if request.method=="POST": user_form = Share_file(request.POST) data=share_files(select_user=select_user,select_file=select_file) data.save() return redirect('share') else: user_form=Share_file() return render(request, 'accounts/share.html',{'user_form':user_form, 'user_data':user_data, 'file_data':file_data}) and the form for it is, class Share_file(forms.ModelForm): class Meta: model = share_files fields = ('select_file', 'select_user') I am displaying shared files in template , from model share_files but i also want to provide download option for that file. How can i achieve that? Thanks in advance. -
Django multi host url configuration per app
I searched around here on SO for how I would setup different domains for apps within a single django project. e.g.: news.io, jobs.io, etc for a news, job, etc app within the main project. The app will also have authentication where the user will need to remain signed in across the domains if this matters. e.g. - billing platforms, etc. The recommendation was to use a MultiHostMiddleware found here which is obviously outdated. Similarly, the other recommendation was to use django-multihost which is also really old. I'm on Django 1.11 and Python 3.6. Is there anything more recent or better yet how would I roll my own? -
Where are stack-traces for my Django / uWSGI vassal logged?
I am running my Django site as a vassal of UWSGI emperor. I have created /etc/uwsgi-emperor/vassals/mysite.ini as follows: [uwsgi] socket = /var/opt/mysite/uwsgi.sock chmod-socket = 775 chdir = /opt/mysite master = true virtualenv = /opt/mysite_virtualenv env = DJANGO_SETTINGS_MODULE=mysite.settings module = mysite.wsgi:application uid = www-data gid = www-data processes = 1 threads = 1 plugins = python3,logfile logger = file:/var/log/uwsgi/app/mysite.log vacuum = true But the only logs I get are things like this: [pid: 2887|app: 0|req: 7/7] 1.2.3.4 () {52 vars in 936 bytes} [Fri Oct 13 20:46:04 2017] POST /mysite/login/ => generated 27 bytes in 2453 msecs (HTTP/1.1 500) 4 headers in 126 bytes (2 switches on core 0) [pid: 2887|app: 0|req: 8/8] 1.2.3.4 () {44 vars in 702 bytes} [Fri Oct 13 20:52:24 2017] GET / => generated 1561 bytes in 2 msecs (HTTP/1.1 200) 4 headers in 124 bytes (2 switches on core 0) Where's the stack-trace for the 500 error? (Is there a module I need to enable?) -
Django render json response with html elements
I'm learning ajax. for example I want to fetch some items. As the json only contains dict-like data, I have to render them as complicated html elements. I'm thinking about where to do the render job. If done in frontend, using javascript to render such complicated html element will be painful. So I thought it will be better to leverage Django template. And What I need is to render it using html template, and put the whole html elements into a string in json, and return the json. So my frontend will easy fetch the rendered element like data['element'] and append it to my page. But I don't know how to do this in Django, ususally I render a html page and return it directly. But how can it render the html elements and put it into json? Or is there better way to do this? -
'MP3' object has no attribute '_committed'
An uploaded file has to be inserted into a model Django. But it shows the error Models.py class Song(models.Model): user = models.ForeignKey(User,default=1) album = models.ForeignKey(Album, on_delete=models.CASCADE) song_title = models.CharField(max_length=250) audio_file = models.FileField(default='') is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title Forms.py class SongForm(forms.Form): audio_file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) Views.py with open(str("media/"+str(request.user.pk)+"/"+str(file_album_name)+"/"+str(song_title)+".mp3"), 'wb+') as destination: for chunk in a.chunks(): destination.write(chunk) f = open(str("media/"+str(request.user.pk)+"/"+str(file_album_name)+"/"+str(song_title)+".mp3"), 'r') new_song = Song(user = request.user, album = Album.objects.get(album_title=file_album_name,user=request.user), song_title = song_title, audio_file = File(f)) new_song.save() In the above code variable a is the uploaded file. Variable f is the uploaded file location. -
Why are my Django / USWGI emperor logs empty?
I am running my Django site as a vassal of UWSGI emperor. I have created /etc/uwsgi-emperor/vassals/mysite.ini as follows: [uwsgi] socket = /var/opt/mysite/uwsgi.sock chmod-socket = 775 chdir = /opt/mysite master = true virtualenv = /opt/mysite_virtualenv env = DJANGO_SETTINGS_MODULE=mysite.settings module = mysite.wsgi:application uid = www-data gid = www-data processes = 1 threads = 1 plugins = python3,logfile logger = file:/var/log/uwsgi/app/mysite.log vacuum = true But /var/log/uwsgi/app/mysite.log does not get created. If I touch it, it remains empty. This occurs even after I trigger 500-style errors in the application. Why aren't my logs being written? -
Clean_<fieldname>() prevents a file to use upload_to
Django==1.11.6 I'd like to load files only with permitted extensions. Files are loaded via Django admin only. I have put a breakpoint in get_item_path (marked by a comment here). The clean_file method somehow prevents the interpreter from going to get_item_path. In other words the interpreter doesn't stop at the breakpoint. If I comment clean_file out, the breakpoint works. Well, get_item_path is ignored. And by the way, ItemFile object is created. But the file is not saved (the uploaded file doesn't appear in the MEDIA_ROOT directory. Could you help me understand what have I done wrongly here? models.py def get_item_path(instance, filename): item_dir = instance.item.get_item_directory() # Breakpoint return '{directory}/{filename}'.format(directory=item_dir, filename=filename) class ItemFile(models.Model): file = models.FileField(blank=False, max_length=255, upload_to=get_item_path, verbose_name=_("file")) admin.py class ItemFileForm(ModelForm): model = ItemFile def clean_file(self): permitted_extensions = list(PermittedFileFormats.objects.values_list("file_ext", flat=True)) filename = self.cleaned_data['file'].name real_ext = filename.split(".")[-1] if real_ext not in permitted_extensions: raise ValidationError(_("File doesn't have a permitted extention!")) else: return filename class ItemFileInline(admin.StackedInline): model = ItemFile form = ItemFileForm extra = 0 -
difficulty giving alias to an import in python when using Django
I have a Django app that is up and running, mostly in an easy-to-understand way. But I have one quirky problem. My code sits one level below where urls.py and views.py sit. I have a number of Python files, some of which are used as imports across the actual code in the other impoPython files. I have found that, as part of a Django app, I need to precede import filenames with a '.' for them to import. So, if I have a file of code called foo.py, and an import file called vars.py, this won't import right: # foo.py from vars import * but this works: # foo.py from .vars import * The problem comes if I try to be more Pythonic (and safe) and name the import, so if I import everything it gets a prefix. But neither of the following work at all: # foo.py import vars as v import .vars as v my presumption is Django (using virtualenv or through other means) defines certain paths to look up import files, and the '.' becomes necessary to point the Python interpreter to the same directory in which the importing file sits to locate the import files it … -
Django CMS: How to modify style of show_menu
I want to build a Django CMS template from a template found on https://startbootstrap.com. I have load the following tags {% load cms_tags menu_tags sekizai_tags staticfiles %} and then within the <body> part the menu ... <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="#">Start Bootstrap</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> {% show_menu 0 100 100 100 %} </ul> </div> </div> </nav> ... Unfortunately, the links for the pages in the menu have almost no CSS (see image). Basically, the links need to be of class nav-link. How can I fix this? -
Incredibly basic: How to build a json REST API in django (without Django REST framework)
Preface I have a django project. I've wired it up so it serves a bunch of views for a bunch of models. Now I want to add an endpoint which just dumps a good fraction of the database out as json. The way I would assume you do this is add a URL to a view class / method which returns a HTTPResponseObject full of json. Unfortunately, after quite a bit of googling, all I can find are references to Django REST framework. This is the sort of thing you would think Django would provide internally not as part of an external plugin library. But searching the django docs doesn't yield an immediate answer -- I don't think there are any docs about how to build an endpoint which just serves a bunch of json. Questions: Do I really need "Django REST framework" to serve json in django? Did I overlook docs in Django for serving json? What is the canonical way to serve json in a django project? -
How to inline form a deeply nested model?
To give a simple overview. I have a model that has a foreign key to another model in which that model has a foreign key and so forth. How can I go about expanding out the form so it is in a single view? Currently, when I use a CreateView it shows the foreign key field as a dropdown. I would like to replace the drop-down with an actual form that can be filled out. I will give an example on the models: class Address(models.Model): address_0 = models.CharField("address", max_length=64) address_1 = models.CharField("address cont'd", max_length=64, blank=True) city = models.CharField("city", max_length=64, blank=True) state = USStateField() # this is selection field # django_localflavor_us.models zip_code = USZipCodeField() # django_localflavor_us.models class ContactInfo(models.Model): name = models.CharField(max_length=50) address = models.ForeignKey(Address, null=True, blank=True) phone = models.CharField(max_length=50, blank=True) fax = models.CharField(max_length=50, blank=True) email = models.EmailField(blank=True) class Generator(models.Model): contact = models.ForeignKey(ContactInfo, related_name='contact') mailing_address = models.ForeignKey( Address, null=True, blank=True, related_name='mailing_address') code = models.CharField(max_length=50, blank=True) I want the user to create a generator form. The page I get is a bunch of drop-down fields and code being the only fillable field. I want to be able to fill everything out when creating a new generator form. Problems How to get all the … -
Django - Save Cloudinary Object via Upload Widget
I am trying to set up Cloudinary's upload widget and save the resulting Cloudinary objet to my CloudinaryField() on my model. Cloudinary's sample project only shows how to upload images using {{form}}. When I upload using the widget, I get a dictionary back, but I can't find any place in the docs where it gives me a way to save it. -
Convert Full Database to Different database Format using django
I'm switching my database engine and need to convert my data. I can access both databases in a python shell with .using('[database]'). Does django have any built-in backup&restore functions that I could use to fill my empty(but migrated) new database? -
Prevent repeating logic with DRF and Django
I am using Django and Django Rest Framework with the Serializer Extensions Mixin to expand fields. I have some calculated fields that I only want to call sometimes to minimize hits on my DB. However, I need to be able to call these calculations in both templates (i.e. through the models) and through the serializers (i.e. using DRF's serializers.MethodField + Serializer Extensions Mixin expand feature). As it stands, the only way I can figure out how to do this is by including the logic in both models.py AND serializers.py, as I can't use serializers.MethodField to call the method that I created in models.py. Not very DRY and a huge potential flaw. When I try to call the method via serializers.MethodField it simply returns the method object and doesn't run the method itself (i.e. "<property object at 0x7f18d78de9a8>"). Is there any way to force DRF to run a method that is in models.py only when triggered? If I include it as a serializers.ReadOnlyField, it will trigger every time the serializer is called, which I don't want. However, Serializer Extensions Mixin doesn't support serializers.ReadOnlyField. I suppose I could make a serializer specifically for this instance, but that seems overly complicated. Any ideas? … -
AttributeError at /home/
I'm using django 1.11 and python3 when I try to use django-likes and i'm following this project https://github.com/praekelt/django-likes when i set up like app and started displaying like button I get this error: 'str' object has no attribute '_meta' Traceback highlights this line: model_name = obj._meta.module_name in likes_inclusion_tags.py: from secretballot.models import Vote from django import template from likes.utils import can_vote, likes_enabled register = template.Library() @register.inclusion_tag('likes/inclusion_tags/likes_extender.html', takes_context=True) def likes(context, obj, template=None): if template is None: template = 'likes/inclusion_tags/likes.html' request = context['request'] import_js = False if not hasattr(request, '_django_likes_js_imported'): setattr(request, '_django_likes_js_imported', 1) import_js = True try: model_name = obj._meta.model_name except AttributeError: model_name = obj._meta.module_name context.update({ 'template': template, 'content_obj': obj, 'likes_enabled': likes_enabled(obj, request), 'can_vote': can_vote(obj, request.user, request), 'content_type': "-".join((obj._meta.app_label, model_name)), 'import_js': import_js }) return context Traceback also highlights this line: return render(request, self.template_name, args) in my views.py users = User.objects.exclude(id=request.user.id) friend = Friend.objects.get(current_user=request.user) friends = friend.users.all() args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) ... def post(self, request): if request.method == 'POST': form = HomeForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) any idea? -
Django unable to handle concurrent request ? where did I do wrong
I'm sure it's because I did something wrong. I built a website with Django. In the model, I have a subprocess call: class MyModel: ... def foo(self): args = [......] pipe = subprocess.Popen(args, stdout=subproccess.PIPE, stderr=subprocess.PIPE) In my view: def call_foo(request): my_model = MyModel() my_model.foo() When I click my website where it sends async get request to this call_foo() function, it seems like my app is not able to handle other requests. For example, if I open the home page url, it keeps waiting and won't display until the above subprocess call in foo() has finished. Does anyone know where I did wrong? Thanks -
Django 1.11 CreateView adding datepicker for datefields
So I am trying to change my form's model Datefield output to the Datepicker similar to DatepickerWidget in CreateView The forms are generated using a html template: {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.error }}</span> </div> <label class="control-label col-sm-2">{{field.label_tag}}</label> <div class="col-sm-10">{{field}}</div> </div> {% endfor %} Here is the Views with what I tried: class newenv_form(generic.CreateView): model = Environment fields =['name', 'description', 'creation_date', 'status','status_update_date'] template_name = 'catalogue/new_env.html' #Does not work def get_form(self, form): form = super(newenv_form, self) form.fields['creation_date','status_update_date'].widget = forms.DateInput(attrs={'class':'datepicker'}) return form