Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to auto detect user in django
How To Detect User In Django! i see the most of people use foreign key but i don't want foreign key i want to detect user without foreign key i want to detect which user fill this form for example test or something Here is my views.py def buy_form(request): if request.method == 'POST': usr_buy = user_buy_form(request.POST) if usr_buy.is_valid(): usr_buys = usr_buy.save(commit=False) usr_buys.save() else: return print(usr_buy.errors) else: usr_buy = user_buy_form() context = {'usr_buy':usr_buy} return render(request,'user_buy.html',context) Here is my models.py class user_buy(models.Model): users = models.ForeignKey(user_register_model,on_delete=models.CASCADE) title = models.CharField(max_length=200) payment_method = models.CharField(max_length=500) price = models.IntegerField() Trade_limits = models.IntegerField() Location = models.CharField(max_length=1000) def __str__(self): return self.users.user.username Here is my urls.py urlpatterns = [ path('', views.Buy_List_View.as_view(),name='index'), path('accounts/signup/', views.user_reg,name='register'), path('profile/<username>', views.user_profile, name='user_profile'), path('sell_btc/',views.buy_form,name='buy_form') ] Here is my user_buy.html {% extends 'base.html' %} {% block body_block %} <form class="form-control" method="POST"> {{usr_buy.as_p}} </form> {% endblock %} Here is my forms.py class user_buy_form(forms.ModelForm): class Meta(): model = user_buy fields = '__all__' -
How do I see all sql commands to fully reproduce current state of Django app models (Django 2.2)?
I've read that command python manage.py sqlmigrate <app_name> did that for earlier version of Django (<2.0), but now it requires a migrations's name. Also, there was an option to run python manage.py sql <app_name> in previous versions of Django, but now it doesn't work as well. P.S. I need that list of sql statements to debug test db setup process. -
How do I customise the display text of a related object in a column in Django Tables2?
I'm using Django Tables 2 to display some information from a list of objects, including a column with a related object. I'm trying to change the text displayed in the column that shows the related object. My objects are: Job class Job(StatusModel): ''' Model for jobs ''' STATUS = statuses.JOB_STATUS start_time = models.DateTimeField(_('time'), default=timezone.now) pickup_address = models.TextField() ... destination_address = models.TextField() ... drivers = models.ManyToManyField( 'Drivers.Driver', blank=True, ) ... class Meta: verbose_name = _('job') verbose_name_plural = _('jobs') ordering = ('start_time',) def __str__(self): return self.start_time.strftime('%d/%m/%y %H:%M') + ' from ' + self.pickup_address def get_absolute_url(self): return reverse('job_view', args=[str(self.id)]) ... Driver class Driver(StatusModel): ... current_job = models.ForeignKey( Job, on_delete=models.CASCADE, blank=True, null=True, verbose_name=_('Current Job'), related_name='current_job' ) ... def __str__(self): return self.user.get_full_name() ... My table: class DriverStatusListTable(tables.Table): user = tables.Column(linkify=True, verbose_name=_('Driver')) ... current_job = tables.Column(linkify=True) class Meta: model = Driver ... I want the "current_job" column to show text different to the returned __str__ representation of the Job object - namely: Job.start_time.strftime('%H:%M') + ' to ' + Job.destination_address, but I can't work out how to do this, without changing the __str__ method on the Job object. Any ideas? -
How to get uploaded file location in Django
I define a custom upload_to path for a FileField entry. In models.py I have the following class: class MyModel(models.Model): def user_directory_path(self, filename): folder = 'user_{0}/{1}/{2}'.format(self.publisher.id, datetime.today().strftime("%Y/%m"), filename) return folder file = models.FileField(upload_to=user_directory_path, blank=True, null=True, default=False) in settings.py: MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'project/app/uploads/') MEDIA_URL = '/media/' FILE_UPLOAD_PERMISSIONS = 0o644 The upload works fine. What I want is the permalink to this file. When I use {{ mymodel.file.url }} I get just 127.0.0.1:8000/media/filename/ which rise a 404. I would like to have 127.0.0.1:8000/media/user_id/year/month/filename/ -
What is the best way to use user model in django with project from scratch
I have read docs, but still in confuse (new with django). I need auth system with default creds (user and password, like django default user model has) and some extra fields (like subunit_id, post_id, role, parent_id, ... etc). What kind of model i have to use: Proxy, Profile, inherit from Abstract(Base)User? -
How To Fix List View is not Showing in Django
How To Fix List View is not Showing in Django! I Add The List View in Class Based Views When i See It's Not Showing data in html file I'm tired To Fix Can You Please Help Me! Here is my views.py class Buy_List_View(ListView): model = user_buy template_name = 'index.html' Here is my models.py class user_buy(models.Model): users = models.ForeignKey(user_register_model,on_delete=models.CASCADE) payment_method = models.CharField(max_length=500) price = models.IntegerField() limits = models.IntegerField() Here is my index.html {% for buy in user_buy_list %} <tr> <td><a href="#">{{ buy.users }}</a></td> <td>{{ buy.payment_method }}</td> <td>{{ buy.price }}</td> <td>{{ buy.limits }}</td> </tr> {% endfor %} Here is my urls.py from . import views from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index,name='index'), path('accounts/signup/', views.user_reg,name='register'), path('profile/<username>', views.user_profile, name='user_profile'), path('buy/form/seller',views.Buy_List_View.as_view(),name='buy') ] -
Django Admin: Add User settings.Database Improperly configured
Trying to Add a User by Django Admin App I get the following error: settings.DATABASE is improperly configured My Databases are defined as: DATABASE_ROUTERS = ['*****.routers.RouterDB',] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.dummy' }, 'helpdesk': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'mongoengine.django.auth.MongoEngineBackend', ) And in my Router: So If the App is different from **** I get the 'helpdesk' DB that is the SQLite with Django Users. The Mongo Database stores Users for another app that it's not to use Django App from django.conf import settings class RouterDB: def db_for_read(self, model, **hints): if model._meta.app_label == '****': return 'default' return 'helpdesk' def db_for_write(self, model, **hints): if model._meta.app_label == '****': return 'default' return 'helpdesk' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'helpdesk' or \ obj2._meta.app_label == 'helpdesk': return True if obj1._meta.app_label == 'default' or \ obj2._meta.app_label == 'default': return True return False def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'helpdesk': return db == 'helpdesk' if app_label == '****': return db == 'default' return 'default' -
django replace view add a record instead of replacing the updated one
this is my Django view for the update form views.py def updatebc(request, pk): instance = get_object_or_404(BaseCase, pk=pk) instance.base_case_name bcform = BaseCaseForm(request.POST or None,instance=instance) if bcform.is_valid(): instance = bcform.save(commit=False) instance.save() context = { 'bcform':bcform, } return render(request, 'update.html', context) and here is my model.py class BaseCase(models.Model): base_case_name = models.CharField(primary_key=True, max_length=255) version = models.TextField(blank=True, null=True) default = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'base_case' when I try to update a record I actually add one instead of replacing it ! -
What if my Django server receives more traffic than I can afford?
If the server crashes, will it automatically recover if the traffic drops again? -
Recommendations for AWS CodeStar/Pipeline and Python (Django/Flask)
I am quite new to AWS. I did a course called 'AWS Cloud Practitioner Essentials' and then I have recently been doing a certified developer course which I got from Udemy. For a while, I have been interested in python, Django and Flask. It was a little bit interesting setting up an EC2 instance, but what really caught my attention was i) setting up autoscaling groups/load balancers. ii) Elastic Beanstalk iii) CodePipeline and iv) CodeStar. As part of the course, a CodePipeline was setup using Elastic Beanstalk with node.js which created a pre-production environment, manual sign-off and then production release. Within CodeStar it is pretty easy to setup a Django Project, however I am not very confident about a number of things and was looking for a bit of advice. In particular when a Django Project is setup in CodeStar, instead of creating an Elastic Beanstalk item directly in the CodePipeline, it creates two CloudFormation objects called GenerateChange... and ExecuteChangeSet. I must admit that I am not confident with CloudFormation. When I look at the Elastic Beanstalk that is generated by the Django Project, it creates a system with one EC2 instance. What I really wanted to try out was … -
How to hide auth | group | can add group and auth | group | can delete group Permissions Django
Hide Django permissions from Admin site enter image description here -
Is this possible to restrict backward relationship lookup in the core model?
Is this possible to restrict (filter) objects on the level of the core model so that none of the related models is able to see the unfiltered results? Let the example be provided: class UserManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(deleted__isnull=False) def User(models.Model): objects = UserManager() ... def Report(models.Model): users = models.ForeignKey(User, ....) ... I expected this to be working the following way: Report.users will not show record where deleted is not null. But actually, they are shown. -
Django: How to check object category when using Model Inheritance?
Here is my models.py the idea of app is to have different objects (restaurants, services, etc) with different features (you can check each Model). But when I want to get all objecs Object.objects.all() I don't know which is the category for each of them. models.py: from django.db import models from users.models import ProfileUser from django.utils import timezone # Create your models here. class City(models.Model): name = models.CharField(max_length=20) def __str__(self): return f"{self.name}" class Object(models.Model): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.IntegerField(default=10) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" class Restaurant(Object): seats = models.IntegerField() bulgarian_kitchen = models.BooleanField(default=False) italian_kitchen = models.BooleanField(default=False) french_kitchen = models.BooleanField(default=False) is_garden = models.BooleanField(default=False) is_playground = models.BooleanField(default=False) class SportFitness(Object): is_fitness_trainer = models.BooleanField(default=False) class CarService(Object): is_parts_clients = models.BooleanField(default=False) class BeautySalon(Object): is_hair_salon = models.BooleanField(default=False) is_laser_epilation = models.BooleanField(default=False) class FastFood(Object): is_pizza = models.BooleanField(default=False) is_duner = models.BooleanField(default=False) is_seats = models.BooleanField(default=False) class CarWash(Object): is_external_cleaning = models.BooleanField(default=False) is_internal_cleaning = models.BooleanField(default=False) is_engine_cleaning = models.BooleanField(default=False) class Fun(Object): is_working_weekend = models.BooleanField(default=False) is_kids_suitable = models.BooleanField(default=False) class Other(Object): is_working_weekend = models.BooleanField(default=False) class … -
How do you deploy Channels(ASGI) applications on Windows?
Just as Nginx and Supervisor can be used on Linux for channels application deployment, is there a similar service for managing background programs on window? -
Draw Chart while Exporting Pdf file - Django
I am using Jinja Template and WeasyPrint for PDF generation. While calling a API, I have prepared the data in the back-end and export that data into PDF file. I want include chart(Column Chart/Bar Chart) in the pdf file. I don't know how to include chart while exporting PDF. Because the data preparation and export everything should be happened in Back-end with single API. Thanks in Advance. -
Run Django test in a docker container on Travis CI
I'd like to run a Django test in a docker container on Travis. However, I saw the error python: can't open file 'manage.py': [Errno 2] No such file or directory The command "docker-compose run --rm app sh -c "python manage.py test && flake8"" exited with 2. I felt a bit weird because I didn't see any error when I tried docker-compose up -d with the docker-compose.yml. Could anyone let me know what is wrong with me, please? Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /api WORKDIR /api ADD . /api/ RUN pip3 install --upgrade pip RUN pip3 install pipenv RUN pipenv install --skip-lock --system --dev docker-compose.yml version: '3' services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py runserver 0.0.0.0:8000" .travis.yml language: python python: - "3.7" services: - docker before_script: pip install docker-compose script: - docker-compose run --rm app sh -c "python manage.py test && flake8" -
How can i display either video or image based on file type in django
A part of my website allows users to upload pictures and videos, just like facebook or instagram, a user can upload either video or picture and it will be rendered on the template depending on the file extension type. Whatever the user uploads either picture or video should be rendered on the template. Am using Django. -
Google App Engine Blobstore API on Django
I have an app built in Django and currently deployed on Google App Engine. Everything works fine except for when I want to upload files larger than 32MB. I get an error which says, 413. That’s an error. I have been doing some research and I've come to realize that I have to use Google App Engine's Blobstore API. I have no idea on how to implement that on my Django App. Currently my code looks something like this: Model: class FileUploads(models.Model): title = models.CharField(max_length=200) file_upload = models.FileField(upload_to="uploaded_files/", blank=True, null=True) Form: class UploadFileForm(forms.ModelForm): class Meta: model = FileUploads fields = ["title", "file_upload"] View: def upload_file(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): form.save() form = UploadFileForm() return render(request, "my_app/templates/template.html", {"form": form}) Everything works fine. I would just like to know how to implement Google App Engine's Blobstore API on my current code structure to enable large file uploads. -
Django redirect in an if statement not working
I am experiencing an error in Django that I can't manage to solve. After receiving a post to my endpoint I try comparing if the result code is equal to 0 if its equal to 0 I redirect to the relevant view. This is my views.py code def home(request): if request.method == 'POST': messages.add_message(request, messages.SUCCESS, 'Transaction Intited Successfully. Enter PIN on your phone') phone_no = request.POST['client_phone'][1:] base_url = settings.BASE_URL lipa_time = datetime.now().strftime('%Y%m%d%H%M%S') Business_short_code = settings.BUSINESS_SHORTCODE passkey = settings.PASSKEY data_to_encode = Business_short_code + passkey + lipa_time online_password = base64.b64encode(data_to_encode.encode()) decode_password = online_password.decode('utf-8') lipa = Lipa() access_token = lipa.get_token() print(access_token) api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest" headers = {"Authorization": "Bearer %s" % access_token} request = { "BusinessShortCode": Business_short_code, "Password": decode_password, "Timestamp": lipa_time, "TransactionType": "CustomerPayBillOnline", "Amount": "1", "PartyA": "254"+phone_no, "PartyB": Business_short_code, "PhoneNumber": "254"+phone_no, "CallBackURL": base_url+"/confirmation", "AccountReference": "Jaymoh", "TransactionDesc": "Channel join payment" } response = requests.post(api_url, json=request, headers=headers) pprint.pprint(response.json()) rendered = render_to_string('home.html', {}) response = HttpResponse(rendered) return response return render(request, 'home.html', {}) Post data is sent to the view below: def confirmation(request): print(request.body) if request.method == 'POST': response = json.loads(request.body) pprint.pprint(response) transaction_response = response['Body']['stkCallback'] save_transaction = Transaction( MerchantRequestID = transaction_response['MerchantRequestID'], CheckoutRequestID = transaction_response['CheckoutRequestID'], ResultCode = transaction_response['ResultCode'], ResultDesc = transaction_response['ResultDesc'] ) save_transaction.save() transaction_result = transaction_response['ResultCode'] print("ResultCode = %s" … -
How to use model historical on deserialize on migration file?
I am using deserialize from json file in migrate operation. But it have a problem as "missing columm". I figure out that, using historical model will keep version model suitable for each migration file. On documentation from django official: https://docs.djangoproject.com/en/2.2/topics/migrations/#historical-models But I don't know how to apply historical model on deserialize operation -
Django relation does not exist when running test
I'm using Django 2.2.3 and Postgres. I'm trying to add tests into the project and constantly running into an error django.db.utils.ProgrammingError: relation "auth_group" does not exist at test db creation step, when doing either python ./manage.py test or python ./manage.py test app_name. First of all, my suggestion is that I've messed my db schema a little - some time ago development team was asked to import several tables from another db and I've done it via direct importing using pgsql. Than I created models using python manage.py inspectdb and placed them into a separate app. That command created an initial migration, which looks like that: class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name='SomeModelName', fields=[ ( 'id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), ('some_other_field)', models.CharField(max_length=254, unique=True)), ], options={'db_table': 'some_existing_table_name', 'managed': False,}, ), Everything works fine, since than I've created and applied several migrations without any issues. But now I've got stuck with that tests issue. After a brief investigation I found, that inspectdb also created models for some auth tables, and they are present in models.py of that apps with old tables. So, the following lines are present into initial migration of the discussed app: migrations.CreateModel( name='AuthGroup', … -
Django Logging Not Working for Requests(GET or POST Request Logging) when deployed using Gunicorn. But it works when running locally
When I run the Django Application locally, the logs of all the GET and POST request appears in my configured file but when I deploy my application using Gunicorn, only server side log is observed and the logs for GET and POST request does't show up. settings.py has following details: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} {asctime} {module} {lineno} {message}', 'style': '{', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'file': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'interval': 1, 'backupCount': 30, 'filename': 'logs/monosync.log', 'formatter': 'simple' } }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, 'monosync': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': False } } } I am deploying my application using Gunicorn Server using wsgi.py file. conf.py file for Gunicorn is name = 'monosync' loglevel = 'info' errorlog = '-' accesslog = '-' workers = 10 redirect_stderr='true' stdout_logfile='log2.log' I am getting logs for logger with name monosync but unable to store GET and POST request logs. DJANGO_LOG_LEVEL is set to 'INFO' Do I need to make disable_existing_loggers to True ? I don't need any logs created by Gunicorn. Thanks In Advance. -
Authenticate using Google OAuth2 and Postman
Like a week or two ago I used to authenticate in Postman using Google OAuth2 with no problem. But I believe that Google has changed something, because right now it doesn't take me straight to the result of authentication (which is a redirection to my django backend) with access and refresh tokens in response. But right now it looks like some kind of DDoS prevention redirection and in Postman I got an HTML with the script below, that is not being run (most likely Postman is not running it - thus not forwarding). <script type="text/javascript" nonce="H3VTxxxx1x1Ixxxx/Dr/ng"> xsrfstatemanager.chooseKeyAndRedirect( 'https:\/\/accounts.google.com\/signin\/oauth?client_id\x3d2305xxxx9382-bs4v9fkxxxxnt53cf4skirxxxxkmkj4l.apps.googleusercontent.com\x26as\x3dF-fPfkixxxxyJIIdgxxxxw\x26destination\x3dhttp:\/\/127.0.0.1:8000\x26approval_state\x3d!ChQ4dExxxxUzbndIRxxxxkJZU2UzOBIfWXd1LxxxxDVmT3NkOERFdWhZOThQxxxxdWFSQTVoWQ%E2%88%99AJDr988AAAxxxx0ayvP61bbERtYdABfULE34-qRLGgUd\x26oauthgdpr\x3d1\x26xsrfsig\x3dChkAeAxxxxp2XLUCh0OhQv7fnFihxzJthXPzEg5hcHByb3xxxxzdGF0ZRILZGVzdGluYXRpb2xxxxNvYWN1Eg9vYXV0aHJpcxxxx2NvcGU', 'wHNxxxxQ2EVRv5apbGxxxxLjbgegn_BxxxxoHJxA-2g', 'OCAK',true,true, 'https:\/\/accounts.google.com\/o\/nocookie'); </script> It works fine in browser, as JS is being run and is actually forwarding it. What can I do to make it work in Postman? -
Elastic APM: How to turn off logging for django
flushing due to time since last flush 9.060s > max_flush_time 9.060s I 'm getting tone of those message in django debug. I tried changing to their default setting LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'elasticapm': { 'level': 'WARNING', 'class': 'elasticapm.contrib.django.handlers.LoggingHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'mysite': { 'level': 'WARNING', 'handlers': ['elasticapm'], 'propagate': False, }, # Log errors from the Elastic APM module to the console (recommended) 'elasticapm.errors': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, }, } Still getting lots of logs. How to turn this off? -
AttributeError 'NarrateUpdate' object has no attribute 'object'
I got an attribute error on my NarrateUpdate view. I want to edit/update a user submission from a form Here's my views.py: class NarrateUpdate(SuccessMessageMixin, UpdateView): model = Narrate fields = ['title', 'body'] template_name = 'narrate_update_form.html' success_url = reverse_lazy('narrate-status') success_message = "Narration successfully updated" def get(self, request, *args, **kwargs): footer = FooterLinks.objects.all() context = self.get_context_data(**kwargs) context['footer'] = footer return self.render_to_response(context) The urls.py path('narration/<int:pk>/update/', NarrateUpdate.as_view(), name='edit-narration'), And here's the models.py: class Narrate(models.Model): STATUS = ( ('F', 'FOR REVIEW'), ('P', 'PASSED'), ) title = models.CharField(max_length=255) body = models.CharField(max_length=10000) status = models.CharField( max_length=25, choices=STATUS, default='for_review', blank=True) def __str__(self): return self.title def get_absolute_url(self): return "/narration/%i/" % self.title class Meta: verbose_name = "narration" verbose_name_plural = "narrations" What can I do to make this work?