Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django return date() object to hour format
I try to get time difference between now and a data's last call and monitoring that in the website. my models.py codes are; class MyModel(models.Model): th_id = models.CharField(max_length=55) src_id = models.IntegerField() call_time = models.DateTimeField() @property def time_diff(self): if self.call_time: return (datetime.now().date() - self.call_time.date()) > timedelta(hours=2) else: return 0 def now_diff(self): return datetime.now().date() - self.call_time.date() But I need to now_diff function return hours difference too, I search on the internet but can't find any solution, date() object doesn't return hours or minutes. Is there a way? -
Logging in Django - Cant get an output in the console using INFO
After reading a tutorial on Logging in Django. I added the following to my settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'null': { 'class': 'logging.NullHandler', }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django': { 'handlers': ['console'], }, 'django.request': { 'handlers': ['console'], 'level': 'INFO', #(DEBUG, INFO,WARNING, ERROR, CRITICAL) 'propagate': False, }, 'django.security': { 'handlers': ['console'], 'level': 'ERROR', 'propagate': False, }, 'py.warnings': { 'handlers': ['console'], }, } } Then in my views I did this stdlogger = logging.getLogger(__name__) class SomeFuct_CreateAPIView(CreateAPIView): serializer_class = Serializer_FooSerializer permission_classes = (permissions.AllowAny,) def post(self, request, format=None): stdlogger.info("------Attempting to login-------") serializer = Serializer_FooSerializer(data=request.data) I wanted to know why my statement stdlogger.info("------Attempting to login-------") is not showing up on the console. Any suggestions ? -
Djanog with React how to reset user password by sending user an email
I am using Django with React, I am implementing a method to reset user password when users forget their password. My basic idea is to: 1) Users give their email address 2) Send an email to their email adress with the link to reset their password(with SendGrid api) 3) Users type in new password to reset their password below is my serializers, views, urls and React code //views.py class PasswordResetConfirmSerializer(serializers.Serializer): new_password1 = serializers.CharField(max_length=128) new_password2 = serializers.CharField(max_length=128) uid = serializers.CharField() token = serializers.CharField() set_password_form_class = SetPasswordForm def custom_validation(self, attrs): pass def validate(self, attrs): self._errors = {} try: self.user = UserModel._default_manager.get(pk=attrs['uid']) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): raise ValidationError({'uid': ['Invalid value']}) self.custom_validation(attrs) self.set_password_form = self.set_password_form_class( user=self.user, data=attrs ) if not self.set_password_form.is_valid(): raise serializers.ValidationError(self.set_password_form.errors) return attrs def save(self): return self.set_password_form.save() // serializers.py class PasswordResetConfirmView(GenericAPIView): serializer_class = PasswordResetConfirmSerializer permission_classes = (AllowAny,) @sensitive_post_parameters_m def dispatch(self, *args, **kwargs): return super(PasswordResetConfirmView, self).dispatch(*args, **kwargs) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response( {"detail": ("Password has been reset with the new password.")} ) //urls.py path('api/passwordreset/confirm/',views.PasswordResetConfirmView.as_view(), name = 'password_reset_confirm') // React const config = { headers: { "Content-Type": "application/json" } }; const body = JSON.stringify({ new_password1: this.state.new_password, new_password2: this.state.confirm_password, uid: this.state.fetched_data.pk, token: this.state.fetched_data.token }) axios.post(API_URL + 'users/api/passwordreset/confirm/', … -
How to backup PostgreSQL database using Django?
I'm trying to export Postgresql database but it returns backup() takes no arguments (1 given). I tried various methods, but unable to export database. from pathlib import Path, PureWindowsPath from subprocess import PIPE,Popen def backup(): version = 11 # postgresDir = "D:/Program Files (x86)/PostgreSQL/9.1/bin" postgresDir = str("D:/Program Files (x86)/PostgreSQL/9.1/bin/").split('\\')[-1:][0] directory = postgresDir filename = 'myBackUp2' # output filename here saveDir = Path("D:/{}.tar".format(filename)) # output directory here file = PureWindowsPath(saveDir) host = 'localhost' user = 'postgres' port = '5432' dbname = 'BPS_Server' # database name here proc = Popen(['pg_dump', '-h', host, '-U', user, '-W', '-p', port, '-F', 't', '-f', str(file), '-d', dbname], cwd=directory, shell=True, stdin=PIPE) proc.wait() backup() -
Django html variable inside a json string
I have a json string that contains a variable. "country": { "name":"England", "city":"London", "description":"This country has a land mass of {{ info.1 }}km² and population is big as <span class=\"colorF88017\">{{ info.2 }} millions</span>.", "info":[ null, [130395], [5479] ] } As you see those variables are linked to a list in the json file. But when i do in the template html: {{ country.description }} It does not show what info.1 or info.2 contains. It just display everything as a text. How can i display the value from a variable inside a string? Thanks -
Django:How to pass a foreign key value in pre_save signal?
This are my models: class Ledger1(models.Model): creation_Date = models.DateField(default=datetime.date.today,blank=True, null=True) name = models.CharField(max_length=32) group1_Name = models.ForeignKey(group1,on_delete=models.CASCADE,null=True,related_name='ledgergroups') class Journal(models.Model): date = models.DateField(default=datetime.date.today) voucher_id = models.PositiveIntegerField(blank=True,null=True) voucher_type = models.CharField(max_length=100,blank=True) by = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') to = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') debit = models.DecimalField(max_digits=10,decimal_places=2,null=True) credit = models.DecimalField(max_digits=10,decimal_places=2,null=True) This is my signal: @receiver(pre_save, sender=Journal) def pl_journal(sender,instance,*args,**kwargs): if instance.Debit != None or instance.Credit != None or instance.By.group1_Name.group_Name == 'Indirect Expense': Journal.objects.update_or_create(date=instance.date, voucher_id=instance.id, voucher_type= "Journal",by=instance.by,to=ledger1.objects.get(name='Profit & Loss A/c'),debit=instance.debit,credit=instance.credit) I want to pass a pre_save signal that whenever a Journal objects is created which is having a group1 object name of Indirect Expense another journal with the same by with the to value of 'Profit & Loss A/c' should be automatically created... This line of code is giving me a error: ledger1.objects.get(name='Profit & Loss A/c') Error: get() returned more than one ledger1 -- it returned 2! Can anyone tell me how to get a Foreign key object in a pre_save signal? Thank you -
Problems while updating object in Django Admin Site
I override clean method of ModelForm to add custom validation, getting all the object from database. While updating I want to prevent checking on the object that is being edited. Right Now, while updating it shows ValidationError of "Event with this room in ths Event Date and Time ALready Exists" on the same object that is being Edited. How can I fix this ? class EventForm(forms.ModelForm): class Meta: model = Event fields= '__all__' def clean (self): cleaned_date = super (EventForm, self).clean() print (cleaned_date) print (obj) event_name = cleaned_date.get ('event_name') event_duration = cleaned_date.get ('event_duration') event_date = cleaned_date.get ('event_date') event_startTime = cleaned_date.get('event_startTime') event_duration = cleaned_date.get ('event_duration') event_rooms = cleaned_date.get ('event_rooms') required_event = Event.objects.filter (event_date = event_date,event_startTime= event_startTime) print ("Events in this date and time",required_event) for room in event_rooms: if required_event.filter (event_rooms = room).exists(): print ("Event with this rooms in given date and time", required_event.filter (event_rooms = room)) raise forms.ValidationError("Event with this room in ths Event Date and Time ALready Exists") break else: continue return cleaned_date If I can get ID of object that is being edited, I can prevent this error. Is there any way to get ID of object while editing?? -
Update data of forgeign key model in django
I have a two model class LabReportRelation(models.Model): labReportId = models.AutoField(primary_key=True) collectedSampleId = models.ForeignKey(CollectedSample, null=True) .... .... class Meta: db_table = 'labReportRelation' class CollectedSample(models.Model): id = models.AutoField(primary_key=True, max_length=5) collectionTime = models.DateTimeField() .... .... class Meta: db_table = 'collectedSample' I want to update the 'collectionTime' of CollectedSample model related to the 'labereportId' my current query is: LabReportRelation.objects.filter(labReportId__in=labReportIdList) .prefetch_related('collectedSampleId') .update( collectedSampleId_collectionTime=updateTime ) But I am getting this error. FieldDoesNotExist(u"labReportRelation has no field named 'collectedSampleId_collectionTime'",) Please help me. -
Error running WSGI application , ImportError: No module named 'mysite' during hosting on pythonanywhere
I am trying to deploy my Django project through the project using pythonanywhere but I am getting a problem and am really stuck. Can anyone help me with that. I am stuck on it from 2 days.Please help me out in solving this error. The WSGI.py configuration import os import sys path = '/home/blogaspp/django_project' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() And the error that shows after I reload the Page is 2019-02-22 15:32:43,068: Error running WSGI application 2019-02-22 15:32:43,078: ImportError: No module named 'mysite' 2019-02-22 15:32:43,078: File "/var/www/blogaspp_pythonanywhere_com_wsgi.py", line 16, in <module> 2019-02-22 15:32:43,079: application = get_wsgi_application() 2019-02-22 15:32:43,079: 2019-02-22 15:32:43,079: File "/home/blogaspp/.virtualenvs/myenv/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-02-22 15:32:43,079: django.setup(set_prefix=False) 2019-02-22 15:32:43,080: 2019-02-22 15:32:43,080: File "/home/blogaspp/.virtualenvs/myenv/lib/python3.5/site-packages/django/__init__.py", line 19, in setup 2019-02-22 15:32:43,080: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2019-02-22 15:32:43,080: 2019-02-22 15:32:43,080: File "/home/blogaspp/.virtualenvs/myenv/lib/python3.5/site-packages/django/conf/__init__.py", line 57, in __getattr__ 2019-02-22 15:32:43,081: self._setup(name) 2019-02-22 15:32:43,081: 2019-02-22 15:32:43,081: File "/home/blogaspp/.virtualenvs/myenv/lib/python3.5/site-packages/django/conf/__init__.py", line 44, in _setup 2019-02-22 15:32:43,082: self._wrapped = Settings(settings_module) 2019-02-22 15:32:43,082: 2019-02-22 15:32:43,082: File "/home/blogaspp/.virtualenvs/myenv/lib/python3.5/site-packages/django/conf/__init__.py", line 107, in __init__ -
My comment form in django is not working ? It,s neithere sending data to the db nor it,s displaying those?
I am trying to make a comment form in django where people can comment below my pot ,I tried a lot of things but I am not getting a appropriate solution .I hope that I wil get this here. Here,s my model for comment class Comments(models.Model): post = models.ForeignKey('app.Post', related_name='comments') author = models.CharField(max_length=200) text = models.TextField() Here,s the forms for Comment from django import forms from .models import Comments class CommentForm(forms.ModelForm): class Meta: model = Comments fields = '__all__' widgets = { 'comment':forms.Textarea(attrs = {'class':'form-control'}), 'name':forms.TextInput(attrs = {'class':'form-control'}) } Here,s the views.py code class BlogDetail(DetailView): model = Post context_object_name = 'blog_object' template_name = 'app/blog.html' def add_comments(request, pk): if request.method == 'POST': email = request.POST['email'] text = request.POST['text'] form = CommentForm() form.email = email form.text = text form.save() return render(request,'app/blog.html') And finally here,s the comment section of my blog.html <div id="comments" class="comments-area"> <div id="respond" class="comment-respond"> <h3 id="reply-title" class="comment-reply-title">Leave a Comment</h3> <form action="#" method="post" id="commentform" class="comment-form" novalidate=""> {% csrf_token %} <div class="form-group form-group-with-icon comment-form-email"> <input id="email" class="form-control" name="email" type="text" placeholder="Your Email" value="" size="10" aria-required="true"> <div class="form-control-border"></div> <i class="form-control-icon fa fa-envelope"></i> </div> <div class="form-group form-group-with-icon comment-form-message"> <textarea id="comment" class="form-control" name="comment" placeholder="Your Comment" cols="2" rows="8" aria-required="true" style="resize: none;"></textarea> <div class="form-control-border"></div> <i class="form-control-icon fa fa-comment"></i> … -
Do I really need to specify namespace in django2
Currently I'm using django 2 . Is there any importance of using namespace in django2. If then please clarify me, what is the difference between app_name and namespace. -
Django doesn't save all modelform fields in database
I customized the default django user model to make email required and username optional. I have a form for users to enter info and create an account. They enter email, first name, last name, password, confirmation password and check the terms/conditions box. All of these fields are required. In my view, I validate and clean the data and save the user to the database. This was working with a SQLite database and default project layout via the admin tool. Then I decided to use the project layout recommended in two scoops of django. I got the site working again except when I submit a user signup form, it saves the user in the database with an email and password but it doesn't save the first name or last name. I confirmed that first name and last name are being passed to the view. This makes sense because it was working previously. Maybe there's a setting somewhere that needs updating after the project layout change? I'm really not sure what's happening because it's saving user info to the database, just not all the user info. Any help would be greatly appreciated! This is my first real django project and I'm stumped … -
how to add a "id" in a django forset field
I need to add a id to my django formsets image field I know how to add a id to a modelform. Below is my post model. Below is my form template <h2> Create/Update a post</h2> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} #More images {% bootstrap_formset formset %} <br/><br/><input type="submit" class="btn btn-primary" value="Post"/> </form> Below are my models just in case class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() post_image = models.ImageField(upload_to='post_images/') Below model adds the remaining images class Prep (models.Model): #(Images) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_prep') image = models.ImageField(upload_to='post_prep_images/', blank=True, null=True) image_title = models.CharField(max_length=100) image_description = models.CharField(max_length=250) Below is my view @login_required def post_create(request): ImageFormSet = modelformset_factory(Prep, fields=('image',), extra=7, max_num=7, min_num=2) if request.method == "POST": form = PostForm(request.POST or None, request.FILES or None) formset = ImageFormSet(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() post_user = request.user for f in formset.cleaned_data: try: photo = Prep(post=instance, image=f['image'], image_title=f['image_title'], image_description=f['image_description']) photo.save() except Exception as e: break return redirect('posts:single', username=instance.user.username, slug=instance.slug) else: form = PostForm() formset = ImageFormSet(queryset=Prep.objects.none()) context = { 'form': form, 'formset': formset, } return render(request, 'posts/post_form.html', context) Now how do I … -
Limiting cpu resources in subprocess management
I have to execute c/c++ code from client to server side and I have to limit and cpu time and memory so that it doesn't affect the server. Currently I am executing the code using subprocess management on my server side. But I am unable to find a way to limit the cpu usage. eg. I have to limit cpu usage to 1s and 256mb and kill it or return some code otherwise How can I achieve this? -
Answer create view is not storing data in the database in django
I am working on a Hybrid of Quora and StackOverflow clone. I have made an "add_answer" view for letting me add answers to the questions but for some reasons the value is not being stored on the database. But when I add through admin panel then it adds answer in the database. What is wrong? The code is as follows: models.py: <code> class Answer(models.Model): content = models.TextField() user = models.ForeignKey(User,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE,blank=False) created = models.DateTimeField(auto_now_add=True) upvotes = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=True) def __str__(self): return '{}\'s Answer'.format(self.user.username) class Meta: ordering = ('-upvotes','-created') </code> forms.py: <code> class AnswerForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea,help_text='Your Answer in Detail. Note: MarkDown is enabled.') class Meta: model = Answer fields = ['content'] def __init__(self,author,question,*args,**kwargs): super().__init__(*args,**kwargs) self.user = author self.question = question </code> "add_answer" view (views.py): <code> @login_required def add_answer(request, pk): ques = get_object_or_404(Question, pk = pk) if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): cd = form.cleaned_data answer = form.save(commit=False) answer.content = cd['content'] answer.save() messages.success(request,'Success! Your Answer has been added!') return redirect('forum') else: messages.error(request,form.errors) else: form = AnswerForm(request.user,ques) return render(request,'discussion/answer_create.html',{'form':form}) </code> answer_create.html (template): {% extends 'base.html' %} {% load markdownify %} {% block title %} Add Answer {% endblock %} {% block header %} <h2 class="display-5" … -
How do I write a BeautifulSoup strainer that only parses objects with certain text between the tags?
I'm using Django and Python 3.7. I want to have more efficient parsing so I was reading about SoupStrainer objects. I created a custom one to help me parse only the elements I need ... def my_custom_strainer(self, elem, attrs): for attr in attrs: print("attr:" + attr + "=" + attrs[attr]) if elem == 'div' and 'class' in attr and attrs['class'] == "score": return True elif elem == "span" and elem.text == re.compile("my text"): return True article_stat_page_strainer = SoupStrainer(self.article_stats_html_match) soup = BeautifulSoup(html, features="html.parser", parse_only=article_stat_page_strainer) One of the conditions is I only want to parse "span" elements whose text matches a certain pattern. Hence the elem == "span" and elem.text == re.compile("my text") clause. However, this results in an AttributeError: 'str' object has no attribute 'text' error when I try and run the above. What's the proper way to write my strainer? -
Why am I getting a 'Page Not Found' error in Django's URL patterns?
I'm new to Django and I'm just trying to create a small application to output 'Hello World'. When I run my code, it says 'Page not found' and gives me the following reason: 'Using the URLconf defined in helloworld_project.urls, Django tried these URL patterns, in this order: admin/ home/ The empty path didn't match any of these.' I'm a bit confused as to why this is happening. I've included a few samples of my code. Any assistance would be greatly appreciated! urls.py from django.contrib import admin from django.urls import path from my_app.views import HomeView urlpatterns = [ path('admin/', admin.site.urls), path('home/', HomeView.as_view()) ] views.py from __future__ import unicode_literals from django.shortcuts import render from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'index.html' index.html <html> <head><title>Home Page</title></head> <body> Hello world </body> </html> -
error while trying to push repository to heroku
after creating repository in heroku I want to push my project from master branch to heroku repo. First try I got "No default language could be detected for this app" error message. so after searching I did: heroku buildpacks:set heroku/python Now it gives me "App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz" error message. So now I tried everything from the beginning and it give me "Python app detected n/ Requested runtime ("python-3.7.1") is not available for this stack (heroku-18). Can someone help? I do have requirements.txt with all requirements and runtime.txt in the same folder ad manage.py -
I can not save an object related to the User object
I'm trying to add an instance to the Books model, which is added using the inheriting form of ModelForm, the Books instance is added, but I'm not able to relate the user field to the User model. forms.py from django import forms from .models import Books class BooksCreationForm(forms.ModelForm): class Meta: model = Books fields = ('title', 'language', 'status', 'short_desc', ) models.py User = settings.AUTH_USER_MODEL class Books(models.Model): STATUS_CHOICES = ( ('Reading', 'Reading'), ('Finished', 'finished'), ) user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='books',null=True) title = models.CharField(max_length=120) short_desc = models.TextField(max_length=1000) slug = AutoSlugField(populate_from='title', overwrite=True) language = models.CharField(max_length=20, blank=True) status = models.CharField(max_length=35, choices=STATUS_CHOICES) views.py class AddBooksView(View): # .... def post(self, request, *args, **kwargs): template = self.template form = self.form(request.POST) # ?? user = User.objects.get(request.user) user = User.objects.get(username=request.user.username) if form.is_valid(): form.save(commit=False) form.user = user form.save() print("book post sucess") return redirect('main:books') context = {'form': self.form()} return render(request, template, context) But when i add in the shell, works: >>> u = User.objects.get(username='marcos') >>> u.email 'marcos@marcos.com' >>> bk = Books.objects.create(title='stackoverflow', language='Python', status='reading', short_desc='desc...') >>> bk.title 'stackoverflow' >>> bk.user = u >>> bk.user.username 'marcos' >>> bk.save() >>> for v in Books.objects.filter(user=u): ... print(v.title, v.user.username) ... stackoverflow marcos several instances that i try save through ModelForm have user = None: >>> for … -
Stripe API test keys Django
I was wondering if someone knows what the hell is wrong with my code/import of the API keys in my project. import os try: from secret import * except:print("Error: make a local version of private_settings.py from the template") # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1','sidespacer.herokuapp.com', 'sidespacer.com', 'www.sidespacer.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'users', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'stripe', 'phonenumber_field', 'multiselectfield', 'crispy_forms', #My Apps 'Spaces', 'submitaspace', 'product', 'carts', 'memberships', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Space.urls' TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR,'static_root') STATICFILES_DIRS = [STATIC_DIR, ] MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' #print(STATIC_ROOT) #print(STATIC_DIR) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media' ], }, }, ] STATIC_URL = '/static/' MEDIA_ROOT = MEDIA_DIR #where to look for files MEDIA_URL = '/media/' #where to serve files from on url WSGI_APPLICATION = 'Space.wsgi.application' if DEBUG: STRIPE_PUBLISHABLE_KEY = 'pk_test_MYPUBLISHABLEKEY' STRIPE_SECRET_KEY = 'sk_test_MYSECRETKEY' else: … -
How to create working HTML tags in textfields
I want to add HTML tags when creating posts and i want them to be converted to a normal text for the user. I want to know how to add links in posts for users to access them directly when they click on it. Any help with django or flask is appreciated. Thanks! -
Add relationship to three tables with data and strange column names
I have a Postgres database with 3 tables with data and their models in Django. I do not have control over how these tables are filled. But I need to add relationships to them. It would not be a problem for me in MsSQL, Oracle or MySql. But Im confused here. class Keywords(models.Model): id = models.AutoField(primary_key=True) keyword = models.CharField(unique=True, max_length=250) class Mapping(models.Model): id = models.AutoField(primary_key=True) keyword = models.CharField(max_length=250) videoid = models.CharField(max_length=50) class Video(models.Model): videoid = models.CharField(primary_key=True, max_length=50) -
Are there minimal footprint ways to integrated a field into an existing model (3rd party)?
I was wondering if there was a way to take an existing model and change the default id = AutoField into id = UUIDField. I have tried injecting the UUIDField through migrations, but I get a couple of issues. It doesn't like changing from int to uuid for the id and whenever I do a makemigrations it removes the key since the model reflects different, thus removing it. This is already a lot of monkey patch, which could easily break on its own if things didn't work perfectly. Migration example: def gen_uuid(apps, schema_editor): MyModel = apps.get_model(APP_NAME, MODEL_NAME) for row in MyModel.objects.all(): row.uuid = uuid.uuid4() row.save(update_fields=['uuid']) # https://stackoverflow.com/a/29587968/1294405 class Migration(migrations.Migration): def __init__(self, name, app_label): super(Migration, self).__init__(name, APP_NAME) replaces = ((APP_NAME, __module__.rsplit('.', 1)[-1]),) dependencies = [ ('APP_NAME', '0004_auto_20190222_1551'), ] operations = [ migrations.AddField( model_name=MODEL_NAME, name='uuid', field=models.UUIDField(blank=True, null=True), ), migrations.RunPython(gen_uuid), migrations.AlterField( model_name=MODEL_NAME, name='uuid', field=models.UUIDField(unique=True) ) ] I tried a couple different variants of inheriting, in hopes to get it to function properly. It works almost, for the most part, except when it got time to doing stuff with a custom manager. Most of the methods internal dealt with its model instead of the wrapper I made. Wrapper Example: class MyModel(3rdPartyModel): uuid = models.UUIDField( … -
Python3 + Gunicon 19.9 + Django 2.0 does not print my logs, but print django.request
I added a lot of logs to my django app, but non is printed.. My logs are printed to std when I do not use gunicorn (just manage.py runserver ) python manager.py runserver log : 2019-02-22 16:36:13,973 apscheduler.scheduler #INFO 162 Scheduler started 2019-02-22 16:36:13,974 management.startup_tasks #INFO 14 Scheduling Test task, to run every 5 seconds 2019-02-22 16:36:14,029 apscheduler.scheduler #INFO 878 Added job "Test" to job store "default" The following is my Django logging setting LOGGING_CONFIG = None logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "console": { # exact format is not important, this is the minimum information "format": "%(asctime)s %(name)-12s #%(levelname)-3s %(lineno)d %(message)s" } }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"} }, "loggers": { "": {"level": logging.INFO, "handlers": ["console"]}, "scheduler": { "level": logging.INFO, "handlers": ["console"], # required to avoid double logging with root logger "propagate": False, }, "django.request": { "handlers": ["console"], "level": logging.INFO, # change debug level as appropiate "propagate": False, }, }, } ) and this is no command : pipenv run gunicorn scheduler.wsgi:application --log-file - yet the only log I see [2019-02-22 16:32:17 -0800] [44478] [INFO] Starting gunicorn 19.9.0 [2019-02-22 16:32:17 -0800] [44478] [INFO] Listening at: http://127.0.0.1:8000 (44478) [2019-02-22 16:32:17 -0800] [44478] [INFO] Using worker: sync … -
Use Django Migrations to delete a table
I am moving from Rails to Django and have an existing database. I created models.py via python manage.py inspectdb > models.py, made changes, and tested some endpoints. Everything seems fine. I then ran python manage.py makemigrations and migrate to make the initial django mirgation. I noticed an old Rail's specific Model / table called ArInternalMetadata / ar_internal_metadata. I figure I could easily remove the table by simply removing the model from models.py and rerun makemigrations however when I do that, django just says No changes detected. Running migrate doesn't remove the table either.