Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing from CharField to IntegerField - Postgres Column data type hasn't changed Django
So I switched from sqlite to postgresql for production of my django reviews website- but due to psql being strongly typed, I'm having errors with my code LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. So I figured I could change the type by changing my CharFields to IntegerFields to change the type to int... like so move_in_condition = models.CharField(max_length=5,choices=RATING_CHOICES, blank=False, default='5') treatment = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5") response_speed = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5") maintenance_quality = models.CharField(max_length=5, choices=RATING_CHOICES, blank=False, default ="5") to move_in_condition = models.IntegerField(choices=RATING_CHOICES, blank=False, default=5) treatment = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5) response_speed = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5) maintenance_quality = models.IntegerField(choices=RATING_CHOICES, blank=False, default =5) with choices: class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) But then i read somewhere that sql doesn't directly support changing a string column to an int column....So i'm still getting the same error. I tried deleting my db creating it new again, and I'm still getting the same exact error after migrating. I believe this is the bit that is triggering the error def get_avg(self): return self.reviews.annotate( … -
Django returning 500 on POST request
So, I have this simple contact form, which Django handles by sending e-mails to me and to the person who contacted us. I've written an AJAX funcion to handle it. The only thing is that, no matter what I try, I keep getting an 500 status. My Django (1.11) code: def contato(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] newmessage = "Mensagem recebida de {}.\nTelefone: {}\ne-mail {}\n {}".format(name, phone, email, message) send_mail( 'Nova mensagem pelo site', newmessage, 'PLACEHOLDER@EMAIL', ['PLACEHOLDER@EMAIL'], fail_silently=False ) send_mail( 'Recebemos sua mensagem!', 'Olá, {}!\nRecebemos sua mensagem e entraremos em contato em breve.'.format(name), 'PLACEHOLDER@EMAIL', [email], fail_silently=False ) return HttpResponse() And here's my AJAX request: form.addEventListener("submit", function(event) { event.preventDefault(); let dadoscontato = { name: name.value, email: email.value, phone: phone.value, message: message.value, csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value }; fetch('/contato/', { method: 'POST', credentials: 'same-origin', headers: { "X-CSRFToken": getCookie("csrftoken"), "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify(dadoscontato), }) .then(function(response){ console.log(response) return response.json(); }) .then(function(response){ alert('Mensagem enviada com sucesso!'); }); }); -
Attempting to open the admin panel after trying to add something to my table in Django crashes the server
I'm using Django to host a site off of the local host, with webpages that ideally will exchange information with a SQLite database in Django's Models. I'm attempting https://stackoverflow.com/a/19761466/12352379 solution to taking data from my html fields and adding them to my table. When I try to do that, the console shows a GET request with all of the relevant data, with a 200 code. When I go to the admin panel of Django to see if the item appeared in the table, I get this lovely error: PS J:\School\Full Stack\nov19Branch\Django\Real Project\fullStack> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 25, 2019 - 19:25:18 Django version 2.2.7, using settings 'fullStack.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [25/Nov/2019 19:25:23] "GET / HTTP/1.1" 200 4131 Not Found: /css/simple-sidebar.css [25/Nov/2019 19:25:23] "GET /css/simple-sidebar.css HTTP/1.1" 404 3603 [25/Nov/2019 19:25:25] "GET /characterCreator/ HTTP/1.1" 200 6118 Not Found: /characterCreator/css/simple-sidebar.css [25/Nov/2019 19:25:25] "GET /characterCreator/css/simple-sidebar.css HTTP/1.1" 404 4681 [25/Nov/2019 19:25:34] "GET /characterCreator/?characterName=pls&race=human&class=fighter&strength=1&dexterity=2&constitution=3&intelligence=4&wisdom=5&charisma=6&mybtn=Click HTTP/1.1" 200 6118 Not Found: /characterCreator/css/simple-sidebar.css [25/Nov/2019 19:25:34] "GET /characterCreator/css/simple-sidebar.css HTTP/1.1" 404 4681 [25/Nov/2019 19:25:48] "GET /admin/ HTTP/1.1" 200 4599 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52860) … -
i have SyntaxError: invalid syntax when trying migrate
this is my models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.EmailField(max_length=256, unique=True) and this is my views.py from django.shortcuts import render form appTwo.moldels import User # Create your views here. def index(request): return render(request, 'appTwo/index.html') def users(request): user_list = User.object.order_by('first_name') user_dict = {'users':user_list} return render(request, 'appTwo/users.html', context=user_dict) and protwo/urls.py enter image description here and appTwo/urls.py from django.conf.urls import path from appTwo import views urlpatterns = [ path('', views.users, name='users'), ] ** i want to migrate but i have error the trace back is and File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/proTwo/urls.py", line 18, in from appTwo import views File "/home/hamid/Desktop/my_django_stuff/project_two/proTwo/appTwo/views.py", line 2 form appTwo.moldels import User ^ SyntaxError: invalid syntax (myDjango) hamid@hamid-PC:~/Desktop/my_django_stuff/project_two/proTwo$ ** -
django.core.exceptions.FieldError: Unknown field specified for CustomUser
I just want to add one field (organization) to the auth_user model of my Django 2.2 app. settings.py: INSTALLED_APPS = [ ... 'accounts.apps.AccountsConfig', ... ] ... AUTH_USER_MODEL = 'accounts.CustomUser' accounts\models.py class CustomUser(AbstractUser): organization = 'organization' def __str__(self): return self.username accounts\forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) fields = ('username', 'email', 'first_name', 'last_name', 'organization', 'password1', 'password2') def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = 'Email Address' self.fields['first_name'].label = 'First Name' self.fields['last_name'].label = 'Last Name' self.fields['organization'].label = 'Organization' accounts\apps.py class AccountsConfig(AppConfig): name = 'accounts' admin.py class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username',] ... admin.site.register(CustomUser, CustomUserAdmin) This is the Traceback: File "manage.py", line 15, in <module> (..library stuff...) File "X\staticsheet\accounts\admin.py", line 5, in <module> from .forms import CustomUserCreationForm, CustomUserChangeForm File "X\staticsheet\accounts\forms.py", line 21, in <module> class CustomUserCreationForm(UserCreationForm): File "X\Python\Python37-32\lib\site-packages\django\forms\models.py", line 266, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (organization) specified for CustomUser I've been looking for a solution to this everywhere and I've been following a simple tutorial but I keep getting this error. Any help is appreciated. -
Is it possible to have the submission option change depending on the the question type asked in django?
Scenario If you were designing an app where one user could set questions and another could answer them. Now instead of just requiring a checkbox answer each time you wish instead to change the submission type required (text, checkbox, file upload) depending on the question type being answered. Code Example class Question(models.Model): name = models.CharField(max_length=20) description = models.TextField() ANSWER_TYPE = ( ('c', 'checkbox'), ('t', 'text input'), ('u', 'file upload'), ) answer_required = models.CharField( max_length = 1, choices = ANSWER_TYPE, default = 'c', help_text = 'select the type of submission you require' ) Question So using the question code example above would this be possible and if so what would be the best way of implementing it? -
Django ORM and chained select_related
How do I do this query with Django ORM? It is a multiple join, chained from table to table, with inner and left outer joins. SELECT * FROM SERVICE INNER JOIN VISIT ON SERVICE.VisitRecordID = VISIT.VisitRecordID INNER JOIN INVOICETO on INVOICETO.InvoiceTo = Visit.InvoiceTo INNER JOIN CM_PATIENT ON VISIT.PatientNo = CM_PATIENT.PATIENT_ID INNER JOIN DOCTOR on DOCTOR.DoctorCode = VISIT.ServDoctor INNER JOIN FEES ON FEES.ItemNo = SERVICE.ItemNo LEFT OUTER JOIN REC_SERV ON REC_SERV.ServRecID = SERVICE.ServRecID LEFT OUTER JOIN RECEIPT ON REC_SERV.ReceiptNo = RECEIPT.ReceiptNo The first join I can do with q = Service.objects.select_related('visitrecordid',).all() which makes sql like: SELECT * FROM [SERVICE] LEFT OUTER JOIN [VISIT] ON ([SERVICE].[VisitRecordID] = [VISIT].[VisitRecordID]) so I am getting left outer joins, not inner joins, which is one question. But most of all, I don't know how to do the second join, where I find a table related to Visit. -
How can i add Java component to my django app project in heroku?
I am building an django app for my work to extract some pdf info, obviously runs perfectly in the virt environment, however when deploying to heroku i am facing some java plug ins issues, i have added buildpack for heroku/java, i was able to use some pom.xml file i found in google, however now i got this error: NO IDEA WHATS NEEDED NEXT....... remote: [INFO] Packaging webapp remote: [INFO] Assembling webapp [application-mvc] in [/tmp/build_6ef3792faeda2226e0eed7f586b0857f/target/ApplicationName] remote: [INFO] Processing war project remote: [INFO] Webapp assembled in [59 msecs] remote: [INFO] Building war: /tmp/build_6ef3792faeda2226e0eed7f586b0857f/target/ApplicationName.war remote: [INFO] ------------------------------------------------------------------------ remote: [INFO] BUILD FAILURE remote: [INFO] ------------------------------------------------------------------------ remote: [INFO] Total time: 8.912 s remote: [INFO] Finished at: 2019-11-25T22:31:19Z remote: [INFO] ------------------------------------------------------------------------ remote: [ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project application-mvc: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1] remote: [ERROR] remote: [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. remote: [ERROR] Re-run Maven using the -X switch to enable full debug logging. remote: [ERROR] remote: [ERROR] For more information about the errors and possible solutions, please read the following articles: remote: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException remote: … -
Django: Best way to display quantity, product, brand and allow only quantity to be updated for all list
In Django 2.1 I need to be able to update the quantities in an order when click save button at the bottom of the page. So far the approach is to use a modelformset_factory but this leaves the product and brand open to be by the user and it is needed to display them as non-editable text. Is this the best aproach and how can I make ready only or display as normal text the fields product and brand while leaving quantity enabled to be changed? Here is the code: models.py class OrderLine(models.Model): order_number = models.ForeignKey('Order', blank=False, null=False, on_delete=models.CASCADE) product = models.ForeignKey('Product', blank=True, null=True, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True) brand = models.ForeignKey('Brand', blank=True, null=True, on_delete=models.CASCADE) forms.py class OrderLineForm(forms.ModelForm): class Meta: model = OrderLine fields = ['quantity','product','brand'] views.py def OrderLineUpdate(request): OrderLineFormSet = modelformset_factory(Levantamiento, form=OrderLineForm, extra=0) if request.method == "POST": formset = OrderLineFormSet(request.POST) if formset.is_valid(): formset.save() return HttpResponseRedirect('/orders/order-detail') else: formset = OrderLineFormSet(queryset=OrderLine.objects.all()) return render(request, 'order/detail/update.html', {'formset': formset} template update.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {{ formset }} <input type = "submit" class ="btn btn-primary" value="Save"> -
How to enable column sorting on foreign fields in Django Admin
The following are my models: class A(models.Model): a_one = models.CharField() a_two = model.ForeignKey(B) class B(models.Model): b_one = models.Charfield() b_two = models.ForeignKey(C) class C(models.Model): c_one = models.CharField() c_two = models.CharField() I would like to create a table in django admin for model A with columns a_one, a_two, b_one, c_one, and c_two where all of them are sortable. How can I achieve this? -
TypeError: TypeError: expected string or bytes-like object. While i am trying to create django object
I am faced with issue while trying to create object from django models. I have the Fixture model from django.db import models from django.contrib.postgres.fields import JSONField import datetime from django.utils import timezone class Fixture(models.Model): fixture = models.IntegerField(primary_key=True) league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL, to_field="league") event_date = models.DateTimeField(null=True) event_timestamp = models.DateTimeField(null=True) firstHalfStart = models.DateTimeField(null=True) secondHalfStart = models.DateTimeField(null=True) round_count = models.CharField(max_length=10) status = models.CharField(max_length=20) statusShort = models.CharField(max_length=15) elapsed = models.IntegerField(null=True) venue = models.CharField(max_length=170) referee = models.CharField(max_length=70) home_team_id = models.IntegerField(null=True) away_team_id = models.IntegerField(null=True) goal_of_home_team = models.IntegerField(null=True) goal_of_away_team = models.IntegerField(null=True) half_time_score = models.CharField(max_length=15) full_time_score = models.CharField(max_length=15) extratime = models.CharField(max_length=50) penalty = models.CharField(max_length=50) lastModified = models.DateTimeField(auto_now=True) I have json file where i store some json data from which i want to create objects of this model fixtures_date = open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagues_date.txt"), "r") leagues_json = json.load(fixtures_date) leagues_json = leagues_json["api"]["fixtures"] for item in leagues_json: fixture_id = item["fixture_id"] league_id = item["league_id"] event_date = item["event_date"] event_timestamp = item["event_timestamp"] firstHalfStart = item["firstHalfStart"] secondHalfStart = item["secondHalfStart"] round_count = item["round"] status = item["status"] statusShort = item["statusShort"] elapsed = item["elapsed"] venue = item["venue"] referee = item["referee"] home_team_id = item["homeTeam"]["team_id"] away_team_id = item["awayTeam"]["team_id"] goal_of_home_team = item["goalsHomeTeam"] goal_of_away_team = item["goalsAwayTeam"] half_time_score = item["score"]["halftime"] full_time_score = item["score"]["fulltime"] extratime = item["score"]["extratime"] penalty = item["score"]["penalty"] Now i am trying to create objects … -
Making a new migration for a Django app, ignoring all other app models
I have made model changes to a Django model Bicycle in app bicycles in a project where another unrelated app cars has a model Car which has changes that has model changes without the accompanying makemigrations. The developer of cars.Car is unavailable and I cannot change their source code, but I still need to make a new migration for bicycles.Bicycle. Is this possible at all in Django 2.2? When I run makemigrations bicycles, I get this: You are trying to add a non-nullable field 'year' to car without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: As I said, the bicycles app is completely unrelated to cars, so I feel like I should be able to make the migration for the bicycles app only? -
How to serialize a list of objects?
The Django-Rest-Framework documentation (https://www.django-rest-framework.org/api-guide/serializers/) gives the following example for serializing a list of objects: queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) serializer.data I try to do something similar with the following code: @api_view(['GET']) def postComments(request, pk): """ Retrieve all comments with originalPostId = pk. """ if request.method == 'GET': comments = Comment.objects.all() comments = comments.filter(originalPostId = pk) serializer = CommentSerializer(comments, many=True) if serializer.is_valid(): return Response(serializer.data) logger.error(serializer.errors) However, right off the bat I get the following error: AssertionError: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. This other post (django-rest-framework: Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance) seems to address this, but the answer suggests that putting in data= when calling my CommentSerializer would serve to deserialize instead of serialize, which is not what I want. However, when I do run with the line serializer = CommentSerializer(data=comments, many=True) I get the error{'non_field_errors': [ErrorDetail(string='Expected a list of items but got type "QuerySet".', code='not_a_list')]} Here is my serializer, in case that matters: poster = UserSerializer() community = CommunitySerializer() originalPost = PostSerializer() class Meta: model = Comment fields = ['post', 'community', 'poster', 'originalPost', 'originalPostId'] def create(self, validated_data): userData = … -
Make rows in Django table clickable
First off, I'm not a web developer. I'm just trying to write a simple web app for myself and I decided to do it in Django because I am very comfortable with Python. Anyway, my main page is essentially a django_tables2 table on the left side of the screen and a chart.js graph on the right. I've got the skeletons of both of these up. But now I cannot figure out to add click events to the rows in my table. What I'd like to do is have the graph updated whenever I click on a row in the table. If anyone has a simple example of this handy, that would be rad. I'm not sure what code you need from me, so just ask if there is something that would make it easier to see what I'm doing. -
Filter on Nested serializer - Django REST
I have the following models.py: class Question(models.Model): code = models.CharField(max_length=12) text = models.CharField(max_length=1000, null=True) catgeroy = models.ForeignKey( Category, on_delete=models.PROTECT, null=True, blank=True, db_index=True, related_name='category') class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.PROTECT, null=True, blank=True, db_index=True, related_name='question') exam = models.ForeignKey(Exam, on_delete=models.CASCADE) value = models.FloatField(null=True, blank=True) class Exam(models.Model): year = models.IntegerField() my nested serializer looks like this: class NestedQuestionAnswerSerializer(serializers.ModelSerializer): answer = AnswerSerializer(many=True, read_only=True) class Meta: model = Question fields = ( ('id','code', 'text', 'answer') ) class AnswerSerializer(serializers.ModelSerializer): related_name = 'answer' class Meta: model = Value fields = ('id', 'value', 'question', 'exam') my views.py looks like this: class QuestionAnswerViewSet(BaseCertViewSet): queryset = Question.objects.all() serializer_class = serializers.NestedQuestionAnswerSerializer filter_backends = [filters.DjangoFilterBackend] filterset_fields = ('category',) my urls.py looks like this: router.register('question-value', views.QuestionAnswerViewSet, 'question-answer') What I would like to be able to do is to filter by both Category AND Exam(which is a child attribute). So something like this: https://example.com/api/question-value?category=4&exam=21 This potentially should return all the Questions that are part of category=4 AND appeared on exam=21. I have no problem filtering by category alone, but can't seem to filter on exam which is a child foreign key. I've tried many solutions on SO but none seem to do the above. -
Allowing user to only create certain amount of objects with non-paid account, using Dajngo Stripe
I currently have a Personal CRM app that allow user to create Contacts and then create Logs for those contacts. Here is how the code looks like. views.py class CreateContact(LoginRequiredMixin, CreateView): model = Contact template_name = 'network/contacts_list.html' form_class = ContactForm def get_success_url(self): return reverse('home') def form_valid(self, form): form.instance.contact_owner = self.request.user return super(CreateContact, self).form_valid(form) def get_context_data(self, **kwargs): context = super(CreateContact, self).get_context_data(**kwargs) context['contacts'] = Contact.objects.filter(contact_owner=self.request.user) return context class CreateContactLog(LoginRequiredMixin, CreateView): model = ContactLog template_name = 'network/contact_detail.html' fields = ('log_type','body',) def get_success_url(self): return reverse('contact-detail', kwargs={'id':self.kwargs['id']}) def form_valid(self, form): current_contact = Contact.objects.get(contact_owner=self.request.user, contact_id=self.kwargs['id']) form.instance.contact_owner = self.request.user form.instance.contact_id = current_contact return super(CreateContactLog, self).form_valid(form) def get_context_data(self, **kwargs): current_contact = Contact.objects.get(contact_owner=self.request.user, contact_id=self.kwargs['id']) context = super(CreateContactLog, self).get_context_data(**kwargs) context["contact_info"] = current_contact context["first_name"] = current_contact.first_name context["id"] = current_contact.contact_id context['log_entries'] = ContactLog.objects.filter(contact_owner=self.request.user, contact_id=current_contact) return context Everything is working perfectly. Now I want to start accepting payments I want to integrate my app with Stripe. The best way to do this is with the third party package dj-stripe. I want to have 2 plans, free and paid. I want to allow free plan users to create up to 10 contacts. Reading the documentations for django-stripe I see that I can use class based views, but I dont't understand how I would approach … -
Django: conditionally override get_queryset
Django 1.11 I have two models. I would like to conditionally override the default behavior of their manager. class Project(models.Model): title = models.CharField(max_length=50) class Task(models.Model): title = models.CharField(max_length=50) project = models.ForeignKey(Project, null=True, blank=True, related_name='tasks') protected = models.BooleanField(default=False) objects = TaskManager() class TaskManager(models.Manager): def get_queryset(self): return super(TaskManager, self).get_queryset().exclude(protected=True) Tasks where protected = True should be filtered from any query not explicitly asking for them (I am aware the Django docs advise against filtering on overrides of get_queryset()) With the above code, any query on project.tasks returns all related tasks where protected = False, as expected. How can I conditionally override get_queryset() to return only related tasks where protected = True? Something like: project.protected_tasks or project.tasks.protected? -
App stuck on printing information from very first input
views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import AddmemberForm, Lookupmember from .models import Addmember def add_member(request): if request.method == 'POST': form = AddmemberForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'The member has been added.') return redirect('front-page') else: form = AddmemberForm() return render(request, 'members/add.html', {'form': form}) def list_member(request): context = Addmember.objects.all() return render(request, 'members/list_members.html', {'context': context}) def look_up_member(request): if request.method == 'POST': form = Lookupmember(request.POST) if form.is_valid(): member_id = form.cleaned_data['member_id'] if Addmember.objects.filter(id = member_id): for x in Addmember.objects.all(): if Addmember.objects.filter(id = member_id): context = { 'name': x.name, 'email': x.email, 'address': x.address, 'city': x.city, 'state': x.state, 'zip_code': x.zip_code, 'phone_number': x.phone_number, } return render(request, 'members/about_members.html', context) else: messages.error(request, f'Error: This member does not exist.') return redirect('look_up_member') else: form = Lookupmember() return render(request, 'members/look_up_member.html', {'form': form}) The idea is to use a form that just takes one input, the member id. This is supposed to be a lookup feature. If no member exists with that ID, then an error appears. If the member ID does exist, then it's supposed to redirect to a page with the member's information. When I tested this for the very first time, I typed "1" for the member ID. This member does indeed exist, so I … -
I need a foolproof checklist for hosting an already built e-commerce site on Amazon Web Services
I have built an e-commerce website on my local computer that uses Django version 2.2 and python 3.7. The website consists of: fancyfetish is the main project directory. The apps, (cart, users, baseapp, products, blog) are all stored in their own directory 'apps. Within the settings folder I have three settings files: - production.py - base.py - development.py The static file in the main directory is where I put collectstatic files. Media is where I store externally uploaded images (product images for example) Docs is just random bits like a hand drawn site layout. Static files like JS and CSS are stored within baseapp, within apps. I want to host this website on Amazon Web Services, and I assume I need to use Elastic Beanstalk. I went through the process of trying to host with free version of EB, installed the EB CLI, and after using eb create and eb deploy on the CLI my website appeared. However, the static files didn't load properly in the first instance because I had not properly configured DJANGO_SETTINGS_MODULE. I have now done this. But before deploying I added eb migrate functionality so that I could also migrate my database. This seems to have … -
How to get or create credentials from authenticated user in django-allauth
I think I might be missing something obvious, but I cannot figure out the answer to my question. I have setup django-allauth on my project, added Google auth, enabled the API, ran the server, and successfully used the app for authentication. Here's where I'm getting stuck: Once the user is authenticated, I'm wanting the user to be able to view their calendar but I cannot figure out how to build the credentials using the credentials of the already authenticated user. I know that in order to get the calendar, I have to run: service = build('calendar', 'v3', credentials=creds) calendar = service.calendars().get(calendarId='primary').execute() print(calendar['summary']) but I cannot figure out how to build the value for credentials Any help would be so greatly appreciated. -
django cookiecutter compile sass in docker
I am running cookiecutter-django locally with docker. How do I compile the sass? I run the app by doing $ docker-compose --file local.yml up. When I edit the source code template files the web app reflects those changes at http://localhost:8000 When I edit static/sass/project.scss the site does not get the new css rules. I tried running $ docker-compose --file local.yml run --rm npm install but I get the message ERROR: No such service: npm. Resources that might help: https://cookiecutter-django.readthedocs.io/en/latest/live-reloading-and-sass-compilation.html https://cookiecutter-django.readthedocs.io/en/latest/deployment-with-docker.html#building-running-production-stack -
Can I make queries for tables which generated in pgAdmin without using SQL-scripts?
I have five tables in PostgreSQL database of my Django-project. I made two of these five tables as follows: made two classes/models in the models.py -> python manage.py makemigrations -> python manage.py migrate. I made other three tables as follows: I wrote scripts CREATE TABLE and INSERT some data into it using Query Editor of pgAdmin. I can retrieve objects from two first tables like here (first method) using Manager. But can I retrieve objects from three other tables (which I made in Query Editor of pgAdmin) using Manager (first method)? Now I don't understand how to do it because I don't have classes/models of three tables in models.py. Yes, I know about second method (using SQL script). But I would like to know there possibility to use only first method for tables created in Query Editor of pgAdmin is! -
Upload and overwrite CSV in specific location - django app
I currently have a django web app which reads in data from a csv and creates graphs using that data, the file hierarchy looks like this: csvparser csvparser init.py settings.py urls.py wsgi.py dataset admin.py apps.py models.py stored.csv ****** tests.py views.py The csv file that my graphs are made from (stored.csv) is included right in the application's folder, but now I want to have it so that I can upload any csv file (with the same headers) to that location with that name so that my app will do the same thing with an uploaded csv as it does with the current stored.csv. Essentially I just want to have functionality to upload a csv which overwrites the current stored.csv file at that location, is there an easy way to do this? -
Does git update or does git overwrite when pushing a sqlite database
FYI: Retired programmer new to git. Development platform is linux workstation. Current production is on Heroku. Framework is django using sqlite. Database is a flat file called db.sqlite3. When I push to Heroku using git, is the entire file of db.sqlite3 pushed from my workstation to the server? or Is some automagic worked so that the remote db.sqlite3 is only updated? (Obviously the latter is more efficient as the db grows in size.) thanks -
Discarding a Javascript file and using another one in an HTML template page in Django 2.2
I have an X.html web page which extends base.html. X.html is a django 2.2 template and extends base.html as below : {% extends 'base.html' %} {% load i18n %} {% load crispy_forms_tags %} {% block title %}{% trans "x-box" %}{% endblock title %} {% block content %} In the base.html page I have the below jQuery included: <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> This jQuery is included in X.html also. I want to discard the above jQuery for x.html and add the below jQuery in x.html : <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> Because the slim version causes problem for x.html. But I cannot delete slim version from base.html as it is extended by several other pages.