Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'index' with keyword arguments '{'username': 'garrett', 'pk': 7}' not found
So I know what a reverse is, I just don't understand how the Keyword stuff fits into it. What I am trying to do is enable people to delete only their own posts. The delete button shows up properly on only the users own posts, however when you click "Delete" I'm getting an error, here is the error along with the code. The traceback doesn't highlight anything but if you want to see it or anything else let me know and I can add it. Also haven't been able to find any other questions on this site... Error: NoReverseMatch at /colorsets/delete/7/ Reverse for 'index' with keyword arguments '{'username': 'garrett', 'pk': 7}' not found. 1 pattern(s) tried: ['$'] Colorsets App views.py from django.shortcuts import render from colorsets.forms import ColorForm from colorsets import models from colorsets.models import ColorSet from django.utils import timezone from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse,reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from braces.views import SelectRelatedMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here. #def index(request): # return render(request,'index.html') class PostListView(ListView): model = ColorSet def get_queryset(self): return ColorSet.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class CreateColorSetView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'index.html' form_class = … -
How do I filter data using .date() keyword in the column name in django?
I am writing a web application using Django where I have to use date() in column name. The orignal field is datetimefield and i need filter using date only and ignore the time. Here is my code: datas = Data.objects.all() for data in datas: all = Data.objects.filter(datetime.date() = data.datetime.date()) But it gives out the following error: all = Data.objects.filter(datetime.date() = consumption.datetime.date()) SyntaxError: keyword can't be an expression Any idea how I use datetime.date() as a column name to use only date section of the datetimefield column? UPDATE Here is my model: class Data(models.Model): datetime = models.DateTimeField(auto_now=False) value = models.FloatField() -
How to call javascript function with input type "submit" in django
html file <div class="container"> <div class="row"> <div class="col-6"> <form method='POST' class='my-form' action=''>{% csrf_token %} <br/> <br/> <br/> {{ form|crispy }} <br/> <br/> <!-- <input type="button" class="btn btn-primary" value="Get Route" onclick="GetRoute()"/> --> <input type="submit" class="btn btn-primary" value="Get Route" onclick="GetRoute()"/> </form> </div> </div> <table border="0" cellpadding="0" cellspacing="3"> <tr> <td colspan="2"> <div id="dvDistance"> </div> </td> </tr> </table> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script> <script type="text/javascript"> var source, destination; var directionsService = new google.maps.DirectionsService(); google.maps.event.addDomListener(window, 'load', function () { new google.maps.places.SearchBox(document.getElementById('txtSource')); new google.maps.places.SearchBox(document.getElementById('txtDestination')); }); function GetRoute() { var mumbai = new google.maps.LatLng(18.9750, 72.8258); var mapOptions = { zoom: 20, center: mumbai }; //*********DIRECTIONS AND ROUTE**********************// source = document.getElementById("txtSource").value; destination = document.getElementById("txtDestination").value; var request = { origin: source, destination: destination, travelMode: google.maps.TravelMode.DRIVING }; //*********DISTANCE AND DURATION**********************// var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix({ origins: [source], destinations: [destination], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERIAL, avoidHighways: false, avoidTolls: false }, function (response, status) { if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") { var distance = response.rows[0].elements[0].distance.text; var uzaklyk = parseInt(distance) cikdayci = ' ' if (uzaklyk <= 100) { cikdayci = 250; } else if (uzaklyk <= 200) { cikdayci = 340; } else if (uzaklyk <= 300) { cikdayci = 430; } else if (uzaklyk <= 400) { cikdayci = 520; … -
How to delete a model instance and modify the user profile when another model instance is created django?
I'm trying to do an website where you can see differents match and vote for the team you think that will win. And I'm at the point when the match ends I'd would like to simply create an instance in the django admin with the match and the winner of the match and then delete all the votes and adding some points for every user that has the good vote. So there are my models : class Prognostic(models.Model): match = models.IntegerField() user = models.IntegerField() vote = models.CharField(max_length = 100) def __str__(self): return self.vote class MatchResult(models.Model): match = models.ForeignKey("MatchOpponents") winner = models.ForeignKey("TeamGGC") @receiver(post_save, sender=Prognostic) def voteRepartitionPoints(sender, instance, **kwargs): profil = apps.get_model("userMembers", "Profil") for prognostic in Prognostic().object.filter(match = match_id): if prognostic.vote == winner: user = profil.object.get(user_id = prog.user) user.nbGGCPoints += 50 user.save() prognostic.delete() def __int__(self): return self.match But when I do that, nothing happends, someone has a idea what i do wrong or what i should look for? Thanks! -
Python tornado Too many open files Ssl
If i have many connection on my tornado server, i se error on log Exception in callback (<socket._socketobject object at 0x7f0b9053e3d0>, <function null_wrapper at 0x7f0b9054c140>) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 888, in start handler_func(fd_obj, events) File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 276, in accept_handler callback(connection, address) File "/usr/local/lib/python2.7/dist-packages/tornado/tcpserver.py", line 264, in _handle_connection File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 517, in ssl_wrap_socket context = ssl_options_to_context(ssl_options) File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 494, in ssl_options_to_context context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None)) IOError: [Errno 24] Too many open files and disconnect my client. Tornado open ssl certificate file on ewery connect? Tornado app class VastWebSocket(tornado.websocket.WebSocketHandler): connections = set() current_connect = 0 current_user = 0 status_play_vast = False def open(self): c = Connection() c.connection = self VastWebSocket.connections.add(c) self.current_connect = c def on_message(self, msg): data = json.loads(msg) app_log.info("on message = " + msg) if not 'status' in data: return if data["status"] == "start_vast": VastWebSocket.status_play_vast = True if data["status"] == "end_vast": VastWebSocket.status_play_vast = False app_log.info("status_play_vast = " + str(VastWebSocket.status_play_vast)) if data["status"] == "get_status_vast": self.current_connect.connection.write_message({"status": VastWebSocket.status_play_vast}) return for conn in self.connections: conn.connection.write_message(msg) def on_close(self): if self.current_connect <> 0: VastWebSocket.connections.remove(self.current_connect) def check_origin(self, origin): return True Start tornado server from django command class Command(BaseCommand): help = 'Starts the Tornado … -
OperationalError at /admin/Survey/intro/add/
I was writing a simple admin form, but the error of no such table keeps showing up even though I have done the makemigration and migrate many times it shows no updates. Traceback: File "C:\Python34\lib\site-packages\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "C:\Python34\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (no such table: Survey_intro) was the direct cause of the following exception: File "C:\Python34\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\contrib\admin\sites.py" in inner 224. return view(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in add_view 1508. return self.changeform_view(request, None, form_url, extra_context) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\utils\decorators.py" in bound_func 63. return func.get(self, type(self))(*args2, **kwargs2) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in changeform_view 1408. return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in _changeform_view 1448. self.save_model(request, new_object, form, not add) File "C:\Python34\lib\site-packages\django\contrib\admin\options.py" in save_model 979. obj.save() File "C:\Python34\lib\site-packages\django\db\models\base.py" in save 806. force_update=force_update, update_fields=update_fields) File … -
How to scan image from scanner and perform ocr on that image using python's django web framework?
I want to build a website through which I can scan image from the scanner and perform OCR on it. I had searched a lot on the net and found some paid API from Asprise's Scanner.js and Dynamsoft's Dynamic Web Twain. But I don't want to use any paid API. I also found some links: How Can I Trigger a Scanner from a Browser? TWAIN Browser Plugin But it is of no help. Please help me to solve this problem. -
Upload files dynamically into different s3 buckets with django-storages boto3
I'm using django-storages to upload into an s3 bucket. But I want to be able to upload into a different s3 bucket than what I have set in my default in settings.py My app has a different web page for each bucket and can access the contents. Ideally I would want to pull the bucket name from the url and dynamically set the bucket name to where the file is being uploaded in my code. -
Django not showing updated data from database
I have a django 1.11.4 application running on mysql 5.6.16 on windows. When I add new data or update existing data, the new information does not show up until after I restart. I have tried providing the db_name as suggested here but it has not solved my case. How else can I resolve this? I am using the default web server that comes with django. My complete model is as shown below class Member(AbstractUser): first_name = models.CharField(verbose_name=_('First Name'), blank=False, max_length=100) last_name = models.CharField(verbose_name=_('Last Name'), blank=False, max_length=100) member_number = models.IntegerField(blank=False, unique=True) national_id = models.IntegerField(verbose_name=_('National ID Number'), blank=False, unique=True) phone_number = models.CharField(max_length=50, verbose_name=_('Phone Number')) email = models.EmailField(verbose_name=_('Email'), unique=True, max_length=100, blank=False) username = models.CharField(verbose_name=_('User name'), max_length=50, blank=True, null=True) position = models.CharField(verbose_name=_('Position in Society'), max_length=100, choices=( ('MEMBER', 'Member'), ('COMMITTEE', 'Committee'), ('STAFF', 'Staff'), )) employer = models.CharField(verbose_name=_('Employer'), max_length=250, blank=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['member_number', 'national_id', 'first_name', 'last_name'] class Meta: verbose_name = _('member') verbose_name_plural = _('members') db_table = 'members_member' def get_short_name(self): return self.last_name def __str__(self): return self.get_full_name() My database connection settings are shown below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'open_db', 'USER': 'root', 'PASSWORD': 'rootpass', 'HOST': 'localhost', 'PORT': '3306', } } -
Python: assert if string matches a format
I have some unit tests for my Django API using Django Rest Framework APIClient. Different endpoints of the API return custom error messages, some with formatted strings like: 'Geometry type "{}" is not supported'. I'm asserting the status code from the client responses and error message keys, but there are cases that I'd like to figure what error message is returned to make sure nothing else has caused that error. So I'd like to validate the returned error message against the original unformatted string too. For example if I receive an error message like 'Geometry type "Point" is not supported', I'd like to check if it matches the original unformatted message, i.e. 'Geometry type "{}" is not supported'. The solutions I've thought of so far: First: replacing the brackets in the original string with a regex pattern and see if it matches the response. Second: (the cool idea, but might fail in some cases) using difflib.SequenceMatcher and test if the similarity ratio is bigger than, for example, 90%. So my question is what the other ways of doing such comparison are and whether there is any built-in feature in Python to achieve this. -
Django Multi join query
I am new to django and need to do a query. I can do in sql but I can't seem to figure it out in django. Here it is in SQL. Can someone tell me how to do it in django. select token from api_userprofile join api_userdevice on api_userdevice.user_id=api_userprofile.user_id join api_device on api_device.id=api_userdevice.device_id where api_device.serial=3 My models look like this: class UserDevice(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False) device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False) activation_date = models.DateTimeField(default=timezone.now, null=False) friendly_name = models.CharField(max_length=20, null=True, blank=True) is_owner = models.BooleanField(null=False, default=False) is_admin = models.BooleanField(null=False, default=True) class Device(models.Model): serial = models.CharField(max_length=16, null=False, unique=True) publickey = models.CharField(max_length=44, null=False) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, null=False) token = models.TextField(null=False, blank=True) -
Django makemigration keeps recreating the same migration
I'm using Django 1.9 and I have on model that keeps generating a migration when makemigrations is called even when no change has occured. Here's two examples of two subsequent migration files: Here's 0005_auto_20170830_1841.py: # -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2017-08-30 18:41 from __future__ import unicode_literals from django.db import migrations, models import django.utils.translation class Migration(migrations.Migration): dependencies = [ ('account', '0004_auto_20170830_1801'), ] operations = [ migrations.AlterField( model_name='accounttype', name='description', field=models.TextField(verbose_name=django.utils.translation.ugettext), ), ] And here's 0006_auto_20170830_1846.py which references the previous one: # -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2017-08-30 18:46 from __future__ import unicode_literals from django.db import migrations, models import django.utils.translation class Migration(migrations.Migration): dependencies = [ ('account', '0005_auto_20170830_1841'), ] operations = [ migrations.AlterField( model_name='accounttype', name='description', field=models.TextField(verbose_name=django.utils.translation.ugettext), ), ] What could be causing this behavior? It only happens for this one model. -
Django Rest Framework -- simple GET request hits database multiple times?
Using the Django Rest Framework, I have a simple GET request that I know should only result in 16 records being returned. The GET request isn't filtered at all -- just a simple api/contacts/ and it should return 16 contacts. I am getting my 16 records as expected, but I also see that the database is being queried 12 times!? In my Contact record I do have one field that is a Foreign Key, and not each Contact has this Foreign Key set. So my guess is that I have a case of Django's "lazy querying" going on. Is that right? Is there a way to optimize this? If I have, say, 300 Contact records, I don't want to be hitting the database 500+ times. Can't I just make a single query to the DB and not do all these round trips? -
Django Rest-framework with iOS and android
I would be needing insight from everyone who is willing to support. I have a django web application and I have used the django rest framework to create the REST API and now I want to proceed to mobile development (iOS and android). The Question now is how do I use the REST API created to build an iOS or Android application because I am looking to build a native application. Any one can join the discussion. every tip is appreciated -
Why {% load staticfiles %} required in head tag?
In the below head tag, <head> ..... {% load staticfiles %} <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/> <script src="{% static 'personal/js/myscripts.js' %}"></script> ...... </head> Does link & script tag not suffice to load css styling & JS in DOM? Do we need {% load staticfiles %}? -
Python-Django Static files not being found
My settings: STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'), ) STATIC_URL = '/static/' My urls: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), url(r'^blog/view/(?P<slug>[^\.]+)', view_post), url(r'^blog/category/(?P<slug>[^\.]+)', view_category), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My directory: website blog website __init__.py settings.py urls.py wsgi.py static css js images templates db.sqlite3 manage.py My HTML: <script src="{% static 'js/html5shiv.min.js' %}"></script> <script src="{% static 'js/respond.min.js' %}"></script> I have been struggling bringing in my static files into my Django project for hours. Now, I believe I brought them in correctly but my webpage still gets a 404 error claiming they are not found. When I go to the localhost link that my js, or css file should be in I get the error: "A server error occurred. Please contact the administrator." I set up my URL as said in the documentation https://docs.djangoproject.com/en/1.11/howto/static-files/ So I am very confused on where to go from here on out. Any help would go a long way. Thanks -
How can I display PostgreSQL database in Docker container?
I have both Django project and PotgreSQL database in Docker container. My question is how can I display my database? I was trying docker exec -ti myproject_django_1 /bin/bash and docker exec -ti myproject_db_1 /bin/bash but in both cases I can't use psql because of psql: FATAL: role "root" does not exist or bash: psql: command not found -
Django WebSocket is closed before the connection is established with wss://
Been making progress on learning Django Channels, and proxying traffic through Apache. Been using tutorial here: https://github.com/jacobian/channels-example So far, I have been successful at completing tutorial. Even provided some assistance to another question on this site: Websocket disconnects immediately after connecting (repeatedly) The problem that I have is that while I am able to proxy the traffic for http over Apache, I am unable to do the same thing with https. WebSocket connection to 'wss://example.com:8001/chat/dark-fog-0991/' failed: WebSocket is closed before the connection is established. This is the same errror I received prior to adding message.reply_channel.send({'accept':True} Adding that line fixed it for requests to ws://example.com:8001/chat/dark-fog-0991/ But, the error occurs on: wss://example.com:8001/chat/dark-fog-0991/ apache.conf <VirtualHost *:80> Servername example.com SuexecUserGroup "#1001" "#1001" ProxyPass "/chat.*" "ws://127.0.0.1:8001/" ProxyPassReverse "/chat.*" "ws://127.0.0.1:8001/" ProxyPass "/" "http://127.0.0.1:8001/" ProxyPassReverse "/" "http://127.0.0.1:8001/" </VirtualHost> <VirtualHost *:443> Servername example.com SuexecUserGroup "#1001" "#1001" ProxyPass "/chat.*" "ws://127.0.0.1:8001/" ProxyPassReverse "/chat.*" "ws://127.0.0.1:8001/" ProxyPass "/" "http://127.0.0.1:8001/" ProxyPassReverse "/" "http://127.0.0.1:8001/" SSLEngine on SSLProxyEngine on SSLCertificateFile /home/example/domains/example.com/ssl.cert SSLCertificateKeyFile /home/example/domains/example.com/ssl.key SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 </VirtualHost> I tried changing ProxyPass "/chat.*" "ws://127.0.0.1:8001/" to ProxyPass "/chat.*" "wss://127.0.0.1:8001/" Still doesn't work. Do I need to be doing anything different with my daphne interface? -
Using multiple models on user creation
I'm looking to use an Account model I created to handle financial data about a user. How do I ensure django-allauth will create this model when registering users and will link through keys both the new user and the Account model? -
How can I share with facebook the respective post?
I have a django blog on the web and I finally put the facebook share plugin in the one. But everytime I share, I can share the same image, the image is a static image from the head of base.html. I am using django 1.10,python3.6 and no one share plugin. How can I share respective image from my respective page? Very thanks! ps: I think any others code is be unnecessary. views.py def index(request): posts = Evento.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'core/index.html', {'posts': posts}) from urllib.parse import quote_plus def post_detail(request, pk): post = get_object_or_404(Evento, pk=pk) share_string = quote_plus(post.apresentacao) context = { "title": post.nome, "instance": post.foto, "share_string": share_string, } Evento.objects.get(pk=pk) return render(request, 'core/post_detail.html', {'post': post}) def index(request): posts = Evento.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'core/index.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Evento, pk=pk) share_string = quote_plus(post.apresentacao) context = { "title": post.nome, "instance": post.foto, "share_string": share_string, } Evento.objects.get(pk=pk) return render(request, 'core/post_detail.html', {'post': post}) models.py class Evento(models.Model): nome = models.CharField(max_length=200, null=False, blank=False) apresentacao = models.TextField(null=False, blank=False) foto = CloudinaryField('foto', null=True, blank=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.nome def get_absolute_url(self): #return reverse("detalhe", kwargs={"pk": self.pk}) return "/post/%s" %(self.pk) and post_detail.html <div class="post"> <div class="fb-share-button" data-href="{{ … -
How to set the default value of a dropdown menu in Django?
Currently, I have the following 2 Drop-Down menus to display the years and weeks but I want to display the current year and current week, respectively, inside of these menus. Django form from django import forms class DropDownMenuForm(forms.Form): week = forms.ChoiceField(choices=[(x,x) for x in range (1,53)]) year = forms.ChoiceField(choices=[(x,x) for x in range (2016,2021)]) Template to display the menus <form id="search_dates" method="POST" action="{{ action }}"> {% csrf_token %} <div class="row"> <div style="display:inline-block"> <h6>Select year</h6> <select name="select_year"> <option value={{form.year}}></option> </select> </div> <div style="display:inline-block"> <h6>Select week</h6> <select name="select_week"> <option value={{form.week}}></option> </select> </div> <button type="submit">Search</button> </div> </form> Display the current week and year from datetime import date date.today().isocalendar()[1] date.today().year How can I connect the Display the current week and year code with the template, so I can see the current year and week selected in the dropdown menus? -
django models.DoesNotExist: mahching query does not exist
I am using Django 1.11 and typed below codes in models.py. It works fine when makemigrations, but it notices the error of "models.DoesNotExist" when do migrate. The code in models.py: class RecordType(models.Model): name = models.CharField(max_length=100, default='out',blank=True, verbose_name="name") def get_record_type_default(): return RecordType.objects.get_or_create(pk=1)[0].id class PrimaryCategory(models.Model): type = models.ForeignKey(RecordType, on_delete=models.PROTECT, default=get_record_type_default, verbose_name="type") def get_primary_category_default(): return PrimaryCategory.objects.get_or_create(pk=1)[0].id class SecondaryCategory(models.Model): primary_category = models.ForeignKey(PrimaryCategory, on_delete=models.PROTECT, default=get_primary_category_default, verbose_name="1st category") def get_secondary_category_default(): return SecondaryCategory.objects.get_or_create(pk=1)[0].id class Record(models.Model): secondary_category = models.ForeignKey(SecondaryCategory, on_delete=models.PROTECT, default=get_secondary_category_default, verbose_name="2nd category") And here is the error message while doing migrate: File "C:\Users\myname\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 464, in get_or_create return self.get(**lookup), False File "C:\Users\myname\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 380, in get self.model._meta.object_name datacore.models.DoesNotExist: SecondaryCategory matching query does not exist. -
Alternative ways of styling class-based form fields
In Django, one applies CSS styling to class-based form fields in forms.py (or equivalent). My question: is it impossible to do it any other way inside a Django project? I'll accept the answer even if the answer is "it's impossible". Hacks and tricks are acceptable as well. Illustrative examples would be great. I've been a Django developer since a few years. It's worth it to know tricks, hacks or patterns experienced Djangonauts have been using. This question has been one of my pet peeves for a while. So I thought I'd pose it as a question to the community. p.s. here's an example of a Django form where I've styled in the class-based form: class SampleForm(forms.Form): description = forms.CharField(max_length=250) def __init__(self,*args,**kwargs): super(SampleForm, self).__init__(*args,**kwargs) self.fields['description'].widget.attrs['class'] = 'btn bcg' self.fields['description'].widget.attrs['style'] = 'background-color:#F8F8F8; width:98%; color: #1f8cad;' self.fields['description'].widget.attrs['autocomplete'] = 'off' -
AJAX update variable in html django
I'm trying to update a variable in an html page after it has been updated using an AJAX call: {% for q in questions %} {% if qdelete == forloop.counter %} <div align= Center> <button type="submit" class="btn btn-primary btn-small" id="qyesbtn" name="qyesbtn" value="qyesbtn_{{q.id}}">Yes &raquo;</button> </div> <div align= Center> <button type="submit" class="btn btn-primary btn-small" id="qnobtn" name="qnobtn" value="qnobtn">No &raquo;</button> </div> {% else %} <button type="button" id="qbtn" class="btn btn-primary btn-large" name="qid" value="{{forloop.counter}}" onclick="SetDeleteNum({{forloop.counter}})">Delete &raquo;</button> {% endif %} {% endfor %} <script> function SetDeleteNum(d) { var num = -1 num = d console.log('num: '+num) var page = $(this) $.ajax({ type: "POST", url: "{% url 'home' %}", data: { 'csrfmiddlewaretoken': $('input[name="csrfmiddlewaretoken"]').val(), 'qid': num }, dataType: 'json', success: function (data) { console.log('aa'+JSON.stringify(data)) page.html(data); }, error: function(e){ console.log('err: '+JSON.stringify(e)) } }); } </script> The value qdelete should be updated to 'num' after the AJAX call but it is still as before although I can see from the logs that the qdelete has the new value assigned but it simply not displayed in the page. I also tried to put the new 'data' in the new html using the line 'page.html(data);' but no luck. Any idea? -
Django Rest Framework HyperLinkedRelatedField: allow id instead of url for POSTS requests
I would like to allow a HyperLinkRelatedField to accept just an id instead of requiring a hyperlink to create a new instance of an object, but for get requests I would like to return the hyperlink not just an id but it appears to be either one or the other. Is this possible? class Blog(serializers.HyperlinkedModelSerializer): class Meta: model = Blog fields = ('url', 'id') class Comment(serializers.HyperlinkedModelSerializer): blog = serializers.HyperlinkedRelatedField(view_name='blog-detail', queryset=Blog.objects.all()) class Meta: model = Comment fields = ('url', 'text', 'blog') GET Request for Comment returns (This is perfect): {'url': 'mysite.fake/comments/1', 'text': 'test text', 'blog': 'mysite.fake/blog/1'} POST Request requires: {'text': 'test text', 'blog': 'mysite.fake/blog/1'} I want to also be able to pass: {'text': 'test text', 'blog': '1'}