Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
search and report generation django admin panel
May I get to know how to customize django admin panel with search option and report generation enter image description here -
No module named 'backend.settings' debug pycharm
I am using Pycharm and Django. I have a virtual environment (tour of heroes). When I run python3 manage.py runserver from the terminal (with activated virtualenv) the project runs fine. When I try to run the project from the Pycharm Debugger i get the error: ModuleNotFoundError("No module named backend.settings",) In the Edit Configurations for the Pycharm debugger I have the python interpreter set to the correct tour of heroes virtualenv. The environment variables: DJANGO_SETTINGS_MODULE = backend.settings, PYTHONUNBUFFERED = 1 I am running a similar project with a different environment and i double checked and compared all the settings and variables etc and the other project debugs just fine. I dont get why if I am using the same venv than running in terminal or debugger mode should both work... my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#__2nx&dsjk3)8yx&nut&p7c8rc8zg_cm$bwx*sbrucqp2zu2f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Disable "remember every SQL query" (Django)
I know this: It is also important to remember that when running with DEBUG turned on, Django will remember every SQL query it executes. This is useful when you’re debugging, but it’ll rapidly consume memory on a production server. Source: https://docs.djangoproject.com/en/dev/ref/settings/#debug I have a python script which does stress testing. It uses the ORM in a loop doing more and more traffic in every iteration. It would be great if my script could work in any environment. I don't want other developers to force to fiddle with their settings (configure DEBUG to False) before executing this script. Is there a way to disable the particular feature "remember every SQL query"? -
Django: Create a doctor appointment app with doctor and patient login
So I need some guidance with the structuring of the models. Currently I have 3 models: user, patient, and doctor. models.py: class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Patient(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) user.is_patient = True doctor = models.ForeignKey(Patient, on_delete=models.CASCADE) pid = models.AutoField(unique=True, primary_key=True) #patient #identification phone = models.CharField(max_length=10) class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.is_doctor = True upin = models.AutoField(unique=True, primary_key=True) #unique physician # identification number patient = models.ManyToManyField(Patient) expertise = models.CharField(max_length=20) phone = models.CharField(max_length=10) class Appointment(models.Model): TIMESLOT_LIST = ( (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), (6, '15:00 – 16:00'), (7, '16:00 – 17:00'), (8, '17:00 – 18:00'), (8, '18:00 – 19:00'), ) patient = models.ForeignKey(Patient, related_name='patient_appointment', on_delete="DO_NOTHING") doctor = models.ForeignKey(Doctor, related_name='doctor_appointment', on_delete="DO_NOTHING") timeslot = models.IntegerField(choices=TIMESLOT_LIST, null=True) Right now I can register a user through a form that I created. I have a few questions in mind: I'm still learning database structures as I'm learning Django. Is my approach correct? How can I register a user as either patient or doctor with the custom fields that I specified in the corresponding models? Thank you. -
Django Admin Panel, Relations and ReadOnly fields
I have a very simple scheme in model.py class Attachment(models.Model): name = models.CharField(max_length=100, verbose_name='name') file = models.FileField(upload_to=settings.MEDIA_ROOT, null=True, verbose_name='file') def __str__(self): return self.name class Document(models.Model): title = models.CharField(max_length=250, blank=False) attachment = models.ForeignKey('Attachment', null=True, on_delete=models.CASCADE) date = models.DateField(blank=True) approved = models.BooleanField(default=False) def __str__(self): return self.title And my admin.py class DocumentAdmin(admin.ModelAdmin): fieldsets = ( ('GENERAL', { 'fields': ('title', 'attachment', 'date', 'approved') }), ) admin.site.register(Document, DocumentAdmin) There is two issues I'm struggling with: Firstly, I would like to include Attachment's fields in DocumentAdmin interface. I've created a get method in Document model. def get_attachment_file(self): return self.attachment.file Method get_attachment_file is working in list_display, but not in fieldset list_display = ('get_attachment_file',) In addition, I would like to make fields "approved" and "date" read only, after "approved" is set to "True". Thank you all. -
Upload files from django to a specific directory in a server?
I have a django-admin panel and a Windows Virtual Private Server. What i want to do is upload files from django admin panel to a directory like this : C:\site\media and i dont want to upload files to django app folder . This is my settings.py file : STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' if not os.path.exists(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) How should i change it's values ? Thank you . -
Is it possible to enable caching from Django admin pages?
I have a Django-based website at ozake.com, and I am frequently rewriting parts of the programming. Each time I work on it, I have to modify settings.py to disable caching. I am using file-based caching. Here is the relevant part of settings.py: CACHES = { 'default': {'BACKEND': #'BACKEND': 'django.core.cache.backends.dummy.DummyCache', 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/www/mysite.com/cache', When I work on the site I comment out the last two lines and uncomment the dummy cache line. This means SSH'ing into the site, modifying settings.py, working on the site, then re-modifying it. Is there any way I can make this into a check box somewhere in /admin with admin.py? Alternative idea: is it possible to disable caching for a visitor (me) with a specific IP address? If so, could I specify this IP address in /admin? -
Go to definition is not working with docker and vagrant
I have a project running on a docker container and another running on a vagrant machine, when I try in to go to definition in that two projects, I receive this message ex: "No definition found for 'BaseUserManager'. ", for all plugins that I have installed on that machines I get the same message. PS: Go to definition just work on my local workspace. can you guys help me to solve this problem please?, I really like vscode and I don't wanna quit the editor because of this issue. -
How to determine the specific object using another class object as a ManyToMany or Foreign key in a django model?
How can I determine the object using another object as seen below? for author in book.authors.all(): author.some_func(book) It is redundant to input the book as an argument given how we are using it. Is there a way of inherently determining the book? Similar to how we use "self"? In the pseudo code below for the some_func() method, what code would be used for "if called as field from Book object" and "use_this_book = calling Book object" class Book(models.Model): authors = ManyToMany(Author, settings) class Author(models.Model): fields = relationships def some_func(self, book): author = self if called as field from Book object: # replace this line use_this_book = calling Book object # and this line else: use_this_book = book return do_something_func(author, use_this_book) How would the method change for a ForeinKey relationship compared to the ManyToMany realtionship shown above? book.author.some_func(book) class Book(models.Model): author = ForeignKey(Author, settings) -
Django query JSONField where the value is equal to {}
I have a model with a JSONField like this: metadata = JSONField( _('Metadata'), blank=True, default=dict, help_text=_('Multi key-value field to hold any additional information'), ) Is there any way in Django to query for objects where metadata is equal to {}? I use Django 2.1. -
Plotly graphs in django template
I am writing a code that displays a plotly graph in a django template. The source of data should come from a pandas dataframe. I have tried the one shared from this page: Embedding a Plotly chart in a Django template and modified it as follows: def plotly_scatter(df, _x): x = df.iloc[:, 1:2] y = df.iloc[:, 3:4] trace1 = go.Scatter(x=x, y=y, marker={'color': 'red', 'symbol': 104, 'size': 10}, mode="lines", name='1st Trace') data=go.Data([trace1]) layout=go.Layout(title="Meine Daten", xaxis={'title':'x1'}, yaxis={'title':'x2'}) figure=go.Figure(data=data,layout=layout) div = opy.plot(figure, auto_open=False, output_type='div') return div Have this function called from a view with the following line try: df = pd.read_csv(project.base_file) context['graph'] = plotly_scatter(df, 1) except: pass and tried his template: {% if graph %} <div style="width:600;height:500"> {{ graph|safe }} </div> {% endif %} -
django: unable to redirect to another view in django
I'm trying to click on a button to call getCommodityCommentDetail to do something, and then redirect to another page commodityInfoPage. However, the page always stay at the initial one. After tests, I find the commodityInfoPage in views.py didn't be called. I have searched long time for solutions, but all of them failed. So how can I fix it. urls.py: app_name = 'main' urlpatterns = [ # eg:127.0.0.1:8000/main/ path('', views.index, name = 'index'), path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo'), path('getCommodityCommentDetail/',views.getCommodityCommentDetail, name="getCommodityCommentDetail"), path('<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'), path('comments/<str:commodityId>/',views.commodityCommentPage,name = 'commodityCommentPage'), ] view.py: def getCommodityCommentDetail(request): if request.method=="POST": commodityId = request.POST.get("commodityId") # scrapy module is waiting implementation # return HttpResponseRedirect(reverse('main:commodityInfoPage',args=(commodityId))) def commodityCommentPage(request, commodityId): print("enter commodityCommentPage") commentList = JDCommentDetail.objects.all() context = {'commentList':commentList} return render(request,'main/commodityCommentPage.html',context) templates: <form action="{% url 'main:getCommodityCommentDetail'%}" method="POST"> {% csrf_token %} <input class="hidden" value="{{commodity.id}}" name="commodityId"> <button type="submit" class="btn btn-default" >review</button> </form> -
Customise the way django-crispy-forms display validation error
I have use-case where I have to create a form but the requirement is to customise the way django-crispy-forms display the validation errors. I need to display the validation errors just as text in red below the respective field (bootstrap4 style maybe?) instead of the way the above mentioned library displays those errors (sort of a pop-up). I'm using class based views along with forms.ModelForm. My forms.py is: class EmployeeTestForm(forms.ModelForm): class Meta: model = EmployeeTestModel fields = '__all__' def __init__(self, *args, **kwargs): super(EmployeeTestForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_labels = True self.helper.form_id = 'form-test' self.helper.form_class = 'uniForm' self.helper.form_method = 'POST' self.helper.form_action = 'test_form' self.helper.layout = Layout( Field('full_name', css_class='input-xlarge', placeholder='Your full name'), Field('uk_resident'), Field('post_code', placeholder='Valid UK postcode'), PrependedText('last_salary', '£', placeholder="Your last salary"), PrependedAppendedText('resume_file', 'Upload', 'Browse'), FormActions( Submit('save_changes', 'Submit', css_class="btn-primary") ) ) Any help would be appreciated. -
Getting celery task id
I have made something like that @app.task def some_task() logger.info(app.current_task.request.id) some_func() def some_func() logger.info(app.current_task.request.id) So I receive normal id inside some_task, but it equals to None inside some_func. How can I get real task id? -
How to change a field that automatically affect other records in Django
How to change a field in a specific record that automatically affect the same field on other records? Consider the following model: class AccountUser(models.Model): ADMIN='A' USER='U' USER_PROFILES = ( (ADMIN, 'Admin'), (USER, 'User'), ) account = models.ForeignKey(Account, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) profile = models.CharField(max_length=1,choices=USER_PROFILES,default=USER) current_account = models.BooleanField(default=True) def __str__(self): return format('{} ({})'.format(self.account.name, self.user.username)) This is a many-to-many relation between users and accounts, so users can be in many accounts but every user can have one and only one current account. Then, everytime a new record is created or updated with current_account = True, any other records from the same user should be updated with current_account = False. I've saw a similar question in Actions triggered by field change in Django, but it is for changes in the same record, and that solution could result in infinite loop for this situation. -
how to display featured products in a slide
I want to display my featured products in a single slide.But this code is displaying three different slides.How can i make it possible base.html {% for product in featured_products %} <div class="col-lg-9"> <div id="carouselExampleIndicators" class="carousel slide my-4" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img class="d-block img-fluid" src="/media/{{product.image}}" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="/media/{{product.image}}" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block img-fluid" src="/media/{{product.image}}" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% endfor %} views.py def homepage(request): categories = Category.objects.filter(active=True) products = list(Product.objects.filter(active=True).order_by('-created')) featured_products = Product.objects.filter(featured=True) return render(request,'shop/base.html',{'categories':categories,'product':products,'featured_products':featured_products}) -
How to get specific fields from child serializers?
Say, there are two models: class Model1(models.Model): r = models.CharField(max_length=200) class Model2(models.Model): p = models.CharField(max_length=200) m = models.ForeignKey(Model1,on_delete=models.CASCADE) The serializers are : class Model1Serializer(serializers.Serializer): class Meta: model = Model1 fields = '__all__' class Model2Serializer(serializers.Serializer): class Meta: model = Model2 fields = '__all__' The given Model1 serializer returns the output as: { "id": 1, "r": "r_value" } and model 2 serializer output is: { "id":1, "p: "p_value", "m": 1 } The thing is that I also want the r value in the model2 serializer output. How to do that? -
i use django+nginx+uwsgi,but i can not Visit website when i input my IP
I deployed a django project with nginx and uwsgi, but now I can't access the page after I type ip in the browser. What is the reason for this? Please help me, or tell me how to configure nginx -
How can I join two different database and sort in Django
I have 2 databases. MySQL and PostgreSQL. First database(MySQL) fields are: { 'availstock': Decimal('2.00000000'), 'product_name': 'Product 1', } Second database(PostgreSQL) field are: { 'stock_code': 'Product 1', 'price': '$123' } product_name and stock_code are the same unique field. It's like a foreign key but there is no relation on DB and ORM sides, because these databases are separate from each other. I want to join with these fields. And want to sort by availstock -
What an instance attribute will represent in database? for a Django model
Let say i have a model called foo: class Foo(models.Model): col_one = models.SomeFiled(...) col_two = models.SomeFiled(...) Now i know col_one and col_two will represent columns in the database,but if i add the init() method to the model like so: class Foo(models.Model): col_one = models.SomeFiled(...) col_two = models.SomeFiled(...) def __init__(self): attr_one=value_one Now each instance of Foo will represent a record in the Database,but what attr_one will represent for that particular record,i am new to both python and Django if my question is trivial. -
Django: Browse /media/ Folder from Form ImageField
My Form reference a Django Model with an image field which saves an image url pointing to the /media/ folder. By default, the Form generates a snippet for images where a 'Browse...' button is shown, like below picture. When I press the "Browse" button I get a File upload dialogue window pointing to my desktop. My question: How do I get this dialogue to point to my /media/ Folder? What I am trying to achieve is the ability to point to already uploaded pictures that exist in the /media/ folder. This is an alternative approach to create a modal gallery pointing to the folder and code for select a image. I have looked into to amend class ClearableFileInput(FileInput) but lack necessary level of skills to being successful and kind of have a hunch it may exist a better way. I have not found the place in the code that directs where to Browse (in fact I cannot find the words "Browse..." or "No file selected" when using Find in path.) Greatful for some help. models.py class Product(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) reference_date = models.DateTimeField(auto_now_add=True) product_image = models.ImageField(default='product_image/default.jpg', upload_to='product_image') I use Cripsy forms, form helper to generate the Form. forms.py class … -
Amazon SES with Django not in UTC timezone
I'm developing a django project for use in America, specifically the New York timezone and the system is hosted on AWS, with SES sending email. The email backend is using django-anymail which is a simple wrapper for SES and the system uses send_mail from django core. To support this I've opted for the following Django settings; EMAIL_BACKEND = "anymail.backends.amazon_ses.EmailBackend" TIME_ZONE = 'America/New_York' USE_I18N = False USE_L10N = True USE_TZ = True With the above settings django calls tzset() on startup which modifies the system timezone. This then means the timestamp used by botocore to sign the requests for SES is not UTC, because the following error is received from message sending; An error occurred (ExpiredToken) when calling the SendRawEmail operation: The security token included in the request is expired Emails are sent successfully by changing settings to TIME_ZONE = 'UTC'. I can only assume that the requests are being signed in UTC -4 which then hit AWS which is in UTC. How can django run in a specific timezone, but boto operate with UTC timestamps? -
Django override password_reset_subject.txt does not change subject
I created registration/password_reset_subject.txt as suggested here however it does take effect. The email subject remains Subject: Password reset on 127.0.0.1:8000 -
Django forces primary key on field named `id` even if another field is already declared primary key
These are my requirements, and I can not change them: I have a field named name. That is my primary key I have a field named id, but it is not my primary key. The id is also an auto-increment field. I have several problems: Auto-increment fields must be primary keys in django Django sets primary_key in fields called id: I have been able to work around the first problem, by using this: from django.db.models.fields import AutoField from django.db.models.fields import checks class AutoFieldNonPrimary(AutoField): def _check_primary_key(self): if self.primary_key: return [ checks.Error( "AutoFieldNonPrimary must not set primary_key=True.", obj=self, id="fields.E100", ) ] else: return [] Now I can do: class TheNiceUser(models.Model): id = AutoFieldNonPrimary() name = models.CharField(max_length=16, primary_key=True) But still, the id is declared as primary key. Now I have two primary keys in my model, and the migrations complain. According to the django doc, this should not be the case: if a field has primary_key set, django should not add an id field as primary key. But what happens if I declare an id field? It seems that django insists on making that a primary key, even if another field is already declared as primary key. How can I get out of … -
How to change child class of an object
I have a base model which is inherited by two other models. How can I change a Tender object to an OfferRequest object while keeping ProcurementRow relation intact? My purpose is to convert a Tender into an OfferRequest on demand. class Procurement(models.Model): pass class ProcurementRow(models.Model) procurement = models.ForeignKey(Procurement) class Tender(Procurement): pass class OfferRequest(Procurement): pass