Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set a variable (using set tag) in django template?
I want something like this inside django template. I want to use these variables in javascript file or another template file. {% set titles = { 'table': form._meta.model._meta.verbose_name_plural.title(), 'form': form._meta.model._meta.verbose_name.title() } %} {% set dtable = "dt_" + page %} How can I get set tag? Your answer would be helpful for me. -
adding to a query set from another queryset django
I have a query set that looks like this. <QuerySet [<Room: localhost>, <Room: chat>]> which is inside room <QuerySet [<RoomShare: Shared room u'208349023840928', for company 2>]> which is stored inside roomshare If I print the second query to get the name of the room i just use. for x in roomshare: print(x.room.room_name) which gives me `Room Fun` I would like to add this Room_Fun to the first query set. And it should look like this <QuerySet [<Room: localhost>, <Room: chat>, <Room: Room_Fun]> I tried different method's but couldn't achieve the result I want. Also the second query set can have more than 1 roomShare, so I might have to use a forloop to add multiple of times to the first query set. -
Django 1.11 PostgreSQL multiprocess fail to work
Here's a website I've beening working on. It scrapes data from certain urls. I use multiprocessing module to make it faster, but the data cannot be saved. I tried put this under the worker function, but it still can't work.connection.close() Seems like the database just gets stuck in: data = Data(url=url, title=tile) ps: I'm using PostgreSQL 10, and Django 1.11.5, Python 3.5. def getSoup(url): # get beautifulsoup object from the url def getData(soup, url): title = getTitle(soup) # read title from the soup data = Data(url=url, title=title) data.save() print(url, 'Data saved!') def task(url): # connection.close() # I tried put this here, but it's not working soup = getSoup(url) # try for the first time while soup == 1: try: soup = getSoup(url) # if it failed to get soup, it'll return 1 and try again except TimeoutError: pass getData(soup, url) def scrape(): pool = multiprocessing.Pool(processes=10) pool.map(task, get_urls()) # get_urls is a urls generator pool.close() scrape() -
Django: can database migrations be reverse engineered?
I've been trying to wrap my head around how to avoid creating a mess with Django migrations. I tried "don't delete migrations" and for the most part that worked, but when I wanted to delete an app off my codebase, I struggled and fell back into a mess. I was thinking, it would be far easier to untangle these issue if one could: 1- delete all current migrations 2- create a migration from an existing database schema (rather than from Django models) <- this is the missing step 3- run migrate --fake to synch DB with migrations 4- run makemigrations to add any non-applied changes to the migration chain (this time from Django models) 5- run migrate to synch the DB with the new changes The only step that I don't know how to do is step 2. Is this doable? I don't know of any built in module or tool that does this so I'm wondering why not. Some research showed python manage.py inspectDB gets me partially through step 2. -
Django model foreign key filter
The problem: I have two django models: class Driver(models.Model): event = models.ForeignKey('Event') last_event = ???? ... ... class Event(models.Model): date = models.IntegerField() Now i need only LAST event for each driver PREFETCHED and CACHED d = Driver.objects.prefetch_related('last_event???') How do i achieve it? Is there any way to limit relation as something like: last_event = models.ForeaignKey('Event', filter = ...??? ) -
Django use templatetag API Wrapper
I'm writing a custom API wrapper for automating stuff on multiple devices having a REST API. Authentication to these devices is via csrf token. I'm struggling making a connection via form input using the devices API as custom tag. In addition im not really sure if this is the right approach to start a project like this. app/views.py def index(request): context = {} template = loader.get_template('app/index.html') return HttpResponse(template.render(context, request)) def webbase_html(request): context = {} load_template = request.path.split('/')[-1] template = loader.get_template('app/' + load_template) return HttpResponse(template.render(context, request))` templatetags/device_handler.py from django import template register = template.Library() from app.templatetags.device_api import DeviceAPI from requests.exceptions import ConnectTimeout @register.simple_tag def login_device(host, username, password): dev = DeviceAPI() try: dev.login(host, username, password) hname = dev.get_host_name() return hname except ConnectTimeout as error: return error templatetags/device_api.py Looks like this: (Snippet) class DeviceAPI(object): def __init__(self): self._https = True self._version = "Version is set when logged" self._session = requests.session() # use single session self._session.verify = False def formatresponse(self, res): resp = json.loads(res.content.decode('utf-8') return resp def update_cookie(self): for cookie in self._session.cookies: if cookie.name == 'ccsrftoken': csrftoken = cookie.value[1:-1] # token stored as a list self._session.headers.update({'X-CSRFTOKEN': csrftoken}) def login(self, host, username, password): self.host = host if self._https is True: self.url_prefix = 'https://' + self.host else: … -
javascript: Uncaught SyntaxError: Invalid or unexpected token
I have a dictionary data I add a key and value like so: data['business-details'] = "{{ service.business_details }}"; this is from django and the content has a comma , which I believe is causing the code to crash. Getting this error on the console: Uncaught SyntaxError: Invalid or unexpected token which goes to this line data['business-details'] = "I can design both front and back (Django) end for a site, preferably interesting projects."; -
Read user uploaded csv file and store data in Django modele live on heroku
This is my firts question here. so I would like to thank you for your help. I have a Django School management app. and i would like the user to be able to read csv file and store in database with specific header. My code runs locally very well. but I recently push it on heroku so that I can test it. I may note that all static assets are stored on Amazon s3. and it works. but when I try to read a csv file, I get an Internal server error. here is my code to store Pupils. def convert_header(csvHeader): cols = [ x.replace(' ', '_').lower() for x in csvHeader ] return cols def import_data(request): if request.method == 'GET': return render(request, 'school/import.html') if request.method == 'POST' and request.FILES['myfile']: if request.POST.get("object") == '': message = 'You may chose an object' return render(request, 'school/import.html', {'message': message }) if request.POST.get("object") == 'Pupil': myfile = request.FILES['myfile'] fs = FileSystemStorage(location='eSchool/media/documents') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.path(filename) data = csv.reader(open(uploaded_file_url), delimiter=',') header = next(data) header_cols = convert_header(header) i = 0 k = 0 for row in data: pupil = Pupil() for k in range(len(header_cols)): row_item = row[k].split(',') for item in row_item: key = header_cols[k] … -
How to get information of foreign key when selected to another table when selected specific key
I have three tables, one is mandal, village and Property, in the property table i have linked mandal and village with foreign key, now when i select mandal, only that particular village results should have to shown in property form in django admin. I have also linked mandal with village. #models.py from django.db import models from django.utils import timezone class Mandal(models.Model): id = models.AutoField( primary_key=True, db_column="Mandal_id", verbose_name="Mandal Id", ) name = models.CharField( max_length=200, db_column="Mandal_Name", verbose_name="Mandal Name", null=False, blank=False, help_text="Enter Mandal names only", default=None, ) class Meta: db_table = "Mandal" verbose_name_plural = "Mandal" def __str__(self): return self.name class Village(models.Model): id = models.AutoField( primary_key=True, db_column="Village_id", verbose_name="Village Id", ) name = models.CharField( max_length=200, db_column="Village_Name", verbose_name="Village Name", null=False, blank=False, help_text="Enter village names only", default=None, ) mandal_id = models.ForeignKey( Mandal, db_column="Mandal_id", verbose_name="Mandal Name", ) class Meta: db_table = "Village" verbose_name_plural="Village" def __str__(self): return self.name class Properties(models.Model): id = models.BigAutoField( primary_key=True, db_column="Property_id", verbose_name="Property Id" ) created_on = models.DateField( auto_now=False, auto_now_add=False, default=timezone.now(), ) area = models.BigIntegerField( default=0, db_column="Property_Area", verbose_name="Property Area", help_text="Please enter area in square feet", validators=[], ) mandal_location = models.ForeignKey( Mandal, db_column="Mandal_id", verbose_name="Mandal Name", default=None, ) village_location = models.ForeignKey( Village, db_column="Village_id", verbose_name="Village Name", default=None, ) description = models.TextField( default=None, db_column="Property_description", verbose_name="Property Description", ) features = models.CharField( … -
Django query api: complex subquery
I wasted lots of time trying to compose such query. Here my models: class User(Dealer): pass class Post(models.Model): text = models.CharField(max_length=500, default='') date = models.DateTimeField(default=timezone.now) interactions = models.ManyToManyField(User, through='UserPostInteraction', related_name='post_interaction') class UserPostInteraction(models.Model): post = models.ForeignKey(Post, related_name='pppost') user = models.ForeignKey(User, related_name='uuuuser') status = models.SmallIntegerField() DISCARD = -1 VIEWED = 0 LIKED = 1 DISLIKED = 2 And what i need: Subquery is: (UserPostInteractions where status = LIKED) - (UserPostInteractions where status = DISLIKED) of Post(OuterRef('pk')) Query is : Select all posts order by value of subquery. I'm stuck at error Subquery returned multiple rows Elp!!)) -
show custom django form error in template
I am writing a view to send a password reset email to users. I am checking if the email entered by the user is registered by using the clean method in the forms.py, this is working correctly although I can not get the custom error message to display in the django template. views.py def send_forgotten_password_email(request): heading = 'Reset Password' if request.method == 'POST': form = ForgottenPasswordForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] form = ForgottenPasswordForm() return render(request,'authentication/forms/forgotten_password.html',{ 'form':form, 'heading':heading, }) forms.py class ForgottenPasswordForm(forms.Form): email = forms.CharField( label='Email:', widget= forms.EmailInput(attrs={'class':'form-control','placeholder':'Enter email'}) ) def clean_email(self): email = self.cleaned_data['email'] email = get_object_or_none(User,email=email) if not email: raise forms.ValidationError("Email not found.") return email template {% extends "base.html" %} {% load static %} {% block title %} Forgotten Password {% endblock title %} {% block content %} <div class="row"> <div class="col col-sm-12 col-md-5 col-lg-5"> <div class="card"> <div class="card-body"> <h4 class="card-title">{{heading}}</h4> <div class="alert alert-danger" role="alert"> {{form.non_field_errors}} {{form.errors}} {{forms.errors}} {{form.email.errors}} </div> <form method="POST"> {% csrf_token %} <div class="form-group"> <label>{{form.email.label}}</label> {{form.email}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> </div> {% endblock content %} -
Django allauth connection error
i having an issue when i trying to signup a new user, django return this message: ConnectionRefusedError at /account/signup/ [Errno 61] Connection refused i'm using django 1.11.5 with allauth 0.33 Could someone help me to solve it please? Thank you. forms.py: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label='Nome') last_name = forms.CharField(max_length=30, label='Cognome') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() settings: ACCOUNT_SIGNUP_FORM_CLASS = "custom_profile.forms.SignupForm" ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = '/' ACCOUNT_ADAPTER = 'custom_profile.adapters.HandyAdapter' -
Django file download?
I have two views "ans_page" and "downloads", where "ans_page" generates a file (library.csv) into a directory "output", further "ans_page" render an html page called "ans.html" it shows a table with data and a button just beneath the table to download a file from a directory "output" which is a part of an app called FragBuild, button is provided with a hyperlink which is associated with "Downloads" views URL, my expectation is that if some one click on the download button it should start a download but it showing an error instead like given bellow: View def Downloads(request): file_path = os.path.join(os.path.split(os.path.abspath(__file__))[0],'output','library.csv') file_wrapper = FileWrapper(file(file_path,'rb')) file_mimetype = mimetypes.guess_type(file_path) response = HttpResponse(file_wrapper, content_type=file_mimetype ) response['X-Sendfile'] = file_path response['Content-Length'] = os.stat(file_path).st_size response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('library.csv') and URL like this: url(r'^ans_page/Downloads$', views.Downloads, name='Downloads'), a button in html to initiate download like this: <div class=""> <button class="btn btn-primary" style="width:40; margin-bottom: 30px; margin-left: 300px "><a href="{% url 'Downloads' %}"> Download Peptide as CSV file </a> </button> </div> But when i clicked on a button to initiate download it shows an error: ValueError at /ans_page/Downloads The view FragBuild.views.Downloads didn't return an HttpResponse object. It returned None instead. How can I solve this problem i have struggle … -
Django OneToOneField post_save cant call int object
I want to extend my 'User' model with the 'Profile' model. To facilitate this I've created the following model. I wanted to have the linked 'Profile' model be automatically created with each new 'User' model. Based on some comments on stackoverflow / research on the internet (simpleisbetterthancomplex) I came with the following solution: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') #Pushup related stats total_pushups = models.IntegerField(default=0) best_consecutive = models.IntegerField(default=0) week_streak = models.IntegerField(default=0) save = models.IntegerField(default=000) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() However, every time I run this (whether through unit tests or 'create superuser' - I have no vies yet, I'm practicing TDD) I get the following error: TypeError: 'int' object is not callable Does anyone here know what I am doing wrong? -
Django migration with python3.6 ERROR:root:code for hash sha3_224 was not found
Hello I read Django tutorials and I have an error related to specific sha3_224 hash function during the migration process. How to solve this problem? Thank you. (venv) linuxoid@linuxoid-ThinkPad-L540:~/myprojects/myproject$ python manage.py makemigrations ERROR:root:code for hash sha3_224 was not found. Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 121, in __get_openssl_constructor f = getattr(hashlib, 'openssl' + name) AttributeError: module '_hashlib' has no attribute 'openssl_sha3_224' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 243, in globals()[__func_name] = __get_hash(__func_name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 128, in __get_openssl_constructor return __get_builtin_constructor(name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 113, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha3_224 ERROR:root:code for hash sha3_256 was not found. Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 121, in __get_openssl_constructor f = getattr(hashlib, 'openssl' + name) AttributeError: module '_hashlib' has no attribute 'openssl_sha3_256' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 243, in globals()[__func_name] = __get_hash(__func_name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 128, in __get_openssl_constructor return __get_builtin_constructor(name) File "/home/linuxoid/myprojects/venv/lib/python3.6/hashlib.py", line 113, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha3_256 ERROR:root:code for hash sha3_384 was not found. Traceback (most recent … -
why using "fieldsets" causing duplicate tab for the main model in the inlines tabs
I have in my admin change page two inlines and they displayed fine without using "fieldsets", but after using "fieldsets" I have extra tab for the main model in the inlines. here some images for the tabs and for the "fieldset" code. fieldsets = ( ("barber", { "fields": <some fields> }), ("Balance", { "classes": ("collapse",), "fields": <some fields> }), ("Schedule", { "classes": ("collapse",), "fields": <some fields> }), ) before using "fieldset" after using "fieldset" -
How to include a calendar management module easily within a Django project
I am developing a Python Django platform, using Django, html, and a bit a javascript. This platform aims to manage bookings. I am stuck on a calendar module which I could insert within my html pages. The calendar module would read schedule availabilties and redirect to a booking page when clicked on it. Ideally, I would like something similar to this website : https://www.doctolib.fr/medecin-generaliste/paris (class 'dl-search-result-calendar'). I know it might be coded in AngularJS and Ajax, although my knowledge of this 2 technos is very limited. My question is, what would be the easiest solution to insert such a calendar module, with booking redirect module ? Any help is welcome Thank you -
SEARCH BOX NOT DISPLAYING RESULTS DJANGO
Hello Guys am trying to implement a simple search box on my blog project to be able to display searched posted on my site. Please do have a view at my code and tell me whats wrong MODEL.PY class EntryPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) tags = models.ManyToManyField(Tag) body = models.TextField() slug = models.SlugField(max_length=200) publish = models.BooleanField(default=True) created= models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) VIEWS.PY def search(request): post= EntryPost.objects.all() search_text = request.GET.get('q', '').distinct() results = post.filter(body__icontains=search_text) return render(request, 'search.html', {'results': results}) URL.PY url(r'^search/results$', search, name='search'), SEARCH.HTML {% extends "base.html" %} {% block search_posts %} {% if entrypost.exists %} {% for entrypost in entrypost %} <div class="post"> <h2><a href="{% url "entry" slug=entrypost.slug %}">{{ entrypost.title }}</a></h2> <p class="meta"> {{ entrypost.created }} | Tagged under {{ entrypost.tags.all|join:", " }} </div> {% endfor %} {% endif %} {% endblock %} SEARCH BOX CODE <form method="GET" action='{% url 'search' %}'> <input type="text/submit" name="q" placeholder='search posts'> <input type="submit" value="search"> </form> The Page renders successfully to search.html but no results on the searched post can be seen. -
Unable to show content from 3rd model db in django
I am building a website based on django.Find below my models: model.py class Projectname(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Jenkinsjobsname(models.Model): projectname=models.ForeignKey(Projectname) jobsname = models.CharField(max_length=200) def __str__(self): return self.jobsname class Jenkinsjobsinformation(models.Model): jobinformation=models.ForeignKey(Jenkinsjobsname) build = models.IntegerField() date = models.DateField(null=True) view.py def index(request): project_name=Projectname.objects.order_by('-name')[:5] context = {'categories': project_name} return render(request,'buildstatus/index.html', context) def detail(request,projectname_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) context = {'jobs': jobs, 'categories':project_name} return render(request,'buildstatus/detail.html', context) def jobdetail(request,projectname_id,jobinformation_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) job_detail=Jenkinsjobsname.objects.get(pk=jobinformation_id) context = {'jobs': jobs,'categories':project_name,'job_detail':job_detail} return render(request,'buildstatus/job_detail.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<projectname_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<jobinformation_id>[0-9]+)/$', views.jobdetail, name='job_detail'), ] detail.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% endblock %} {% block text %} <ul class = "nav nav-tabs" > {% for jenkinsjobsname in jobs.jenkinsjobsname_set.all %} <li><a href= "#">{{jenkinsjobsname.jobsname}}</a></li> {% endfor %} </ul> {% endblock %} index.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no … -
Call django rest framework CRUD methods from single page angular application
I'm trying to create a single page application that would enable to list, create, update and delete users without refreshing the page. I'm using Django Rest framework and AngularJS which seem to me a good idea for this. I want to use my html template so I created a UserListView class derived from TemplateView and defined the CRUD methods in the view.py by myself like this: class UserListView(TemplateView): template_name = "user_list.html" renderer_classes = [TemplateHTMLRenderer] def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def update(self, request, username=None): user = self.get_object(username) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, username=None): user = self.get_object(username) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) After that I created a template user_list.html like this: {% extends 'general_list.html' %} {% block ng_controller %}userCtrl{% endblock ng_controller %} {% block content %} {% verbatim %} <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Username</th> <th>Password</th> <th>Role</th> <th>Calories per day</th> <th></th> </tr> </thead> <tbody> <tr ng-repeat="user in user_list"> <td>{{ user.username }}</td> <td>{{ user.password }}</td> <td>{{ user.role }}</td> <td>{{ user.calories_per_day }}</td> <td><button ng-click="delete(user)">Delete</button></td> </tr> </tbody> </table> </div> {% endverbatim %} <form ng-controller="userCtrl" … -
Can't make messages with Django's JavascriptCatalogView
I use Djnago with sites framework. The static root has the following structure: css js site1.bundle.js site2.bundle.js site3.bundle.js When I try to make messages (python manage.py makemessages -d djangojs -a) the command above extracts messages only from the site1.bundle.js and ignores other files. How can I make single translation file from all JS files? -
How to create a system using Django so that a naive user can edit the content of the Django website without using HTML code?
I have created a personal website for someone using Django (however it wasn't required since website is very simple, but it was their demand!). Now they want that they can edit the content of pages without editing HTML. They now want me to use Django-CMS, I again disagree as I don't think it is required (?) . What should I do to create a system so they can edit the webpage without messing with templates and HTML? The webpages contains few listings, say of 'Books', 'Recent Visits'... etc. I was thinking to create a model for each of them, and let them edit the database using admin, which will then be used by Django to create a dynamic page for their site. Do you think CMS would be a better choice (but then they don't really need me to do anything, they can do it by themselves!) ? I perhaps didn't put my problem properly, but if anyone can understand it, then please give me your suggestions. I can provide more details if anyone wants. -
Why does Django try the wrong url pattern?
Django tries the wrong url pattern but I can not find my mistake. urls.py url(r'^profile/(?P<userid>(\d+))/$', profile_view, name="profile"), url(r'^details/(?P<advertisementid>(\d+))/$', details_view, name='details'), views.py def details_view(request, advertisementid): advertisement_data = Advertisement.objects.get(id=advertisementid) return render(request, "details.html", {"advertisement_data": advertisement_data}) def profile_view(request, userid): advertisements = Advertisement.objects.filter(user__id=userid) return render(request, "profile.html", { 'advertisements': advertisements } ) details.html (from where I want to resolve to the users profile) <a href="{% url 'profile' userid=advertisement_data.user.id %}" style="text-decoration:none;"> <input type="submit" class="details-btn-profile" value="Profile"></a> <a href="{% url 'chat_view_with_toid' advertisementid=advertisement_data.id %}" style="text-decoration:none"> <input type="submit" class="details-btn-contact" value="Kontakt"></a> When I click on button class="details-btn-profile" Django gives me this error: Reverse for 'details' with no arguments not found. 1 pattern(s) tried: ['details/(?P(\d+))/$'] Why does it resolve to details ? Any ideas ? -
Django - Get Default value from another Model Field
I came across this strange problem in django where I have 3 models Books, Language, Book_language where i map book to its language. from django.db import models class Book(models.Model): title = models.CharField(max_length=200) year = models.IntegerField() class Language(models.Model): name = models.CharField(max_length=50) class Book_language(models.Model): book = models.ForeignKey(Book) language = models.ForeignKey(Language) other_title # default to title So far i am creating a book and with title and later assigning with language so the title is same for all languages, later i understand that the title may not be the same in all languages, so i want other_title to be default to title if not mention, and appear in django admin when i map with language. -
Send an Image and some metadata to Django
Is there is way to send an image with some custom metadata to django server with python script ?. django server and python script is in different servers