Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, how to rename images using a new auto-numbering per foreign key?
Ok, that title is probably as vague as vague things can get, but I couldn't come up with something good. Let me explain my problem. For the explanation, I'll use books as an example, just because that's easy. So, imagine I have 2 models like this: class Book(models.Model): title = models.CharField(max_length=100) class BookImage(models.Model): book = models.ForeignKey(Book) image = models.ImageField() is_cover = models.BooleanField() Now, as you can see a book can have multiple images. I want to rename the uploaded images to [book title]-[image-id].jpg (or whatever image extension there is of course). However, I want image-id to be unique per book. If that makes sense. So if I have BookA, I want the images to be called BookA-1, BookA-2 and BookA-3 etc. And BookB starts at 1 again, BookB-1, BookB-2, BookB3 etc. Any idea how I can do this? I've been thinking about it myself, but I can't come up with a really good solution. At first I thought I could do a count on the number of images and add 1 to that, but then you would run into problems if you delete images. I also thought about just keeping track of the ids in a separate Model, but that … -
Can/should haystack be used with django to write data to the searchable database
I am considering using django with haystack to make an application. The application shows content from the searchable database and a form. The form can be used to alter or enrich the content. Consequently, I do not only want to query the database but also write data back. The SearchBackend provides a method to update the database. But is haystack a good/accepted solution for this? Or should it only be used for reading/querying/searching the database? -
HTML POST form in Django giving TypeError when submitted
I'm trying get user input from a HTML form and use that value to populate a ChartJS graph in my Django app called DisplayData which has a template called Display.html. I have the following form in my project. Display.html <div class="row"> <form method="POST"> {% csrf_token %} <input type="text" name="textfield"> <button type="submit">Submit</button> </form> </div> In my views file, I have the following code to get the data from this form: views.py class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): display_id = request.POST.get("textfield") #get data from form display_id = int(display_id) all_entries = models.Entries.objects.all().filter(parent=display_id) #change to input from drop down or change to 2 all_id = models.Entries.objects.all().values_list('id', flat=True) all_measurables = models.Measurables.objects.all().filter(user_id=request.user.id) #change to current user all_ids = [m.id for m in all_measurables] #use this to make drop down all_times = [m.timestamp for m in all_entries] all_data = [] for m in all_entries: data = m.data json_data = json.loads(data) value = json_data['value'] all_data.append(value) data = { "labels": all_times, "default": all_data, } return Response(data) My urls are set up as follows. urls.py from .views import get_data, ChartData urlpatterns=[ url(r'^$',views.DisplayView, name='DisplayView'), url(r'^api/data/$', views.get_data, name='api-data'), url(r'^display/api/chart/data/$', views.ChartData.as_view()), url(r'^logs/', views.LogDisplay, name='Display-Logs'), ] When I go into the form in the page and type in … -
Security using Django 1.10 + AJAX without any HTML form
I make a POST request via AJAX without HTML form. Are there any security issues? Why is there no csrf error? Because I do not send any csrf data and csrf is enabled in django? toggle-status.js jQuery(document).ready(function($) { $("#switch-status").click(function(){ $.ajax({ url: '/account/switches/', data: {'toggle': 'status'} }); }); }); view.py @login_required def switches(request): toggle = request.GET.get('toggle', None) current_user = request.user update = Switches.objects.get(owner=current_user) if toggle == 'status': if update.status is True: update.status = False else: update.status = True update.save() return HttpResponse('') -
Excluding certain routes in Django with React Router?
I am currently building a React with a Django REST backend. I have come into this one little problem I can't get past that has to do with Routing. Here is my urls.py file. urlpatterns = [ url(r'^api/', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^djangojs/', include('djangojs.urls')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^$', TemplateView.as_view(template_name='exampleapp/itworks.html')), url(r'^(?:.*)/?$', TemplateView.as_view(template_name='exampleapp/itworks.html')), ] Using this, it lets the react router do it's thing on the front end. For example, if I wanted to go to 127.0.0.1:8000/mentors then it will take me to the page I have set for React Router. However, doing API calls in the frontend also returns the react page rather than the API endpoint because of this. So whenever I remove the last line in the code above: url(r'^(?:.*)/?$', TemplateView.as_view(template_name='exampleapp/itworks.html')),, then it gets the API returned in JSON format successfully. Problem is now when I try to go to the links it will return the Django 404 page rather than the React page I set in the React Router. Is there anyway I can get the best of both worlds? -
What is difference between request.method = "POST" , "PUT", "DELETE" in django
I want to know about what is use of "POST" "PUT" "DELETE" in django and also want to know the difference between these terms. -
Flask-Login raises TypeError: 'int' object is not callable
I just write a flask login demo. @app.route('/reg/', methods=['GET', 'POST']) def reg(): username = request.form.get('username').strip() password = request.form.get('password').strip() if (username == '' or password == ''): return redirect_with_msg('/regloginpage/', u'用户名或密码不能为空', category='reglogin') user = User.query.filter_by(username=username).first() if (user != None): return redirect_with_msg('/regloginpage/', u'用户名已存在', category='reglogin') salt = '.'.join(random.sample('0123456789abcdfeghijklmnABCDEFG', 10)) m = hashlib.md5() str1 = (password + salt).encode('utf-8') m.update(str1) password = m.hexdigest() user = User(username, password, salt) db.session.add(user) db.session.commit() login_user(user) return redirect('/') And Traceback like this: TypeError: 'int' object is not callable File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/Users/apple/PycharmProjects/pinstagram/pinstagram/views.py", line 94, in login login_user(user) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_login/utils.py", line 140, in login_user user_id = getattr(user, current_app.login_manager.id_attribute)() TypeError: 'int' object is not callable It makes me upset, someone can save me ? -
django relationship how to map an indirect relation in model
I have three models class Venue(models.Model): property_values = models.ManyToManyField('feature.PropertyValue') class Feature(models.Model): name = models.CharField(max_length=255, null=False, blank=False) class PropertyValue(models.Model): name = models.CharField(max_length=255, null=False, blank=False) feature = models.ForeignKey('Feature', null=False, blank=False) In this I want to be able to add feature to venue model saying that belongs to it via property value. -
Creating connection to social account does not work when connection already exists
Assume 2 local accounts DjangoUser1 DjangoUser2 And they both have access to TwitterAcct1 Doing the following results in no social account being connected to DjangoUser2: DjangoUser1 registers with username, optional email, password DjangoUser1 logs into Twitter and successfully creates connection DjangoUser1 logs out DjangoUser2 registers with username optional email, password DjangoUser2 logs into Twitter and is taken back to connection page with no connection Is there a way that this can work with django-allauth? -
Can I use bigchainDB server with django instead of using sqlite?
I am creating degree verification process using blockchain approach which contain six main enntities. By entities I mean to say consensus mechanism will evolve around these six entities, so for this I need to build a distributed database . Two approaches came into my mind One approach of achieving this is to completely built everything from scratch ,seperate database for each node in sqlite and then connect each node with some type of query Another approach is to use bigchainDB server which is a distributed database server based on blockchain. Now my question which approach is feasible? . I don't know whether bigchainDB server is compatible with django or not since they haven't mention anything about it in their docs If anyone have use bigchainDB please help me out . I am really confused which approach should I follow -
Python Django Bound Form not returning
I am trying to validate a form by using is_valid() method. form = RegisterForm(request.POST) if form.is_valid(): form.save() else: return (RegisterForm) if there is error, I want tot return Bounded Registerform but I am getting 'get' error. If i remove the if block it is returning 'None' type error. my question is how do i return a bounded form. -
Django, update rate, signals
class Thing (model.Models): name = models.CharField(max_length = 222) ratee = models.IntegerField(default = 0) ... class Rate(models.Model): thing = models.ForeignKey(Thing) user = models.ForeignKey(User) rate = models.IntegerField() If user evaluate the thing(give rate in Rate), I want to automatically calculate average and save to ratee in Thing. How to make it? -
Subprocess with 'While True' ends after 3640 iterations
I have a Django app that spawns a subprocess everytime there is a database insert. models.py # spawn subprocess to trigger tweepy # output of subprocess DOES NOT log to the console. def tweepy_tester(sender, **kwargs): if kwargs['created']: logger.error('tweepy trigger-start!') p = subprocess.Popen([sys.executable, "/Users/viseshprasad/PycharmProjects/Blood_e_Merry/loginsignup/tests.py"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) logger.error('tweepy trigger-over!') # use post_save to trigger tweepy later post_save.connect(tweepy_tester, sender=User) tests.py logger = logging.getLogger(__name__) # Create your tests here. def for_thread(): i = 0 while True: f = open('test.txt', 'a') f.write('Tweepy triggered ' + str(i) + '\n') # python will convert \n to os.linesep f.close() # you can omit in most cases as the destructor will call it i += 1 for_thread() The trigger happens fine but the subprocess only writes 3640 lines to the test.txt file, even though I have used while True: I am basically look for a subprocess to run non-stop after the trigger, as a separate thread and not disturbing the main thread. The purpose : I run my app with the usual python manage.py runserver. User signs-up -> database insert -> triggers my implementation of tweepy which keeps on streaming tweets and analyzing them non-stop on a different background thread so as to not interfere with the signup process. … -
Circular import between models and helpers in Django
I'm trying to add a post_save Signal in my Django app and am running into a circular import issue. helpers.py from tracker.models import Record def get_account_id(name): return name + '123' models.py from helpers import get_account_id class Record(models.Model): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=120, blank=True) matched_account_id = models.CharField(max_length=120, unique=False, blank=True) def find_matched_account(sender, instance, *args, **kwargs): instance.matched_account_id = get_account_id(instance.name) instance.save() pre_save.connect(find_matched_account, sender=Record) This is obviously a simplification but sums up the issue I'm running into. I could move the code in helpers into models but would prefer to store things like this in helpers because I'll end up using it in other places. -
How to set a cell not column or row in a datafram with color?
I have a dataframe with table style that I created : tableyy = final.style.set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(10).render() I have go through this Coloring Cells in Pandas , Conditionally change background color of specific cells, Conditionally format Python pandas cell, and Colour cells in pandas dataframe, I still not able to set a cell with color not the whole dataframe without any condition. Anyone have any ideas, I try this color code for one months already so hope can receive advise from anyone of you guys, thanks. -
eliminate duplicates in django
I'm trying to pick up 3 random numbers out of a list of 20 numbers. In views.py i've defined this variable: nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] In my template index.html: {{ nums|random }} - {{ nums|random }} - {{ nums|random }} I want to get 3 different numbers but i don't know which filter/tag to apply. I've tried if/else statements, for loops, (if there's a duplicate i want a redraw) but i'm not satisfied with the results and i'm pretty sure there's a simple filter to do that. Thanks for your help! -
How to disable cache on Django?
I have a problem with my first django app and I can not find the solution. I send this to my controller: http://localhost:8000/fun1_get_data/?param1_qty=10 The controller: @never_cache def func1_get_data(request): result = request.GET['param1_qty'] return HttpResponse(json.dumps(result), content_type = "application/json") Only return the same parameter...very easy...but doesn't work.Only works the first time after restart de server or 'save changes' on archive .py. The first time OK: http://localhost:8000/fun1_get_data/?param1_qty=10 10 And then.... http://localhost:8000/fun1_get_data/?param1_qty=999 10 panic!! Extra: the template: url(r'^func1_get_data/', controlador.func1_get_data) -
FreeTDS with Django causing Denial of Service on SQL Server
It is a fairly odd behavior coming from an unknown part of the application. My setup: Django FreeTDS Unixodbc django-pyodbc-azure MS SQL The application will work for a seemingly random amount of time (usually 2-3 minutes), then will stop responding and so will the SQL Server. Other applications even with other accounts are unable to do any request to the database. The number of explicit requests on my side is 1 in the ready() of the django application to get some inital data. def ready(self): from django.conf import settings from app.models import SomeModel try: settings.SomeModel_ID = SomeModel.objects.filter(identifier=settings.SomeIdentifier)[0].pk except: settings.SomeModel_ID = SomeModel.objects.create(identifier=settings.SomeIdentifier).pk SQL Server Tracer will log some requests but nothing unusual (quite a lot of BatchStarted/BatchFinished). Wireshark with see an insane amount of packets moving between the application and the database (We are talking +250 for a simple SELECT). Here I took an example with some TCP but +95% for the packets are TDS. 5422 36.248815392 10.10.10.66 -> 10.10.10.103 TDS 183 TLS exchange 5423 36.249013989 10.10.10.103 -> 10.10.10.66 TDS 135 TLS exchange 5424 36.249427950 10.10.10.66 -> 10.10.10.103 TDS 135 TLS exchange 5425 36.250678349 10.10.10.103 -> 10.10.10.66 TCP 1514 [TCP segment of a reassembled PDU] 5426 36.250703683 10.10.10.103 -> 10.10.10.66 TDS … -
NoReverseMatch at /revision/login_user/ Reverse for 'module-add' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am getting the following error in Django. NoReverseMatch at /revision/login_user/ Reverse for 'module-add' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []I am not really sure why i am getting this error. This is my views for logging in: (Traceback refers to here) def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) modules = Module.objects.filter(user=request.user) return render(request, 'revision/index.html', {'modules': modules}) else: return render(request, 'revision/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'revision/login.html', {'error_message': 'Invalid login'}) return render(request, 'revision/login.html') Same with register: def register(request): form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) modules = Module.objects.filter(user=request.user) return render(request, 'revision/index.html', {'modules': modules}) context = { "form": form, } return render(request, 'revision/register.html', context) Both refers to the line of return render(request, 'revision/index.html', {'modules': modules}) How do i fix this issue? -
Convert ManyToMany into ForeignKey (django)
I have a ManyToMany field in my database that I want to convert to a ForeignKey relationship. The relationships are already one-to-many, so there will be no pigeonholing. The closest question I can find on stackoverflow is this more complicated situation in a different framework/language My simplified django models are shown below. The fields in question already exist in the database, and we just need to populate the DbLocation.pattern field. class DbPattern(models.Model): locations = models.ManyToMany(DbLocation) #trying to remove this ... class DbLocation(models.Model) pattern = models.ForeignKey(DbPattern) #and replace it with this ... My naive solution is a nested for-loop. It works, but looks like it will take days to handle several million records: patterns = DbPattern.objects.all() for p in patterns: locs = p.locations # there ary many locations for l in locs: l.pattern = p # each location has exactly 1 pattern. Is there an easy way to implement this in either Python/Django or PostreSQL that will run fast? I imagine there is a way to do this via queries. I only need to do it once. Thanks in advance for your help! -
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'manage.py'
I am facing a rather strange issue. I am trying to get my django app started using the python manage.py runserver. But I get a FileNotFoundError. I have checked multiple time. The file is in the directory from where I am running the python manage.py runserver command. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\commands\runserver.py", line 58, in execute super(Command, self).execute(*args, **options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\commands\runserver.py", line 97, in handle self.run(**options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\core\management\commands\runserver.py", line 106, in run autoreload.main(self.inner_run, None, options) File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 333, in main reloader(wrapped_main_func, args, kwargs) File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 299, in python_reloader reloader_thread() File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 275, in reloader_thread change = fn() File "C:\New folder (2)\Anaconda\lib\site-packages\django\utils\autoreload.py", line 205, in code_changed stat = os.stat(filename) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'manage.py' Any help would be great. Thanks in advance -
Django postgres row-lock
I am trying to implement row level locking in my django project (postgres 9.5) for a model which handles API keys. I have read about select_for_update but it mentions that it throws TransactionManagementError when autocommit is set to True on postgres (select for update). So then I tried this: class APIKeyManager(models.Manager): ... def acquire_n_keys(self, retailer=None, n=1, calls_per=1, propagate=False, nowait=True, **kwargs): assert isinstance(n, int) or (isinstance(n, str) and n == 'max') transaction.set_autocommit(False) with transaction.atomic(): keys = self.get_queryset().select_for_update(nowait=nowait) \ .available_keys(retailer=retailer, num_calls=calls_per, **kwargs) exc = False num_keys = keys.count() if propagate: if num_keys is 0: exc = "No available keys!" elif isinstance(n, int) and (n > num_keys): exc = "Tried to acquire more keys (%d) than were available (%d)." % (n, num_keys) if exc: raise NoAvailableKeys(exc) n = num_keys if ((n == 'max') or (n > num_keys)) else n if num_keys > 0: key_pks = keys.values_list('pk', flat=True).all()[:n] keys = keys.filter(pk__in=key_pks).all() keys.update(in_use=True, last_started=timezone.now(), last_ended=None) transaction.commit() transaction.set_autocommit(True) return keys def release_key(self, **kwargs): assert all(arg in kwargs for arg in ['retailer', 'key', 'service_name']) or ('pk' in kwargs), \ "Must provide `retailer`, `key` and `service_name` args or `id` arg, got : %s" % json.dumps(kwargs) transaction.set_autocommit(False) with transaction.atomic(): pk = kwargs.pop('pk', None) if pk: key = self.get_queryset().select_for_update().filter(pk=pk) else: … -
Django admin editing inline objects is inactive in version 1.10
Editing Foreign Key objects via a "pencil" is inactive in Django version 1.10 and 1.11. In version 1.9 everything still works fine The pencil and cross are greyed out How to make inline editing active again? -
Passed parent ID to child form for child creation in Django app, I get 200 code but no record is created?
I followed some guidelines from This answer in order to pass Parent pk to the child creation page but I still can't get the desired results, my goal is to be able to add lines (CotizacionDetalle) records from a link in a Master/Detail like scenario (i.e.: Quotation creation) this link should take the current Master (parent) record (Cotizacion) and use it in the Detail (child) form creation process populating the relevant field in a transparent way for the user (a hidden field). My views.py: class CotizacionDetalleCreateView(CreateView): model = CotizacionDetalle form_class = CotizacionDetalleForm def form_valid(self, form): cotizaciondetalle = form.save(commit=False) cotizacion_id = form.data['cotizacion'] cotizacion = get_object_or_404(Cotizacion, id=cotizacion_id) cotizaciondetalle.cotizacion = cotizacion return super(CotizacionDetalleCreateView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CotizacionDetalleCreateView, self).get_context_data(**kwargs) context['c_id'] = self.kwargs['cotizacion_id'] return context def get_success_url(self): if 'slug' in self.kwargs: slug = self.kwargs['slug'] else: slug = self.object.cotizacion.slug return reverse('transporte_cotizacion_detail', kwargs={'slug': slug}) The forms.py file: class CotizacionForm(forms.ModelForm): class Meta: model = Cotizacion fecha_vence = forms.DateField(widget=DateWidget(usel10n=True, bootstrap_version=3)) fields = ['nombre', 'fecha_vence', 'itinerario'] class CotizacionDetalleForm(forms.ModelForm): class Meta: model = CotizacionDetalle fields = ['cotizacion', 'item', 'cantidad', 'nivel_de_precio'] def __init__(self, *args, **kwargs): super(CotizacionDetalleForm, self).__init__(*args, **kwargs) self.fields["cotizacion"] = forms.CharField(widget=forms.HiddenInput()) My template: cotizaciondetalle_form.html {% extends "base.html" %} {% load bootstrap3 %} {% block extlibs %}{% endblock %} {% … -
OperationalError at / unable to open database file in Django 1.8.6
I am getting the following error when I try to run a Django site in production: OperationalError at / unable to open database file The strangest part is that it worked for a few page reloads and even clicks on different navigation links. Then, it worked every other time or so. At the end, it stopped working all together. This behavior is very puzzling. Here is the relevant piece from settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I have done chmod 777 db.sqlite as well as chmod o+w . within the directory where db.sqlite3 is located. It did not help. How could I fix this? I am using a basic EC2 instance with Linux and Apache 2.4