Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queryable django admin panel
Is there any admin panel in django that is queryable. I mean a django admin panel in which I can write my SQL queries. -
how to Django dumpdata nested models in yaml
So I have this awesome Django app which gives me satisfaction and such. But now the problem, I want to use dumpdata (or something that does the same) to export a model with a nested other model in yaml format. Lets say I have two models, Project and Questions. Each Project can have it's owns set of Questions. The code looks something like this: Project Model: class Projects(SortableMixin): """ Some docstring """ slug = models.SlugField( _('slug'), help_text=_('Short name to address this projects from templates.')) # Basic fields object_id = models.PositiveIntegerField(blank=True, null=True) name = models.TextField(_('name'), help_text=_('The question.')) # Some other fields... question = models.ForeignKey(Question, null=True, blank=True) Questions Model: class Question(SortableMixin): """ Some docstring """ slug = models.SlugField( _('slug'), help_text=_('Short name to address this question from templates.')) # Basic fields object_id = models.PositiveIntegerField(blank=True, null=True) name = models.TextField(_('name'), help_text=_('The question.')) input = models.TextField() The Project model has his own app and so has the Questions. The structure looks like this: - Django - Apps - Project - Questions Whenever I want to export my database I'll do the following: ./manage.py dumpdata --indent 4 --format yaml > dbdump.yaml Although this works, and I can later import it with LoadData, its not what I want, … -
Django Multiple Record Insert CreateView ( not enough values to unpack (expected 2, got 1))
i am getting the following message while saving the record. not enough values to unpack (expected 2, got 1) I am getting a Acquisition ID and attaching qoutations(single or multiple ) and once saving the record the system pops out the error. there is no error if i select the ACQID from createview itself but when i am getting foriegn key from listview then error is coming. i am getting a foriegn key from listview and inserting qoutations for it in the create view if template is required please let me know even if i save a single record the system is giving error as mentioned above. views.py class QoutationAttach(SuccessMessageMixin, CreateView): template_name = "ePROC/Acquisition/qoutation_add.html" model = QoutationSelection form_class=QoutationAdd success_message = "Record was created successfully" success_url = reverse_lazy('ePROC:qoutattach-list') def form_valid(self, form): form.instance.AcqID=CreateACQModel.objects.get(self.kwargs['pk']) return super(QoutationAttach, self).form_valid(form) class QoutationAttachListView(ListView): template_name = "ePROC/Acquisition/qoutationattach_list.html" model = QoutationSelection queryset = QoutationSelection.objects.all() context_object_name = 'query_results' paginate_by = 10 def get_context_data(self, **kwargs): context = super(QoutationAttachListView, self).get_context_data(**kwargs) context['range'] = range(context["paginator"].num_pages) return context forms.py class QoutationAdd(forms.ModelForm): class Meta: model = QoutationSelection labels = { "Status":"Status", "AcqID":"Acquisition ID", "QoutID":"Qoutation ID", } fields=['QoutID','Status'] QoutID=forms.ModelMultipleChoiceField(queryset=QoutationModel.objects.all()) models.py class CreateACQModel(models.Model): RequestItem=models.ForeignKey(CreateReqModel,on_delete=None,related_name='CreateReqID') ACQProcDate=models.DateTimeField(auto_now_add=True) ACQStatus=models.CharField(default='Procure',max_length=40) def __str__(self): return '%s' %(self.RequestItem) def get_absolute_url(self): return reverse('request-list', kwargs={'pk':self.id}) class QoutationModel(models.Model): … -
Wrong URL for Django filefields download link
I'm currently doing a web app that would store files. I have my class lobby like this : class Lobby(models.Model): (...) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular lobby across whole database") pdf = models.FileField(upload_to='./documents/',blank=True, null=True) (...) def file_link(self): if self.pdf: return "<a href='%s' download>Download</a>" % (self.pdf.url) else: return "No attachment" file_link.allow_tags = True file_link.short_description = 'file_link' (...) When I'm instanciating a lobby I can easily upload my pdf and it goes to the right place (at the root of my app in file named 'documents'). But here's the problem, when I'm trying to download the file thanks to a link by calling: <p><strong>File:</strong> {{ lobby.file_link|safe}}</p> I'm not getting document, but a file not found error Firefox doesn't find the file http://127.0.0.1:8000/catalog/lobby/73d5aede-96af-445e-bec9-8c4522d37ce7/documents/the document.pdf It's like the file_link doesn't send the place the file is stored, but the name the url to go to the page a a specific lobby, then the URL. What did I do wrong?? Thanks. -
Is there a project for Django management utils?
I have just been forced to write some decorators that can be used to require login and do permission checking on Django management commands. I am thinking this is so general purpose that it should be available to the public. Is there a PyPI package where this would make sense to include, or should I start my own project? I have tried searching for "management", but I wondering whether there is something that is named differently, that I don't know off. -
Django models, how to convert existing UUID field to Foreign Key?
I have and existing database where I have models.py as follows: class basicData(models.Model): companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) companyName = models.CharField(max_length=1000,null=True) emailIdCompany = models.EmailField(max_length=1000,blank=False,null=True) numberOfEmployees = models.CharField(max_length=1000,null=True) contactNumberCompany = models.CharField(max_length=1000,null=True) class extraData(models.Model): companyId = models.UUIDField(default=uuid.uuid4, editable=False) interaction = JSONField(db_index=True,null=True) I want to update the models.py as follows: class basicData(models.Model): companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) companyName = models.CharField(max_length=1000,null=True) emailIdCompany = models.EmailField(max_length=1000,blank=False,null=True) numberOfEmployees = models.CharField(max_length=1000,null=True) contactNumberCompany = models.CharField(max_length=1000,null=True) class extraData(models.Model): companyId = models.ForeignKey(globalcompaniesbasicdatabase) interaction = JSONField(db_index=True,null=True) How should I do this without loss of data. -
Serializer Extend User field by same level with Main User in Django Rest Framework
I write a Extend User serializers in Django like this: File Models.py Extend User App: class Profile(models.Model): user = models.OneToOneField(User, unique=True) nickname = models.CharField(max_length=50, null=True, blank=True) gender = models.CharField(max_length=100, choices=GENDER_CHOICES, blank=True, null=True, default='MALE') File serializers.py Extend User App: class ProfilePatchSerializer(ModelSerializer): languages = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='EN') gender = serializers.ChoiceField(choices=GENDER_CHOICES, default='1') class Meta: model = Profile fields = [ 'gender', 'language', ] This serializer in order to extend for Main User Serializers: class UserCreateUpdateSerializer(ModelSerializer): profile = ProfilePatchSerializer() class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'profile', ] As a result, my API will render into this: { "id": 1, "username": "feedgit", "first_name": "Feed Git", "profile": { "gender": Male, "languages": English } } But now I want to API in same level with main User like this: { "id": 1, "username": "feedgit", "first_name": "Feed Git", "gender": Male, "languages": English } Please help me to do this. Thanks in advance! -
Define a self kwarg argument within a FORM request
Here is what I am trying to solve. In my app I invite users to join a team. So I created a form that ask only for a mail, generate a random password, create a user and then send a mail to the user. The user go to the mail and finish his registration by providing first name last name and update his password and is finally part of the team. I gave it a try, but my code was bad : def ApplicantRegister2(request, pk1=None): InviteFormSet = formset_factory(ApplicantForm2) if request.method == 'POST': formset = InviteFormSet(request.POST) if(formset.is_valid()): for i in formset: mail = i.cleaned_data['Email'] user = MyUser(email = mail) password = MyUser.objects.make_random_password() user.set_password(password) user.is_active = False user.is_candidate = True user.save() u1 = user.id #get user id a1 = MyUser.objects.get(email = request.user.email) #get HRuser email a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the HRuser a3 = a2.latest('id') # extract the last project a4 = a3.team_id # extract the team linked to the project a4.applicant.add(u1) # add the member to the team current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'You have been invited to SoftScores.com please sign in to get access … -
Django content type for both static and dynamic content
we're using Django 1.11 (soon moving to 2.0, so it's OK to answer for that as well). We are solving the following problem: We have a Ticket model with several fields, some of them are ForeignKey and some of them are ChoiceField. We have a Condition model with which we want to target a specific value of some of the Ticket fields. If there were just ForeignKey fields in Ticket, we would use GenericRelation (ContentTypes). However there are also "static" values of ChoiceField. One of our colleagues proposed a solution that for every Condition we create a hidden instance of Ticket that is never used anywhere else and is just there to hold the information about the ChoiceField value - and this Ticket is then linked to Condition through GenericRelation. But this sounds like a really bad idea. I was thinking that many developers had to solve this. Is there any good and easy way how to do this? Thank you. -
How to load the webpack bundles created in 'ng build --prod' in django templates?
I am using Angular 4 for client side/frontend and using django 1.11 for backend. I edited .angular-cli.json to redirect the bundles output directory to django app assets ./.angular-cli.json { ... "apps":[ .., "outDir": "django_app/assets/webpack_bundles/", .... ], ... } when building ng build --dev (which for development environment), will create the webpack bundles under assets ./django_app/assets/webpack_bundles django_app/ - assets/ -- webpack_bundles/ --- inline.bundle.js --- main.bundle.js --- polyfills.bundle.js --- vendor.bundle.js then running python3 manage.py collectstatic to migrate in static files and to import it in django templates ./django_app/templates/sample.html {%load static %} <script src="{% static 'webpack_bundles/inline.bundle.js' %}"></script> <script src="{% static 'webpack_bundles/polyfills.bundle.js' %}"></script> <script src="{% static 'webpack_bundles/vendor.bundle.js' %}"></script> <script src="{% static 'webpack_bundles/main.bundle.js' %}"></script> The question is, how can I load webpack bundles on a django templates if building for production ng build --prod? Which will create bundles in minified version and with hash for caching purposes. ./django_app/assets/webpack_bundles django_app/ - assets/ -- webpack_bundles/ --- inline.[hash].bundle.js --- main.[hash].bundle.js --- polyfills.[hash].bundle.js --- vendor.[hash].bundle.js Tried the solution of having ng build --prod --output-hashing none, but this is not a best practice because of caching. Tried using django_webpack_loader, but it is not applicable for angular 4 webpack.config.js -
what is the best way for Database Archiving using django
I have a database with 30 tables which has primary keys and foreign keys. I wish to archive the 1 year data from tables. Could any one please suggest me the best way to Archive the related data of all the tables. Thanks in advance Sridhar. -
how do i get the get_full_url in django2.0?
I am studying django 1.8, but i have to jump to django2.0 def test_home_title(self): self.browser.get(self.get_full_url("home")) self.get_full_url("home") no longer works. i've read the django2 release notes it says - The django.core.urlresolvers module is removed in favor of its new location, django.url im readying the documentation but i cant find any info how. could someone pls point me how to get the full urls in django2.0? p.s. if you could link me how to migrate django1.x to django2.0 that would really help. -
Cuckoo Web TemplateSyntaxError when checking behavioral analysis
I'm having problems with cuckoo web when attempting to check the behavioral analysis results. Whenever I try to click on the link the following error is displayed: Any ideas on the cause? -
django prefetch within a prefetch - must be a Model, Manager, or QuerySet, not 'QuerySet'
Im trying to do a prefetch within a prefetch in django but am getting the below error: First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'QuerySet'. this is the query: site = get_object_or_404(SiteData.objects.prefetch_related( Prefetch( 'sitesubnets_set', queryset=SiteSubnets.objects.filter(site_ip=True), ), Prefetch( 'circuits_set', queryset=Circuits.objects.exclude(decommissioned=True).prefetch_related('servicecontacts_set'), ) ), pk=site_id ) if I remove the below, the query works successfully, so I know its related to chaining the prefetches im just not sure why or how to rectify this? .prefetch_related('servicecontacts_set') -
Getting a new ValueError when using manage.py to run a server from cmd
I'm fairly new to Python and I am using a video tutorial on Lynda to help me build the frameworks for a Social WebApp. I'm trying to run the server from the cmd using manage.py, however, I keep running into this error message. CMD PROMPT ERROR Traceback (most recent call last): File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\urls\resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\utils\functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Kelechi\AppData\Roaming\Python\Python35\site-packages\django\urls\resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Kelechi\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line … -
XML Parsing error: no root element found (empty content) Django
I am using ajax to connect to a view in my web application. $.ajax({ url: url, type: 'PATCH', success: function() { var d = new Date(); img = e.target.parentElement.parentElement.getElementsByTagName('img')[0]; if (img.src.includes("?")){ img.src = img.src.split("?")[0] + '?' + d.getTime(); } else { img.src = img.src + '?' + d.getTime(); } }, }); When I click on the button that triggers this, everything works, but I get an XML Parsing error. According to the other questions on stack exchange, this might be beacuse of an empty content. When I use the firefox developer tools, the content of the reverse of the concerned view is indeed empty, because of which, I think, firefox interprets it as an xml. My problem is, that I do not know how to fill the content. In my view, I changed return Response(status=200) to return Response(status=200, content_type='image/jpeg'), because the view does something to an image. But still the content seems to stay empty and I still get the error. I don't know how else to alter the content type than by specifying it in the response. I only get this error in firefox, not in chrome. -
Django: How can you index images from an object_list in a django template
So basically I wanted to know how you can index images in a django template using a for loop. The idea is to create a slide show using the first three images that you user has adds to the model model.py class Product(models.Model): Name=models.CharField(max_length=120,null=True,blank=True) Category=models.CharField(max_length=80,null=True,blank=True) Image=models.ImageField(null=True,upload_to='Image') Description=models.TextField(null=True,blank=True) Price=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) Delivery_date=models.DateTimeField(null=True,blank=True) Delivered=models.BooleanField(default=False) This is the template but the obj.image.url tag is incomplete as i want only the first three items and not in a loop but listed out {% for obj in object_list%} {%if obj.Image%} <ul class="pgwSlider"> <li><img src="{{obj.Image.url}} "></li> <li><img src="" a></li> <li> <img src='"> <span>Shanghai, China</span> </li> <li> </ul> -
Django: Serializer automatically parse json field and add to common fields
I call serializer: serializer = MySerializer(qs, many=True) when qs - QuerySets for myModel from rest_framework.serializers import Serializer class MySerializer(Serializer): param1 = CharField() param2 = IntegerField(required=False) custom_fields = JSONField() class Meta: pass Next, I just use the custom_fields and get the values manually. Is it possible at this stage to get the fields inside this custom_fields and return them through the serializer? custom_fields contains: { 'custom_value1': 3, 'custom_value2': 5 } -
Celery under supervisor refuse to acknowledge PYTHONPATH. Errors with AttributeError no attribute celery.
I've started to use Celery 4.x after years of using v3.x (Django project). When running locally everything is fine. However on the server when running under supervisor, celerybeat starts ok, but the worker process receives: AttributeError: module 'project' has no attribute 'app' followed by: AttributeError: module 'project' has no attribute 'celery' I believe this is a PYTHONPATH issue and have tried setting the PYTHONPATH in the shell, in the supervisor process config, in supervisord's config, and even in the code itself. Nothing seems to resolve it. I could replicate the issue on the server by running /path/to/venv/bin/celery worker -A project outside of the project directory without PYTHONPATH being set and having it work when it is, but this doesn't seem to work with supervisor. This already shaved hours off my time. - project-dir - project - __init__.py - celery.py - celeryconfig.py - settings.py - otherapp - ... -- # celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -- # __init__.py from __future__ import absolute_import from .celery import app as celery_app __all__ = ['celery_app'] -- `celeryconfig.py` contains the celery and queue configs etc. -- [program:myprogram] process_name=fw%(process_num)s … -
Django in real service, Do I have to set these if else statements to prevent abuse?
EXAMPLE1: def example(request): if request.method=="POST": if request.is_ajax(): #do something EXAMPLE2: def example(request): if request.method=="POST": if request.is_ajax(): #do something else: #do something else: #do something If django project has that above EXAMPLE1 code, even it doesn't have any else: statement like EXAMPLE2, is it okay to run real service? I wonder absense of else: statement will be chance of being abused or some bad things. In real service, Do I have to consider statement almost case of request? -
Data passing from HTML text input to python script
I am creating a web scrapping application, using Django, which scraps the imdb website and lists the movie names based on what users types in the text field[suppose if user types 'b', it lists all the movie names starting with letter 'b'] I have a html text input and a button. <body> <h1>The IMDB Scrapper</h1> <form method="POST" action=""> <input type="text" name="name" placeholder="Iron Man.."> <input type="submit" value="Search"> </form> </body> I also have a python script which scraps the data from the website, using the hardcoded keyword. I want to send the text input data to this python script when the button is pressed and process this data and send send the result hack to the same HTML page for display. -
Django deployment Google App Engine (Flexible)
Google provide a guide how to do this. They have a section on how to run the application locally, together with the Cloud SQL Proxy. Super neat really. So you apply your migrations onto the database hosted on your GCP. Then there is another section how to deploy your application to the cloud. They don't say production, they just say Google App Engine Flexible Which leads me to the question. How do I handle a production environment. I cant seem to find any articles on the topic. Because they can't meen that your suppose to run migrations locally with 'Google SQL Proxy' and then run gcloud app deploy onto a production environment? -
Obtain a client's location coordinates through the browser's geolocation API, or resolve through IP address from the server?
I'm wondering which method to go with for fairly accurate locationing, + scalability and speed. It seems Django's Geoip has a limited number of addresses. And IPs are some times redirected to the ISP generated address. The advantage of using GeoIP would be that I don't have to fiddle around client-side. Would using IP, and relying on Maxmind be a practical hinderance? On the other hand, using the browser's Geolocation API, I believe I can obtain a much more accurate location, but only if it's first "Allow[ed]" by the client. It would then involve sending the coordinates to the backend for further processing using something like Geodjango to resolve the coordinates. What am I missing? Can someone shed some light on the differences? Does it not matter much? -
Mysql: OperationalError at / (1054, "Unknown column '' in 'field list'")
I have made all of my migrations with these commands successfully. python manage.py makemigrations senty python manage.py migrate I end up with this error: django.db.utils.OperationalError: (1054, "Unknown column 'senty_score.points' in 'field list'") To me, it looks like "points" is right there in the class, and it migrated successfully. The most updated pycache has the correct version of the class as well, which was an error before. I wasn't getting an error on this until I changed points from a different function call. Pretty inexperienced to mysql so this is a tough one. Do I have to manually add the column somehow? models.py from django.db import models from datetime import datetime from decimal import Decimal class score(models.Model): ticker = models.CharField(max_length=10) points = models.DecimalField(max_digits=4, decimal_places=1) created_at = models.DateTimeField(default=datetime.now, blank=True) -
How do I extract informations from the user using his/her facebook access token ?
I am doing a Django web app where the user can login using facebook. When the user login, I get a token. I want to use the token to extract and print out the informations the user grants my app without having to paste it in the facebook graph api explorer. How can I do this and integrate it in my django project ? Thanks