Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using lazy loading with DRF
I would like to make a simple lazy loading with Django Rest Framework. I have a solid background with Laravel where you can simply use it like so: Subscription::with('company')->paginate() But with DRF I'm having problems. One Company can have one subscription and my models are defined as such: Company class CompanyManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user class Company(AbstractBaseUser): """ Company refers to what we have referee in the official document as "Empresa Partner" Attributes: name: The name of the main company email: Email to contact the main company code: the code attributed to this company """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(unique=True) username = models.CharField(blank=True, max_length=100) is_staff = models.BooleanField(blank=True, default=False) our_system_date = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CompanyManager() def __str__(self): return self.email Subscription class Subscription(models.Model): """ Subscriptions that references the plans and the companies :company: The owner of this subscription :plan: The plan this subscription is based on :starts: When the subscription starts :ends: When this subscription ends """ company = models.ForeignKey(Company, on_delete=models.CASCADE) … -
How to customize redoc API documentation
I am using redoc in django==2.0 for documenting some django API. I noticed that by default redoc will name the endpoints automatically as you can see on the image below on the left side. Most likely I don't want to use the names generated I want customize the names. From someone who has experience with redoc documentation could you advice please? -
Check Uniqueness, Skip and Enter Data Accordingly in Django API
I want to create a condition where i am taking data from google place api. In my model place_id is unique field. I have created api where it takes multiple data - somewhat like this - [{},{},{}]. When i enter data with 2 same place_id it gives error - "masjid with this place id already exists.". Instead of that unique error of place_id. I want to check if place_id already exists then don't give error, just skip it and enter those data which are having unique place_id. Here i will give you an example where i have send data using json. [ { "name": "Jama masjid", "address": "XYZ", "latitude": 25454.25, "longitude": 1541.4, "place_id": "place_id" <---- This place_id already exist in database }, { "name": "Noor masjid", "address": "kondhwa", "latitude": 25454.25, "longitude": 1541.4, "place_id": "place_id1" } ] So in Response it produce this error - [ { "place_id": [ "masjid with this place id already exists." ] }, {} ] Note - I am sending multiple data - many=True Models.py class Masjid(models.Model): name = models.CharField(max_length=255, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) place_id = models.CharField(max_length=255, null=True, blank=True, unique=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) Views.py class MasjidAddGoogleAPIView(generics.CreateAPIView): queryset = … -
How to compress a JSON payload from Django Rest API
I have a particular Get response which has over 20mb of JSON payload, this takes a lot of time to load. I was wondering if there is a way to compress this payload a bit before sending it to the client. Note: I'm new to the Django framework, kindly provide docs along with your answer so i can understand more. -
VUE axios get API not found
I have an app Vue + Django. I try to send some data from vue to database using axios post method. Unfortunately console shows error: GET http://localhost:8080/api/get_data/ 404 (Not Found) And the same happend in python console: Not Found: /get_data/ I have function get_data defined in my views and i added a path to urls: path('get_data/', views.get_data) In frontend it looks like this: addNewData() { axios.post("/api/get_data/", this.componentData.data).then(response => { console.log("ok"); }); } Did I missed something? -
Can I safely delete Django's empty __init__ files?
I have many __init__.py files in my Django project and apps folder, I think most were generated by Django when I initialised my project and its apps (but some might have been added by my IDE, Pycharm) I have seen in How do I delete DB (sqlite3) in Django 1.9 to start from scratch? that apparently we shouldn't delete the __init__.py file in the migration folders. Can I delete the others, empty __init__.py files ? It s just that they kind of clutter the directory tree, so if they are useless I would rather remove them. -
Seek for suggestion of importing data to Django from external database
I am writing a API by Django to do something like every morning retrieve the yesterday trading data from external MYSQL database, do some mapping and finally return the set of formatted data to front-end. Since I am new to handle the data from external data, I have no idea which is the best way to achieve the goal. I am thinking to connect local and the legacy database in django at the same time and then set a crontab to migrate the new data from the legacy database to local database everyday. However, I think it may have high chance getting error during the migration. Are there any other method directly retrieve the data from legacy database and allow me to the mapping immediately? Reference code for connecting 2 database: Settings.py DATABASES = { 'default': { 'NAME': 'django_database', 'ENGINE': 'django.db.backends.mysql', 'USER': '', 'PASSWORD': '' }, 'legacy': { 'NAME': 'legacy_database', 'ENGINE': 'django.db.backends.mysql', 'USER': '', 'PASSWORD': '' } } Migration.py from django.db import connections from django.core.exceptions import ObjectDoesNotExist from django.db.utils import ConnectionDoesNotExist from my_app import models def setup_cursor(): try: cursor = connections['legacy'].cursor() except ConnectionDoesNotExist: print "Legacy database is not configured" return None ***below have some method save the data into database*** -
Random 502 errors from gunicorn under high load
My Django 1.8 app uses gunicorn on a 21 processor Debian machine, I get lots of random 502 errors under high loads (like more than 80 req/sec) when the server load is roughly over 20. Here is my current gunocorn config: #!/bin/bash NAME="myapp" SOCKFILE=/tmp/gunicorn.sock USER=me GROUP=www-data NUM_WORKERS=49 DJANGO_SETTINGS_MODULE=myapp.settings DJANGO_WSGI_MODULE=myapp.wsgi MAX_REQ=220000 REQ_TIMEOUT=30 LOG_FILE=/var/log/gunicorn/error.log echo "Starting $NAME as `whoami`" cd $DJANGODIR source /path/to/.myappenv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR themselves (do not use --daemon) exec /path/to/.myappenv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=error \ --log-file $LOG_FILE \ --max-requests=$MAX_REQ \ --timeout=$REQ_TIMEOUT /var/log/gunicorn/error.log shows lots of : [2019-03-28 01:30:27 +0000] [11457] [CRITICAL] WORKER TIMEOUT (pid:13481) [2019-03-28 01:30:27 +0000] [11457] [CRITICAL] WORKER TIMEOUT At the same time, the database is quite cool and never reaches max_connections I have tried many different combinations of REQ_TIMEOUT NUM_WORKERS and MAX_REQ but none could resolve the problem. So appreciate your hints on how to solve this issue. -
How to view images when path is saved to database and image is saved to folder in Django?
I'm new in Django.I need a help.I want to display images, here i saved image path to database and images to folder .please help me to display those images -
How can I add class attribute in formset field where we are using inlineformset_factory function
If I add a unit_price field in SupplierForm it does reflect on my template and added class attribute but it added both forms. I want to override unit_price only entries form.how can I do that. class SupplierForm(forms.ModelForm): # unit_price = forms.FloatField(widget=forms.TextInput( # attrs={ # 'class':'product_price', # } # )) # VAT = forms.FloatField(widget=forms.TextInput( # attrs={ # 'class':'product_vat', # } # )) class Meta: model = Supplier exclude = ['uploaded_by', 'approved_by','unit_price'] labels = { "payment_due_date": "Payment Due Date / Paid Date" } help_texts = { 'invoice_date': '<b>Click on arrow for calendar</b>', 'payment_due_date': '<b>Click on arrow for calendar</b>', } widgets = { 'invoice_date': DateInput(format="%d %b %Y"), 'payment_due_date':DateInput(), } # I have added here unit_price field for add class attribute in this field but there is no reflect on template class EnteriesForm(ModelForm): unit_price = forms.FloatField(widget=forms.TextInput( attrs={ 'class':'product_price', } )) class Meta: model = Enteries exclude = () help_texts = { 'unit_price': '<b>Click on arrow for calendar</b>', } EnteriesFormSet = inlineformset_factory(Supplier, Enteries, form=SupplierForm,exclude=['uploaded_by'],extra=1) -
What is the usage of `FilteredRelation()` objects in Django ORM (Django 2.X)?
I've seen Django 2.0 consists of FilteredRelation object in queryset. What is the usage of newly introduced FilteredRelation? What I've looked into? I observed Django 2.0 Documentation but I could not understand idea behind this FilteredRelation object. I looked into following code. But I didn't get it. >>> from django.db.models import FilteredRelation, Q >>> Restaurant.objects.annotate( ... pizzas_vegetarian=FilteredRelation( ... 'pizzas', condition=Q(pizzas__vegetarian=True), ... ), ... ).filter(pizzas_vegetarian__name__icontains='mozzarella') Main Question Show now my question is that what is usage of FilteredRelation and when to use in your QuerySet? -
How to use django-siteflags to bookmark site objects?
The package is here and here but I cannot get it to work. Here is my models.py file class Video(models.Model, ModelWithFlag): name = models.CharField(max_length=255) file = models.FileField(upload_to="static/videos/", null=True, verbose_name="", unique=True) def __str__(self): return self.name And the views.py file def user_bookmarked_video(request, id): video = get_object_or_404(Video, pk=id) # Now a user adds this article to his bookmarks. video.set_flag(request.user) How should the urls.py and .html look like ? -
Django, CSRF token makes an error! Where do I look at?
While I'm looking at log file, I got many error logs related to CSRF I got warning log below Forbidden (CSRF token missing or incorrect.): /my/site/uri and right after that error log below Internal Server Error: /my/site/uri Traceback (most recent call last): File "/data/kukkart_env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 140, in get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "/data/kukkart_env/local/lib/python2.7/site-packages/django/middleware/csrf.py", line 216, in process_view return self._reject(request, REASON_BAD_TOKEN) File "/data/kukkart_env/local/lib/python2.7/site-packages/django/middleware/csrf.py", line 106, in _reject return _get_failure_view()(request, reason=reason) TypeError: server_error() got an unexpected keyword argument 'reason' What makes this error? -
Every 8 minutes a new thread is added in the pool
I run celery 4.1.1, django celery 3.2.2, with Python 3.5.5, ampq 2.3.2, mysqlclient 1.3.12. I have a job defined in mysql as follows: djcelery_periodictask={"id":"5","name":"quote","task":"quote","args":"[]","kwargs":"{}","queue":null,"exchange":null,"routing_key":null,"expires":null,"enabled":"1","last_run_at":"2019-03-27 13:52:00.001668","total_run_count":"147","date_changed":"2019-03-27 13:52:15.029632","description":"","crontab_id":"5","interval_id":null} with : djcelery_crontabschedule = {"id":"5","minute":"*\/2","hour":"9-22","day_of_week":"mon-fri","day_of_month":"*","month_of_year":"*"} I am using rabbitmq. The time is saved in UTC, the server is in EST. The job runs every 2 minutes, but I noticed that every 8 minutes the job adds a new thread in the pool. For example, at the beginning, there is 1 thread running in the pool, the 8 minutes later, 2 threads are running every 2 minutes, then 8 minutes later, 3 threads are running every 2 minutes, and so forth. In the logs it is like, [2019-03-27 21:56:00,029] [WARNING] [QUOTE] [START] [(views.py : 23)] [2019-03-27 21:56:00,029] [WARNING] [QUOTE] [START] [(views.py : 23)] [2019-03-27 21:56:00,029] [WARNING] [QUOTE] [START] [(views.py : 23)] . . . [2019-03-27 21:56:00,029] [WARNING] [QUOTE] [START] [(views.py : 23)] [2019-03-27 21:56:03,905] [WARNING] [QUOTE] [END] [(views.py : 36)] [2019-03-27 21:56:03,905] [WARNING] [QUOTE] [END] [(views.py : 36)] [2019-03-27 21:56:03,905] [WARNING] [QUOTE] [END] [(views.py : 36)] . . . [2019-03-27 21:56:03,905] [WARNING] [QUOTE] [END] [(views.py : 36)] And when the supervisor is restarted the number of threads goes back to one [2019-03-27 21:58:00,032] [WARNING] [QUOTE] … -
How to take array of foreign keys in django model
I have a model product , price and custorder. I want a list of products while creating the order which is used as a foreign key in custorder. I am using postgres as database. class Product(models.Model): product = ArrayField(models.CharField(max_length=200), blank=True) def __str__(self): return str(self.product) class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=50, decimal_places = 5, default=0) def __str__(self): return "%s" % self.price class CustOrder(models.Model): Customer_id = models.AutoField(primary_key=True) CustomerName = models.CharField(max_length=200) email = models.EmailField(max_length=70,blank=True, null= True, unique= True) gender = models.CharField(max_length=6, choices=GENDER_CHOICES) phone = PhoneField(null=False, blank=True, unique=True) landmark = models.PointField() #landmark = models.TextField(max_length=400, help_text="Enter the landmark", default='Enter landmark') houseno = models.IntegerField(default=0) #product_name = models.CharField(max_length=200, choices=PRODUCT_CHOICES,default='Boneless chicken') product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True,related_name='pricetag') quantity = models.IntegerField(default=0) price = models.ForeignKey(Price, on_delete=models.SET_NULL, null=True,related_name='pricetag') #price = models.DecimalField(max_digits=50, decimal_places=5, default=48.9) pay_method = models.CharField(max_length=200,choices=PAYMENT_CHOICES, default='RAZOR PAY') city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True) Price.objects.aggregate(Sum('price')) def __str__(self): return self.CustomerName -
How to use Django login functionality using already created MySQL database table?
I have Database Student, in that database I have one table Student_login whose structure is : Student_id ---Integer Student_Username-----Varchar(PlainText) Student_password-----Varchar(PlainText) Now I have to use already present database for Django Login Functionality but Django creates its own table for login instead of it I want to use Student_login table for login and it encrypts password but I don't want to encrypt the password cause some other people are also using same table. How to achieve this? Thanks in Advance. -
Best approach to keep checking account type in Django
This is nanakondor I have a project about school system which has 3 types of user staff, student, and lecturer Every staff webpage loaded, it will have a url like .com/staff/ something something for example .com/staff/account-management Every student webpage will also be like .com/student/, e.g. .com/student/my_units Every lecturer webpage will also be like .com/lecturer, for example .com/lecturer/my_units If a student access a .com/staff webpage or its similar urls such as .com/staff/account-management or .com/staff/resources-management, I want to display a webpage saying "You do not have the permission to access this page" In conclusion, the student cannot access administrative or lecturer urls, the administrative also cannot access student or lecturer urls, the lecturer also cannot access student or administrative urls. also, everytime i load a student webpage, i need the first name and full name, as well as the classes enrolled. for lecturer webpage, i need the first name and full name, and the classes the lecturer teaches for staff webpage, i only need the first name and full name. this is for the base.html purpose that is extended by other templates this base.html contains navigation bar that needs these info My approach is now this in the student views.py, there is … -
The web appeared "Internal Server 500" while I deployed Flask app. And another web also failed, however, it worked previously
Condition I ran a Flask app and deployed in IIS. And the web appeared the message called "Internal Server Error 500" and "error code 0x80070005". But I definitely followed the steps from Microsoft document. Then, another web with django also failed. However, the web with django can ran previously. Question I do not understand why they happened. Can anybody tell the reasons about why the new web failed so that another web was affected how to fix the web with django ? how to deploy the app with flask successfully ? The flask setting which I have done I copy the wfastcgi.py and paste it into the project directory Add Website Edit module mapping Edit FastCGI Application Set PYTHON_PATH and MSGI_HANDLER It is my web config The django setting which I have done Because of reputation, I cannot paste more links. The steps are the same Here is my web config about django project Thanks!! -
How can I return a new non-repeating item from a list in Django while keeping track of previous items?
I'm working on an app where a user can select a category, which will return a random selection from that category. The main functionality I'm trying to implement is once an item is selected, it can no longer be randomly selected in session. For example, we have 3 categories of photos: landscape, urban, and portraits, each with 5 photos. A user selects urban, is then redirected to a details page with a random photo from urban category. He can either refresh the page or click a button to get a new photo from that category. When that category is out of new photos, he is redirected home. I am able to get my random item from the selected category through converting a queryset to a list, but the data isn't persisting. On every refresh the list I have resets, thus a previously selected photo can come up again, ignoring the the fact that I removed the item from the list after it was selected. Here's the views.py with the function responsible for this: def randomPhoto(request, pk, **kwargs): # queryset to get all photos from selected category gallery = list(Photos.objects.filter(id=pk) .values_list("partof__category", flat=True)) # select random photo from list last = len(gallery) … -
render to response is not work for jquery ajax request
I sent an ajax get request to jquery But render_to_response does not work when added code for print(self.request) but empty is printed please let me know how to fix thank you class PostDetailView(DetailView): print("상세 보기 뷰 함수 실행") model = Posth def render_to_response(self, context): print("request is : ", self.request) if self.request.is_ajax(): print("request is ajax ") return JsonResponse({ 'title': self.object.title, 'summary': truncatewords(self.object.content, 100), }) return super().render_to_response(context) post_detail = PostDetailView.as_view() js $(document).ready(function () { $(document).on('click', '#post_list a', function (e) { e.preventDefault(); const detail_url = $(this).attr("href"); <!-- alert(detail_url) --> console.log("detail_url : ", detail_url ) $.get(detail_url) .done((json_obj) => { var $modal = $("#post-modal"); console.log("json_obj : ", json_obj) $modal.find('.modal-title').html(json_obj.title); $modal.find('.modal-body').html(json_obj.summary); $modal.find('.btn-detail').attr('href', detail_url) $modal.modal(); }) .fail((xhr, textStatus, error) => { alert('failed : ', error); }); }) }); github: https://github.com/hyunsokstar/ask_class -
Django model dynamic choices migration
I have a model charfield which has dynamic choices class MachineChoices(object): def get_machine_choices(self): # call external service to get a full list of machines ... def __iter__(self): yield from self.get_machine_choices() class ExceptionMapping(models.Model): machine_id = models.IntegerField(null=True, blank=True, choices=MachineChoices()) My problem is that when I run makemigrations it will generate a migration for the field with all the choices. How do I get around this without such gigantic migration. Deleting this migration manually each time running makemigrations is a pain in the butt. Please Note: My question is here is not asking why this is happening as I have already asked before. -
What are the pros and cons of using Django and React Native for web applications?
I want to make "hybrid" applications that work on the web and then, without many changes, I can release for mobile devices. -
Python/Django model dictionary allows one type of update, but not another
I am working on some Django/Python code. Basically, the backend of my code gets sent a dict of parameters named 'p'. These values all come off Django models. When I tried to override them as such: p['age']=25 I got a 'model error'. Yet, if I write: p.age=25 it works fine. My suspicion is that, internally, choice #1 tries to set a new value to an instance of a class created by Django that objects to being overridden, but internally Python3 simply replaces the Django instance with a "new" attribute of the same name ('age'), without regard for the prior origin, type, or class of what Django created. All of this is in a RESTful framework, and actually in test code. So even if I am right I don't believe it changes anything for me in reality. But can anyone explain why one type of assignment to an existing dict works, and the other fails? -
Media.url returns a empty string
Whenever I try to image.url function I get an empty string. I also tried the image.path but didn't help. I am using Django 2.15. and I have a Image field in models. My {{MEDIA_URL}} returns /media. I have done Django the config for setting media root, and media url in settings. py also URL pattern. When I go to the link foo.com/media/imagefile.png it loads perfectly fine. But when I pass through views functions a dictionary render (request ,templatepath,object.__dict__) and in template type {{img.url}} I get a empty string. where as I want to see the real image, or its url mentioned. Any help is appreciated. This is what I have in urls.py + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Getting callback function from websocket_urlpatterns given the path or name. Django Channels
Example: websocket_urlpatterns = [ url(r'^ws/sample/$', consumers.PersistentConsumer, name='ws-sample'),] I need to be able to get consumers.PersistentConsumer given "ws-sample" or "/ws/sample/" I have tried django.urls.base.resolve("/ws/some_path") from https://docs.djangoproject.com/en/2.1/ref/urlresolvers/#resolve but it is returning a different callback. I suspect it is because I'm using ProtocolTypeRouter for my websockets, and resolve meant for vanilla django, not django channels.