Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python setup.py egg_info error mysqlclient
I just started learning Python using Django and I just seemed to be stuck at the same place for 3 days, every time I try to run the following command in my terminal using Pycharm (Yep, I am using a Mac) I get the below error: Command: pip install mysqlclient Error: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-c7mudszc/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-c7mudszc/mysqlclient/setup_posix.py", line 44, in get_config (venv) Mervins-MacBook-Pro:untitled mervinkobola$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-w_jamo3b/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-w_jamo3b/mysqlclient/setup_posix.py", line 44, in get_config (venv) Mervins-MacBook-Pro:untitled mervinkobola$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-xefx4qk7/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-xefx4qk7/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/3z/_xzmzzh90z9dj90cb70p3q0c0000gn/T/pip-build-xefx4qk7/mysqlclient/setup_posix.py", … -
GeoDjango - Leaflet show popup of a ForeignKey
I am trying to show the User's name on a popup using Leaflet. Right now, I am only able to return the foreignkey id/pk as a number, but I would want to show the user's actual name on the popup. (the name field in the model is shown correctly in the popup) Here is a simple model class Reserve(gis_models.Model): geom = gis_models.PolygonField() objects = gis_models.GeoManager() user = models.ForeignKey(User) name = models.CharField(max_length = 240) views def reserve_datasets(request): reserve= serialize('geojson', Reserve.objects.all()) return HttpResponse(reserve, content_type='json') html <script type="text/javascript"> function our_layers(map,options){ var all_reserve_datasets = new L.GeoJSON.AJAX("{% url 'reserve_datasets'%}",{ onEachFeature: function(feature,layer){ layer.bindPopup('<h4> Name: '+feature.properties.name+'</h4><p>User: '+feature.properties.user); }, }); all_applied_reserve.addTo(map); } </script> {% leaflet_map "gis" callback="window.our_layers" %} -
Wagtail - Add images on homescreen
Basically, I have want to be able to add new images from the admin panel to my lists section of my homepage. Here, basically: <div class="lists"> <div> <!-- List Nunti --> <div class="title"> <hr /> <h3>Nunti</h3> <hr /> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/203689226?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/70163273?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/70163273?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> <div class="object"> <iframe src="https://player.vimeo.com/video/70163273?title=0&byline=0&portrait=0" width="373" height="210" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </div> </div> My homepage.models looks like this : class GalleryPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), InlinePanel('gallery_images', label="Gallery images"), ] class GalleryImage(Orderable): page = ParentalKey(GalleryPage, on_delete=models.CASCADE, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] -
ForeignKey to autogenerated (or equivalent) m2m Model in Django
I have two Django models A and B with a many-to-many relationship, and I need a third model C to have a ForeignKey that points to the intermediary model. Now, simply writing my own model and using through is by itself not a solution to my problem - I also have admin inlines for A that include a field for this m2m relationship - this breaks if I specify a custom intermediary model. I already tried doing class C(models.Model): ... b_c = models.ForeignKey(A.bs.through, ...) But that gives me (fields.E300) Field defines a relation with model 'A_b', which is either not installed, or is abstract. when I try to run makemigrations. Now, I understand the reasoning behind all this - intermediary models are created dynamically, so migrations don't manage them because that would cause a redundancy. Explicit intermediary models can't in general just be added/removed, because there may be additional data associated with them. This means that presenting them (for example) as a Select2 widget is, in general, not appropriate. In my case, however, I really only need that ForeignKey relation, and am OK if deleting data will lead to errors (I intend to use on_delete=PROTECT). Also, I can see how … -
How do I configure nginx to forward the request to some gateway servr which sends the response to client
I would like to process the request in django and add custom header to the request and let the nginx to forward the request to some gateway server resides on another machine. I attempted few trails, but doesn't seem it is working. Came across the proxy_pass which does pretty much same stuff, but sends the request to a specified proxied server, fetches the response, and sends it back to the client. I don't wish to get back the response to my nginx server and let the gateway server send the response directly to the client. I would like to get the request from nginx server and do pretty authentication, and add custom header to the request and forward to the gateway server which performs the logic and sends the response back to client directly. Here is the code: Django view response = Response() # response['User-Information'] = user.username response['X-Accel-Redirect']='/route/' return response Nginx conf. upstream gateway { server 192.168.1.45:3000; } location /route { proxy_pass http://gateway/postdata; proxy_method POST; } -
Does ViewSets generate view_names in Django Rest Framework?
I want to use HyperlinkedIdentityField in my serializer, that's why I need view name. How can I get the view name if I need model_name-list for example? -
Is there a regex statement to remove all print() statements from my Python/Django project?
I'm preparing to go into production so want to remove all my print() statements before pushing my development code onto my server. Wondering if there is a clean way to do this. -
Change BaseInlineformset validate_min, because is not correct/complete
Having an inlineformset: ProducFormSet = inlineformset_factory(parent_model=Product, model=ProductDoc, form=ProductDocForm, min_num=1, validate_min=True, extra=2, max_num=3, can_delete=True) The validation for validate_min=True is not correct, or not complete.It validates only if there are values in the first form. If the user add info in any of the extra forms, but not in the first form the validate_min is triggered, even if 2 forms are having information. I want/need to overwrite the validation min in the BaseInlineForm, to check all forms. -
How to create many to many relationship between models in Django Rest Framework
I have the following models and serializers: Models: class Site(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) class SiteCategory(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) Serializers: class SiteSerializer(serializers.HyperlinkedModelSerializer): class Meta : model = Site fields = ('id', 'name', 'created', 'categories') class SiteCategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SiteCategory fields = ('id', 'name', 'created', 'sites') I want to setup a many-to-many relationship between the sites and categories so for e.g.: Site1 categories: Category1, Category2. Site2 categories: Category2, Category3. Category1 sites: Site1. Category2 sites: Site1, Site2. Category3 sites: Site2. I'm kinda clueless on how should I set up my models and serializers to achive the output described about. -
How to create a new record from django query set
I have heard of a django orm hack somewhere. It goes like this dp = SomeModel.objects.filter(type="customer").last() dp.id = dp.id + 1 #changing id to a new one dp.save() The last step supposedly creates a new record provided the value of id being used doesn't exist. In case the incremented id exists, then the save method acts like the update method. example :: dp.version += 1 #updating some random field dp.save() # will change the newer version of dp.id I would like to ask veterans in django two questions for our benefit, Is there a sure shot way of creating a new record from an old record with the latest auto_increment_pk instead of pk + 1 method Is the above method any faster or better. One advantage I see is if I have a model with 10 fields and I want to create a new record from an old one with only 1 or 2 changes from the older one, this method saves 8 lines of code. Thank You -
Deleting objects that are not referenced by other objects
I have a need to cleanup my database, hence looking for an efficient way to DELETE all objects that are not referenced by other objects via the ForeignKey. Currently, I am doing the following: from django.db import transaction from django.contrib.admin.utils import NestedObjects from django.db import DEFAULT_DB_ALIAS from django.db.models.deletion import Collector from mygeo.models import Location locations = Location.objects.filter(office__slug='bb-co') with transaction.atomic(): for location in locations.iterator(): collector = NestedObjects(using=DEFAULT_DB_ALIAS) # database name collector.collect([location]) # list of related objects that will be deleted objects_to_delete = collector.nested() if len(objects_to_delete) == 1: location.delete() The above works well but takes a longer time to process, since I have over 100000 records to query. Is there a better way than the above to achieve this? -
How to filter the query_set by multi-params?
How to filter the query_set by multi-params? class UserListAPIView(ListAPIView): """ return the user list """ pagination_class = UserPageNumberPagination class Meta: ordering = ['-id'] def get_serializer_class(self): return UserListSerializer def get_queryset(self): username = self.request.query_params.get("username") real_name = self.request.query_params.get("real_name") phone = self.request.query_params.get("phone") company_name = self.request.query_params.get("company_name") return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False, username=username, real_name=real_name, phone=phone, company_name=company_name ) # if `username, real_name, phone, company_name` all are None, there gets `[]` The serializer: class UserListSerializer(ModelSerializer): """ user list serializer """ username = serializers.CharField(allow_null=True, allow_blank=True) real_name = serializers.CharField(allow_null=True, allow_blank=True) phone = serializers.CharField(allow_null=True, allow_blank=True) company_name = serializers.CharField(allow_null=True, allow_blank=True) You see, my username , real_name, phone, company_name all are allow_null. I want to query all the user that meet the conditions. But gets [], when I do not pass the username, real_name, phone, company_name. I want to if the username is None, it do not filter the username, if real_name is None, it do not filter the real_name. (I means it do not filter out it) I have a idea, but it is fit for less fields, if there is only one username field: def get_queryset(self): username = self.request.query_params.get("username") if username == None or username == '': return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False) else: return User.objects.filter( is_admin=False, is_staff=False, is_superuser=False, username=username) But there … -
Djando DRF nested items
I'm tryng to create a set of objects from a POST request,in this I send the pk list of the objects that should be created: data = { 'a_ref':["17629","17630","17631"] } x= Model_Serializer(data=data) this are my serializers: class A_Serializer(serializers.ModelSerializer): class Meta: model = A fields = ('pk',) class Model_Serializer(serializers.ModelSerializer): a_ref = A_Serializer( many=True) def create(self, validated_data): tracks_data = validated_data.pop('a_ref') model = Model.objects.create(**validated_data) for track_data in tracks_data: A.objects.create(ref=model, **track_data) return model class Meta: model = models.Model but I get this: [14]: x.is_valid() Out[14]: False x.errors Out[16]: ReturnDict([ ('a_ref', [{'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}, {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}, {'non_field_errors': ['Invalid data. Expected a dictionary, but got str.']}])]) -
Not able to set up python environment to run python script for webapplication
Hi Pleaes help me to setup a python environment on my window 7 machine to run python script for web application. I have full script but not able to run it on localhost server as it is running on production server with a domain name. Please Help! -
python Django TinyMCE
I'm trying to add an in-page editor to a project and I came across TinyMCE a HTML editor. I've been following the tutorial on how to integrate it into my app but have been getting very confused. How to set plug-ins and edit font and stuff still remain a mystery. I'm a novice in Django so any ideas will be helpful -
How to update code whilst a website is live?
Sorry if this is a stupid question but how do I update a live website? I've got a Django (social media) website than I'm about to launch on DigitalOcean but how do I update the code without disrupting the user experience? -
django rest_framework permission error
I'm using dry-rest-permission package to write authentication for django webService. When I write permission method as same as the package docs I encounter internal server error and this :'bool' object is not callable And this is my method: @staticmethod @authenticated_users def has_create_permission(request): return True -
what mean "self" in rest django
enter image description here def get(self, request, format=None): usernames = [user.username for user in User.objects.all()] return Response(usernames) -
Django: Order query by AVG() field in related table
I have two models class Item(VoteModel, models.Model): **some_fields** class ItemRating(models.Model): score = models.IntegerField(default=0) item_id = models.ForeignKey(Item) I want to order Item query by Averadge score from ItemRating In SQL, it will something like this SELECT AVG(ir.score) as rating FROM Item it, ItemRating ir WHERE it.id = ir.item_id ORDER BY rating; How to do it in django ? Thank You! -
Creating charts - best practice
I am preparing a tool to parse and display data on charts. I am using python ( django ) as a backend and HTML5/JS as a frontend. I would like to ask you about best practice: looking at desktop applications ,like tableau, those apps are pulling and saving data internally ( in order to avoid executing many requests ). What are your suggestions, if user open my page the app should save result in the browser memory ( local storage (?) ) or should execute new request after every change in menu ? Thanks in advance, -
Django-floppyforms - validation and sending do not work
I have problem with django-floppyforms. On the page, the form appears as it should - it is a dedicated front-end. However, the validation and sending of the form does not work. I do not know why. My form with django-floppyforms: from events import models import floppyforms.__future__ as forms class ParticipantForm(forms.ModelForm): class Meta: model = models.Participant fields = ('event', 'first_name', 'last_name', 'company', 'street', 'post_code', 'city', 'email', 'phone_number',) widgets = {'event': forms.HiddenInput} Here is my form on register template: <form id="anmelde-form" class="form-default" action="" method="post">{% csrf_token %} {% form form using "floppyforms/event_detail.html" %} <input type="submit" value="{% blocktrans %}Anmelden{% endblocktrans %}" class="btn btn-default bg-mid-gray" /> </form> Here is templete included on register template floppyforms/event_detail.html: {% load floppyforms %}{% block formconfig %}{% formconfig row using "floppyforms/rows/p.html" %}{% endblock %} {% form form using %} <div class="form-input"> <label for="prename">First name*</label> {% formfield form.first_name %} </div> <div class="form-input"> <label for="surname">Last name*</label> {% formfield form.last_name %} </div> <div class="form-input"> <label for="company">Company</label> {% formfield form.company %} </div> <div class="form-input"> <label for="street">Street</label> {% formfield form.street %} </div> <div class="form-input-wrapper"> <div class="form-input small-4 columns"> <label for="area-code">Post code</label> {% formfield form.post_code %} </div> <div class="form-input small-8 columns"> <label for="city">City</label> {% formfield form.city %} </div> </div> <div class="form-input"> <label for="mail">E-Mail*</label> {% formfield form.email … -
Trying to extend AbstractUser to create multiple user types in Django
So I have been searching all around the internet for a full example of how to user AbstractUser when u have at least 2 different models. Didn't find anything conclusive.. at least that would work on latest version of Django (2.0.1). I have 2 models, teacher and student, and registration needs to be different. Besides username, email, name and surname, I need for example, for the student, to upload a profile picture, email, phone, student_ID. And for teacher, bio, academic title and website. Did I start good ? What is the right approach ? class Profile(AbstractUser): photo = models.ImageField(upload_to='students_images') email = models.EmailField() phone = models.CharField(max_length=15, ) class Student(Profile): student_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')]) def __str__(self): return self.name class Teacher(Profile): academic_title = models.CharField(max_length=30) bio = models.TextField() website = models.URLField(help_text="E.g.: https://www.example.com", blank=True) -
Library of Django filters
I have created some Django template filters that I constantly need. I wanted to create a simple library to leverage them, but not sure what'd be the best way to import that. Sample views.py code: from django.template.defaulttags import register @register.filter def get_item(dictionary, key): return dictionary.get(key, '') How can I split this function get_item to a say library.py file and still be able to register the templates only when this library is imported? Thank you! Limitiations: only module-level imports; no wildcards or symbols import. -
django - select2 minimum project
My problem looks like this: I want to use select2 in django. I downloaded and installed the package using the guides provided here : https://github.com/applegrew/django-select2 . But the problem is, that i really don't get this example in /tests. Does anyone has some basic, minimum django project with just 1 field of heavyselect2? Let's assume that I have my project set and one app in that project added. I appreciate any help;) -
ModuleNotFoundError: No module named 'importlib.util'
I was trying to install "importlib.util" using pip: pip install importlib But cmd throws the ModuleNotFoundError: No module named 'importlib.util' here is the error image click me