Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to execute git command through Django migration?
I have the requirement to execute a git command in a Django migration. I need to clear the contents of a directory via a Django migration because we do not have access to the production server directly. Being new to both Django and git, I have no idea of how this could be achieved. Any help would be highly appreciated. TIA -
What to learn to implement backend of a website?
My friend, and I are learning websites. He accomplished his part by learning HTML, CSS, and even JAVASCRIPT. I on other hand have failed miserably. I learnt Python, but it's API's like DJANGO, and FLASK are a no go. I simply cannot understand them. Is there a simpler, yet effective technology out there for backend? Please help. Thank you. -
Django : select all columns when innerjoin using extra without foreignkey
I have two tables and they do not have foreign key or relationship. However, I have to do join and get all columns from both tables. This is the query I've made. query = Sms.objects \ .extra(tables=['product'], where=['product.id=sms.sms_id']) When I printed raw query, I could check it only gets tables from Sms model, not from product model. Is there any way to get columns from product model? -
When I excute TradeRecord.objects.create(**traderecord_data) there raise TypeError
In my serializer I override the create method: class CloudServerPayOrderSerializer(ModelSerializer): class Meta: model = TradeRecord exclude = ( 'id', 'name', 'traderecord_num', 'money', 'balance', 'desc', # 自己生成 ) def create(self, validated_data): # 先支付 TODO # 再生成交易记录 user = getUserFormSerializer(self) # --- 数据 name = "购买云服务器" traderecord_num = generateTradeRecordNum(userid=user.id) #order_id = validated_data.pop("order") #order = Order.objects.get(id=order_id) order = validated_data.pop("order") order.order_status = "已支付,未完成" order.save() paytype = validated_data.pop("paytype") money = order.cost account = Account.objects.get(user=user) balance = account.balance desc = "购买云服务器" traderecord_data = { "traderecord_num": traderecord_num, "name":name, "order": order, "money": money, "balance": balance, "paytype":paytype, "desc":desc, } traderecord = TradeRecord.objects.create(**traderecord_data) return traderecord But when I execute the traderecord = TradeRecord.objects.create(**traderecord_data) line, I get TypeError: TypeError at /api/userfront_product/cloudserver/order/pay/ init() got an unexpected keyword argument 'paytype' I use debug to test it, when debug the traderecord = TradeRecord.objects.create(**traderecord_data) step: enter image description here And I also copy the data out: {'paytype': '支付宝', 'order': <Order: 用户名: vcpus:1核 ram:1G 系统盘:SSD40GB 数据盘:SSD0GB 1M >, 'money': Decimal('220.00'), 'name': '购买云服务器', 'traderecord_num': 'TRN15113262838882', 'desc': '购买云服务器', 'balance': Decimal('0.00')} My TradeRecord model is bellow: class TradeRecord(models.Model): traderecord_num = models.CharField(unique=True, max_length=32, help_text="交易记录编号") name = models.CharField(max_length=64, help_text="交易记录名称") order = models.OneToOneField(to=Order, null=True , related_name="traderecord", help_text="对应的订单") money = models.DecimalField( decimal_places=2, default=0.0, max_digits=8, help_text="交易记录金额" ) # 正:代表账户入款 负:出款 balance = models.DecimalField( decimal_places=2, … -
deploying django with gunicorn (and multiple django apps)
I am trying to deploy my first django app to google app engine but am having a hard time follow docs as many are out of date. I have a project that I started from this (https://github.com/Shopify/shopify_django_app) but cant deploy with the outdated docs in the readme. -I dont know my project name -I am unfamiliar with gunicorn -and I'm unsure where to put my wsgi file as I have multiple django apps Every tutorial seems to only have one app (https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/appengine/flexible/hello_world_django) # app.yaml runtime: python env: flex entrypoint: gunicorn -b :$PORT main:app health_check: enable_health_check: True check_interval_sec: 5 timeout_sec: 4 unhealthy_threshold: 2 healthy_threshold: 2 handlers: - url: /static static_dir: static/ expiration: '30d' - url: /.* script: djangoappengine/main/main.py -
Django Rest Framework: Duplicate key value violates unique constraint
I have a problem with Django Rest Framework. This app I'm building is Avatar. User can update his/her own avatar, then avatar auto save with my path I defined (/users_id/photoset_id/filename.png). So I make function to save like this code: def avatar_file_path(instance, filename): ext = filename.split('.')[-1] filename = '%s.%s' % (instance.id, ext) return "users/%s/avatar/%s_%s" %(instance.user.id, instance.photoset.id, filename) class Avatar(models.Model): user = models.ForeignKey(User, related_name='avatar_set', null=True) photoset = models.ForeignKey(PhotoSet, null=True, blank=True) primary = models.BooleanField(default=True) caption = models.TextField(blank=True, null=True) image = models.ImageField(max_length=1024, upload_to=avatar_file_path) is_public = models.BooleanField(_('is public'), default=True, help_text=_('Public photographs will be displayed in the default views.')) date_uploaded = models.DateTimeField(default=datetime.datetime.now) def save(self, force_insert=False, force_update=False, *args, **kwargs): # Make one primary Avatar if self.primary: avatars = Avatar.objects.filter(user=self.user, primary=True).exclude(id=self.id) avatars.update(primary=False) # Set default photoset if self.photoset is None: if not PhotoSet.objects.filter(user=self.user, photoset_type=3).exists(): PhotoSet.objects.create(user=self.user, photoset_type=3, title='Profile Pictures') self.photoset = PhotoSet.objects.get(user=self.user, photoset_type=3) if PhotoSet.objects.filter(user=self.user, photoset_type=3).exists(): self.photoset = PhotoSet.objects.get(user=self.user, photoset_type=3) # Model Save override if self.id is None: saved_image = self.image self.image = None super(Avatar, self).save(*args, **kwargs) self.image = saved_image super(Avatar, self).save(force_insert, force_update, *args, **kwargs) When I create serializers POST with Django Rest Framework: class AvatarCreateUpdateSerializer(ModelSerializer): class Meta: model = Avatar fields = [ 'user', 'image', 'caption', 'is_public', ] It goes problem: Error Log Tracking in line: super(Avatar, self).save(force_insert, … -
Using {%extends var_name%} not being re-evaluated in jinja2 template
I am using Django and Jinja2 for email templating. Our template uses {% extends %} to dynamically derive from a base template depending on the style of email chosen by the user. It appears that the {extends} is never re-evaluated. Whichever value was supplied for the base_template parameter is always re-used. It feels like the two where textually combined. This uses the default DjangoTemplates engine I've logged all calls to cached.Loader and the base template is never re-requested {% include footer %} seem to be re-fetched from the loader every time Our email templates look like this: {% extends base_template %} {% block subject_line %} New Something Happened{% endblock %} {% block html_content %} <h2>Hello {{ name }},</h2> {% endlbock %} And we call it (through django) with context like: ctx = { base_template="emails/base/happy.html", dyn_footer="emails/footers/please_reply.html" } send_templated_email("gretting.html", ctx) I'm not sure about how Jinja2 actually behaves with {extends} and didn't see anything in the documentation saying this will or will not happen. -
Managing specific static pages acoss multiple domains in wagtail
I know wagtail can handle multiple domains to manage the sites, but after reading the documentation and browsing around what I don't understand is how exactly this works for static pages or really even where to get started. Non-static pages: I understand that the "Page" essentially replaces the model and you can defined the "content_panels" to determine what fields are editable and kick it off to a view to be rendering. Yet, I don't understand how the "@route" works with respect to pre-existing url schemas (Trying to integrate into a pre-existing project). I essentially want to move to using pages for my models so that they're openly editable through admin but keep my same url schema / setup. Maybe I misunderstand how wagtail works.... Static pages: (Main question) Right now I'm using a middleware to detect what domain im on, have a bunch of domains pointing to my app on a server through CDN since they share the same codebase, and then patch the root urlconf to use that apps urls file. So, I have domains xyz.com, abc.com, def.com, etcetera which are controlled by their respective apps (code is interrelated) and I'm simply rendering the (non-wagtail) template for their static … -
Django get_context_data error
i'm trying to create a custom get_context_data, but i'm getting the error get_context_data() takes 1 positional argument but 2 were given, and I don't know why can someone help me?, why i'm getting this error?, and how i can solve it? thanks in advance class JobDetail(DetailView): model = Job template_name = 'employer/job_detail.html' def get_context_data(self, **kwargs): context = super(JobDetail, self).get_context_data(kwargs) job = Job.objects.all() sign_job = False if self.request.user.is_authenticated(): get_job = SignJob.objects.filter(user=self.request.user, job=job) # TODO:look at how to get the job the right way if self.request.method == 'POST': SignJob.objects.create(user=self.request.user, job=job) sign_job = get_job.exists() context['sign_job'] = sign_job return context -
Not Null constraint issue should be appearing = django
I have a django project and I am trying to add an activity based on a model that I create. I am entering all of the required fields but for some reason, I cant figure out where this error is coming from. I feel like it is something small but I am getting coders block... here is the error: IntegrityError at /groups/create/ NOT NULL constraint failed: groups_groupactivity.group_id Request Method: POST Request URL: http://127.0.0.1:8000/groups/create/ Django Version: 1.11.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: groups_groupactivity.group_id Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 328 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/decorators.py in _wrapped_view return view_func(request, *args, **kwargs) ... ▶ Local vars /Users/omarjandali/Desktop/split/split/groups/views.py in create_group category = 2, ... ▶ Local vars /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/manager.py in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ... ▶ Local vars here is the views: group_description_user = 'You created ' + name group_description_general = user.username + ' created ' + name # activites for creating the group: group_user = GroupActivity.objects.create( user = user, description = group_description_user, category = 2, ) group_general = GroupActivity.objects.create( user = user, description = group_description_general, category = 1 ) can anyone help me figure out this issue and where it is coming from . Here is the model that I have right … -
Whats the `self` means in create(self, validated_data) method?
Whats the self means in create(self, validated_data) method ? I have a serializer named CloudServerPayOrderSerializer, and I want to override the create() method. class CloudServerPayOrderSerializer(ModelSerializer): class Meta: model = TradeRecord exclude = ( 'id', 'name', 'traderecord_num', 'money', 'balance', 'desc', ) def create(self, validated_data): user = getUserFormSerializer(self) ... You see, I am override the create method, and I want to get user through self. so there is a util method getUserFormSerializer. But I don't know the self here stands for what, whether it is stand for CloudServerPayOrderSerializer, if is not, I can not name the util method as getUserFormSerializer. -
Django Debugger not showing cache use
I am trying to implement cache on my django models queryset . But my django begugger is not showing the cache use . Here is my code def index(request): if request.method == 'POST': if cache.get('alllog'): alllog=cache.get('alllog') else: alllog = ActivityLog.objects.all() cache.set('alllog',alllog) data = [] for log in alllog.iterator(): data.append( { 'id': log.id, 'user_id': log.user.username, 'description': log.description, 'timestamp': log.timestamp.strftime('%Y-%m-%d %H:%M:%S'), } ) data = json.dumps(data) return HttpResponse(data) return render(request,'dashboard/activitylog.html') Is it the proper way to implement cache on my queryset ? I am using redis server and the cache is being sucessfully set up . But i cant use it . -
Django filter query with foreign key
I want to filter query based on three user inputs. Depart City, Arrive City and Date. Depart City and Arrive city are on the same table called Route while the TravelDate is a foreign key in Route. My model class TravelDate(models.Model): start_date = models.DateField(null = True) interval = models.IntegerField(null = True) class Route(models.Model): depart_city = models.CharField(max_length=50, null=True, blank=False) arrive_city = models.CharField(max_length=50, null=True, blank=False) driver = models.ForeignKey(Driver) schedule = models.ForeignKey(Schedule) traveldate = models.ForeignKey(TravelDate) My View def newpage(request): if 'origin' in request.GET and request.GET['origin']: q = request.GET['origin'] c = request.GET['dest'] d = request.GET['travelDate'] results = Route.objects.filter(depart_city=q, arrive_city=c) return render(request,'busapp/newpage.html', {'results': results}) else: return render(request, 'busapp/newpage.html',{}) In Views how can i make one query that will filter depart_city, arrive_city, and TravelDate of those routes based on user inputed. If a bus is available on that date from city A to city B will be calculated by doing doing something like this if (d - TravelDate.start_date)% TravelDate.interval =0 then display the results to the user. I cannot get this right. I'm new to Django and trying to learn. -
google compute platform port setting
I have already opened the ports but its still not working. From gcloud on my local machine: C:\Program Files (x86)\Google\Cloud SDK>gcloud compute firewall-rules list To show all fields of the firewall, please show in JSON format: --format=json To show all fields in table format, please see the examples in --help. NAME NETWORK DIRECTION PRIORITY ALLOW DENY default-allow-https default INGRESS 1000 tcp:443 default-allow-icmp default INGRESS 65534 icmp default-allow-internal default INGRESS 65534 tcp:0-65535,udp:0-65535,icmp default-allow-rdp default INGRESS 65534 tcp:3389 default-allow-ssh default INGRESS 65534 tcp:22 django default EGRESS 1000 tcp:8000,tcp:80,tcp:8080,tcp:443 django-in default INGRESS 1000 tcp:8000,tcp:80,tcp:8080,tcp:443 From the instance on google cloud: admin-u5214628@instance-1:~$ wget localhost:8080 --2017-11-22 01:23:56-- http://localhost:8080/ Resolving localhost (localhost)... 127.0.0.1 Connecting to localhost (localhost)|127.0.0.1|:8080... connected. HTTP request sent, awaiting response... 302 FOUND Location: http://localhost:8080/login/?next=/ [following] --2017-11-22 01:23:56-- http://localhost:8080/login/?next=/ Connecting to localhost (localhost)|127.0.0.1|:8080... connected. HTTP request sent, awaiting response... 200 OK Length: unspecified [text/html] Saving to: ‘index.html’ index.html [ <=> ] 6.26K --.-KB/s in 0s 2017-11-22 01:23:56 (161 MB/s) - ‘index.html’ saved [6411] But via the external ip, nothing is shown: http://35.197.1.158:8080/ -
DJANGO Update dont applied changes in database
def registrar(request): form = RegForm(request.POST or None) context = { "form":form } if request.method == 'POST': form = RegForm(request.POST) if form.is_valid(): b = form.cleaned_data['folioboleto'] n = form.cleaned_data['nombre'] aP = form.cleaned_data['apellidoPaterno'] aM = form.cleaned_data['apellidoMaterno'] fecha = form.cleaned_data['fechaDeNacimiento'] g = form.cleaned_data['genero'] e = form.cleaned_data['email'] tel = form.cleaned_data['telefono'] di = form.cleaned_data['direccion'] c = form.cleaned_data['ciudad'] est = form.cleaned_data['estado'] actP = form.cleaned_data['actividadPrincipal'] cSE = form.cleaned_data['comoSupoEvento'] aF = form.cleaned_data['aceptoFotos'] obj = Cliente.objects.create(Nombre=n,ApellidoPaterno=aP,ApellidoMaterno=aM,FechaDeNacimiento=fecha,Genero=g,Email=e,Telefono=tel,Direccion=di,Ciudad=c,Estado=est,ActividadPrincipal=actP,ComoSupoEvento=cSE,AceptoFotos=aF) bole = Boleto.objects.get(Folio=b) if bole.Folio == b: bole.Estatus = '2' bole.Cliente_id = obj.id bole.save(update_fields=['Estatus']) the bole dont save changes. -
Querying hits per hour on Django timezone aware setup
I'm someone new at the whole Django thing and find myself stuck on the whole timezone awareness kerfuffle. Problem I would like to query the database to create a report such as: Time of day | Clicks -------------------- 12 am | 3 1 am | 12 2 am | 28 3 am | 48 ... I would like these to be shown based on the timezone of the user that created the event, not in the timezone setting of the system. Current approach Given the following model (simplified to avoid clutter) and assuming proper libraries are imported. class Event(models.Model): type = models.CharField() created = models.DateTimeField() user = models.CharField() I then created the following in tests.py def test_events_per_day(self): # creates events in two timezones date = datetime(2017, 1, 13, 12, 0, 0, 0, pytz.timezone('Pacific/Auckland')) date2 = datetime(2017, 1, 13, 12, 0, 0, 0, pytz.timezone('UTC')) Event.objects.create( type='click', created=date.strftime('%Y-%m-%dT%H:%M:00.%f%z'), user = 'user 1' ) Event.objects.create( type='click', created=date2.strftime('%Y-%m-%dT%H:%M:00.%f%z'), user = 'user 2' ) event_per_day_count = Event.objects \ .filter(type='click') \ .annotate(day=TruncDay('created')) \ .values('day') \ .annotate(events=Count('user', distinct = True)) \ .order_by('day') self.assertEquals(over_time.first().get('events'), 2) # FAIL: AssertionError: 1 != 2 # PASS if I use the same date for both When I look at the database and … -
Django struggling to make migrations
I'm currently learning django and doing the tutorial from Django Rest Framework. The problem is the following. I have the following tree: . ./tutorial ./tutorial/manage.py ./tutorial/tutorial ./tutorial/tutorial/__init__.py ./tutorial/tutorial/__init__.pyc ./tutorial/tutorial/settings.py ./tutorial/tutorial/settings.pyc ./tutorial/tutorial/snippets ./tutorial/tutorial/snippets/__init__.py ./tutorial/tutorial/snippets/__init__.pyc ./tutorial/tutorial/snippets/admin.py ./tutorial/tutorial/snippets/apps.py ./tutorial/tutorial/snippets/apps.pyc ./tutorial/tutorial/snippets/migrations ./tutorial/tutorial/snippets/migrations/__init__.py ./tutorial/tutorial/snippets/models.py ./tutorial/tutorial/snippets/tests.py ./tutorial/tutorial/snippets/views.py ./tutorial/tutorial/urls.py ./tutorial/tutorial/wsgi.py I added dependencies in settings.py by adding 'rest_framework', 'snippets.apps.SnippetsConfig', in INSTALLED_APPS. The problem is that when I do ElbattoresMacbook:tutorial elbattore$ python manage.py makemigrations snippets. I have the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/anaconda/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/anaconda/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/anaconda/lib/python2.7/site-packages/django/apps/config.py", line 142, in create app_module = import_module(app_name) File "/anaconda/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named snippets What's wrong with what I do?? I'm strictly following http://www.django-rest-framework.org/tutorial/1-serialization/ But it doesn't work... Thanks guys -
NoReverseMatch at/ in base.html
so when I run my code locally, it works fine. But when I run it online I get NoReverseMatch at/. I've gone through the code for the past 2 hours but still can't figure out the reason why. base.html {% load staticfiles %} <html> <head> <title>Ranindu's Blog</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="page-header"> {% if user.is_authenticated %} <a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a> {% endif %} <h1><a href="/">First Blog Success!</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'), ] Error Screenshot in base.html line 13 -
HTTP request 408 error(Client request timeout) over mobile network. Django + Gunicorn + Nginx
I have faced with strange issue. My API has endpoint on which i am using PATCH(tried also PUT and POST - same result) to send json with jsonarray(request body size typically is 40KB) from mobile phone. When i am doing this using Wi-Fi - all works fine. But if i am using mobile network, i am facing with SocketConnection Timeout(in Retrofit/Kotlin) with some phones(iOS works perfect). From nginx access.log : domain - - [21/Nov/2017:16:33:01 +0000] "PATCH /endpoint/ HTTP/1.1" 408 0 "-" "Dalvik/2.1.0 (Linux; U; Android 6.0.1; Nexus 5 Build/M4B30Z)" Nginx config : server { listen port; server_name domain; client_max_body_size 32m; proxy_connect_timeout 75s; proxy_read_timeout 300s; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/apps/api; } location / { include proxy_params; proxy_pass http://unix:/home/user/apps/api/api.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot Gunicorn config : respawn setuid root setgid www-data chdir /home/user/apps/api exec /home/user/virtualenvs/apienv/bin/gunicorn --workers 3 --timeout=90 --bind unix://api.sock api.wsgi:application -
Raw query and row level access control over multiple models in Django
I'm trying to provide an interface for the user to write custom queries over the database. I need to make sure they can only query the records they are allowed to. In order to do that, I decided to apply row based access control using django-guardian. Here is how my schemas look like class BaseClass(models.Model): somefield = models.TextField() class Meta: permissions = ( ('view_record', 'View record'), ) class ClassA(BaseClass): # some other fields here classb = models.ForeignKey(ClassB) class ClassB(BaseClass): # some fields here classc = models.ForeignKey(ClassC) class ClassC(BaseClass): # some fields here I would like to be able to use get_objects_for_group as follows: >>> group = Group.objects.create('some group') >>> class_c = ClassC.objects.create('ClassC') >>> class_b = ClassB.objects.create('ClassB', classc=class_c) >>> class_a = ClassA.objects.create('ClassA', classb=class_b) >>> assign_perm('view_record', group, class_c) >>> assign_perm('view_record', group, class_b) >>> assign_perm('view_record', group, class_a) >>> get_objects_for_group(group, 'view_record') This gives me a QuerySet. Can I use the BaseClass that I defined above and write a raw query over other related classes? >>> qs.intersection(get_objects_for_group(group, 'view_record'), \ BaseClass.objects.raw('select * from table_a a' 'join table_b b on a.id=b.table_a_id ' 'join table_c c on b.id=c.table_b_id ' 'where some conditions here')) Does this approach make sense? Is there a better way to tackle this problem? Thanks! -
dynamically add instances of a model in Django forms
I have the following model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class CalEvents(models.Model): user = models.ForeignKey(User) activity = models.CharField(max_length=256, unique=False, blank=True) activity_type = models.CharField(max_length=30, unique=False, blank=True) activity_code = models.CharField(max_length=30, unique=False, blank=True) def __str__(self): return "Activity, type and code for the calendar events of @{}".format(self.user.username) What I would like to know is how can I dynamically add instances of that model with forms. I'm imagining something like having a form for the first instance (with fields "activity", "activity_type" and "activity_code") and then, if the user clicks a "plus sign" (or whatever), (s)he can add a second, third...Nth instance to the database. -
Django Foreign Key lookup into Template
Good afternoon, I have a ticket, notes for the ticket, & the user who constructed the note. When loading the ticket detail, I want to output the username of the person who wrote it. I send all the notes for a given ticket to the template, but this contains the foreign key (ID) for the user. (i.e. 1, 2, 3) and not the username (i.e. jdoe, syzerman, jsmith). How can I convert the ID to the username when I passing back all notes? Views function rpt = Sir.objects.get(pk=sir_id) status = Sir_Status.objects.get(pk=rpt.status_id) rpt_notes = Notes.objects.filter(sir_id=sir_id).order_by('-note_date') form = NotesForm(initial={'status' : status.status}) return render(request, 'details.html', {'rpt' : rpt, 'notes' : rpt_notes, 'form' : form}) Template {% for note in notes %} On {{ note.note_date }}, {{ note.user_set.username }} noted: {{ note.note }} <hr /> {% endfor %} If I did a {{ note.note_owner }} it would just output the number 1,2,3... Thanks for your help as I get my mind around Django. -
Custom readonly_fields and has_delete_permission on Django admin TabularInline
I have an admin.TabularInline. I need to configure dinamically readonly_fields and I need to enable or disable deleting with has_delete_permission checking some fields in current object. Is possible this? What have I check in this method ? def has_delete_permission(self, request, obj=None): Where can I found che current saved object (not parent object)? -
Shopify API to Django
I am trying to pull and display total order volume from a Shopify store in a table row via private app. I am familiar with Shopify's API and have been able to pull the relevant data by calling 'https://API_KEY:PASSWORD@shop.myshopify.com/admin/orders/count.json?status=any' and retrieving the count in JSON. I do not, however, understand how to parse the JSON and display the count in a table. I'm also unsure if I should use Python or jQuery to achieve this. Any assistance would be greatly appreciated! -
How to count the number of resuts of an if on Django built in templates
I have the following situation: {% for subject in subjects %} {% if subject.media < 60 %} {{ subjects|length }} {% endif %} {% endfor %} The result of that is "161616", because I have 16 subjects on my database, but I want to show the number of subjects that are below the media, like "3".