Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Showing time according to User's Country
I am building a BlogApp and I am stuck on a Problem. What i am trying to asking :- As everybody know that Django provides Time Zone select feature in settings.py like TIME_ZONE = 'Asia/Sanghai' AND i have made a instance date = models.DateTimeField(auto_now_add=True) AND date_added = models.DateTimeField(null=True,default=timezone.now) in models.py So my time is of Asia AND whenever i deploy my webapp and A user from Europe try to access the webapp and try make a BlogPost, So what will be the time for Europe's User ? My selected time ( Asia/Sanghai ) ? OR `Europe's User Time ? If his/her time will be My selected time then how can i make it like : When someone visit the site then show time according to User's timezone ? I have no idea, What will be the timezone when someone try to access the site from different Country. Any help would be Appreciated. Thank You in Advance. -
Social media algorithms
I'm learning django my first project is social media app, how social media algorithms work (the suggestion algorithms to be specific)? Is it written by the backend (django) or there's something else? -
How do I select more than one of the same item in the serializer?
I'm trying to make this app where I can select the items I want to buy. I want to select two cakes, for example, but so far I can't select more than one. How do I do that? The field I need to change is 'food' since this one has options like 'cake', 'pastries', etc. I want the user to be able to select as many of each item as they want. I tried with many=True but something is not working out. This is the serializer so far: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__' This is the model: class Food(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class Order(models.Model): food = models.ManyToManyField('Food', related_name='order', blank=True) def __str__(self): return self.food -
Images In CSS Integrity Issue
How do I link a local image in CSS as background-image? When I go to my localhost and console there is an error which says: " Failed to find a valid digest in the 'integrity' attribute for resource 'http://127.0.0.1:8000/static/css/base.css' with computed SHA-256 integrity 'VamhLHC0Rd5RsK5ayIQbhNx167AvkjG9xrdEDZaSFoc='. The resource has been blocked. ". I am using Django Framework. How do I fix this? This is my first question, so sorry if it is hard to understand. -
I trial make Notification for Comment
I trial make Notification for Comment by Many-to-many relationships how fix it raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use NotfFaId.set() instead. [17/Apr/2021 03:37:31] "POST /forum/addcomment/ HTTP/1.1" 500 73061 class CommentT(MPTTModel): Topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='author') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') NotfFaId = models.ManyToManyField( User, related_name='NotfFaVId', default=None, blank=True) content = models.TextField() publish = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class MPTTMeta: order_insertion_by = ['publish'] def addcomment(request): if request.method == 'POST': if request.POST.get('action') == 'delete': id = request.POST.get('nodeid') c = CommentT.objects.get(id=id) c.delete() return JsonResponse({'remove': id}) else: comment_form = NewCommentTForm(request.POST) # print(comment_form) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) result = comment_form.cleaned_data.get('content') user = request.user.username user_comment.author = request.user user_comment.NotfFaId = request.user user_comment.save() Topic.objects.get(id = request.POST.get('Topic') ).NotfFaV.add(request.user) # CommentT.objects.get(id=user_comment.id).NotfFaId.add(request.user) return JsonResponse({'result': result, 'user': user,'id': user_comment.id }) -
Django GET request not reading parameters
I am using Django and the Django REST Framework to code a web API, I created a view for user authentication. It has a corresponding model called "Users" which takes fields "email", "password", etc. The view also has a corresponding serializer called UserSerializer. Here is the code for the view, which is supposed to check if the provided email and password exists in my Users table. class UsersView(APIView): def get(self, request, _email=None, _password=None): if _email and _password: try: queryset = Users.objects.get(email=_email , password=_password) except Users.DoesNotExist: return Response({'error': 'No user with the given credentials.'}, status=400) read_serializer = UsersSerializer(queryset) return Response(read_serializer.data) return Response({'error': 'Outside.'}, status=400) The issue I am having is when I send a get request with a body that contains fields for _email and _password, their values are not interpreted, they just stay null. For example, if I add the line return Response({_email}, status=400) (which simply prints the value of email) directly under the function definition (before the if statement), I get a response "null", even when I have passed in a valid value. Another way I tested this is by removing the function parameters altogether and instead defining variables _email and _password locally within my function and giving them … -
Django/React App: How to have both Django URLS (for the api to send data) and React URLS (to render my components) in my web app, compatibly
I just added this to the urls.py in my react folder: re_path(r'^(?:.*)/?$', views.index), after following this stackoverflow post: react routing and django url conflict. My error in the dev tools is: Unknown_URL_Scheme However, in my situation, this creates problems. My method of sending JSONs to my react is through the url: "api/leads," which is now inaccessible. How do I produce a way for my react urls to exist in harmony with my django urls? Attached are my django urls.py, react--> App.js, urls.py, views.py, index.html, and DataFetching.py (where you will be able to see how I send the data from my api). Django: urls.py from django.urls import path from . import views urlpatterns = [ path('api/lead/', views.LeadListCreate.as_view()), ] Django Project: urls.py from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('', include('leads.urls')), path('', include('frontend.urls')), ] React--> urls.py from django.urls import path, re_path from . import views urlpatterns = [ #path('', views.index), re_path(r'^(?:.*)/?$', views.index), ] By the way, I tried to look at the documentation for urls(r^...) and it wouldn't tell me how to import it, but instead basically said that urls is basically the same as re_path; this may be the problem, nonetheless, I would … -
Return updated HTML table values into Views.Py
Hi I have an html table that has values that is originally pulled from a database. They are editable and if the user updates the value, I want to be able return the updated values to Views.py and then from there save the updated value back into the database. For example, I have the table below: <table> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> {% for x in VAR %} <tr> <td>Yes</td> <td>{{ x }}</td> <td><div contenteditable>{{ x.a }}</div></td> <td><div contenteditable>{{ x.b}}</div></td> <td><div contenteditable>{{ x.c}}</div></td> </tr> {% endfor %} </table> If they update x.a for example, I want to return the new value to Views. When I try a POST request, I return a blank value / empty list. How do I return the updated values into my Views.py? -
How do I check if user exists or not and add or update the database in DRF according to that?
I am writing an app in which the user inputs either their email or number to continue. If the user only writes one of those, I need to check if either the email or number belong to an existing user so I can use that user. If the user writes both things, I need to check if the user exists (if it does, I use it, if not I create it). If the user exists with only email or number, I need to update the other field that does not match. I wrote something but I'm not sure how to go on, I'm pretty new at this. This is what I have so far in my serializer: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' def checkuser(self, email, number): if order['email'] or order['number'] in User: return User elif order['email'] or order['number'] not in User: pass elif order['email'] and order['number']: if not in User: UserSerializer() elif order['email'] or order['number']: if User.objects.filter(**validated_data).exists(): return User.objects.create(**validated_data) -
Multiple autocomplete-light dropdowns in django template
I am building a web application that requires searching for a specific user record by entering one of two attributes: first name OR last name. Eventually there will be two more search attributes, but currently having problems with having two autocomplete-light drop-downs in the same template. The problem is that only the second input is working as expected. Below are the relevant code sections (with irrelevant code removed). This approach is not "DRY" but my priority is to have a working implementation before optimization/refactoring. forms.py class StudentChoiceFieldLN(forms.Form): students = forms.ModelChoiceField( queryset=Student.objects.all().order_by("last_name"), widget=autocomplete.ModelSelect2(url='student-ln-autocomplete'), ) def __init__(self, *args, **kwargs): super(StudentChoiceField, self).__init__(*args, **kwargs) # without the next line label_from_instance does NOT work self.fields['students'].queryset = Student.objects.all().order_by("last_name") self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name) class StudentChoiceFieldFN(forms.Form): students = forms.ModelChoiceField( queryset=Student.objects.all().order_by("first_name"), widget=autocomplete.ModelSelect2(url='student-fn-autocomplete'), ) def __init__(self, *args, **kwargs): super(StudentChoiceFieldFN, self).__init__(*args, **kwargs) # without the next line label_from_instance does NOT work self.fields['students'].queryset = Student.objects.all().order_by("first_name") self.fields['students'].label_from_instance = lambda obj: "%s %s" % (obj.last_name, obj.first_name) views.py class StudentLNAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Student.objects.all() if self.q: qs = qs.filter(last_name__istartswith=self.q) return qs class StudentFNAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Student.objects.all() if self.q: qs = qs.filter(first_name__istartswith=self.q) return qs def index(request): students_choice_ln = StudentChoiceFieldLN() students_choice_fn = StudentChoiceFieldFN() context = { 'students_choice_ln': students_choice_ln, 'students_choice_fn': … -
bytes object has no attribute 'encode'
/tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/decorators/cache.py in _wrapped_view_func response = view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/utils/decorators.py in _wrapper return bound_method(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/contrib/auth/decorators.py in _wrapped_view return view_func(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in dispatch response = super().dispatch(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/django/views/generic/base.py in dispatch return handler(request, *args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/utils.py in post return super().post(*args, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in post return self.render_next_step(form) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in render_next_step return super().render_next_step(form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render_next_step return self.render(new_form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/formtools/wizard/views.py in render context = self.get_context_data(form=form, **kwargs) … ▶ Local vars /tmp/8d9010f9ad09a86/antenv/lib/python3.7/site-packages/two_factor/views/core.py in get_context_data rawkey = unhexlify(key.decode('ascii')) im getting this error and i dont know what exactly should i do, i already tried to change rawkey = unhexlify(key.decode('ascii')) to rawkey = unhexlify(key.encode('ascii')) and im still getting the same exact error. im … -
Django Server Wont Relaunch after change
I've been experimenting with both the django and django rest framework. My projects all used to be working fine, but the other day I had to hard reset my macbook. Since then whenever I go open an old project, or even make a new one whenever I make changes in my vscode project folder, my server does not update and relaunch. Also when I run 'python manage.py migrate' it says there are no migrations to be made, even though I have created new models. The only time python manage.py migrate' had worked was straight after using the 'pip install django'. (Just an fyi, but I completely remade a project I had done previously (a follow through on youtube), when I had first made the project it worked perfectly, but when remaking it the server does not relaunch after changes nor do migrations work) -
PyMongo + Django: MongoClient constructed in settings returning no data
My Django app constructs a MongoClient in the settings file, and this works in local environments. mySettings.py: # mysettings.py MONGO_HOST = os.environ.get('MONGO_HOST') MONGO_PORT = int(os.environ.get('MONGO_PORT')) MONGO_DATABASE = os.environ.get('MONGO_DATABASE') MONGO_USERNAME=os.environ.get('MONGO_USERNAME') MONGO_PASSWORD=os.environ.get('MONGO_PASSWORD') MONGO_CLIENT = MongoClient( host=MONGO_HOST, port=MONGO_PORT, username=MONGO_USERNAME, authSource=MONGO_DATABASE, password=MONGO_PASSWORD, connect=True ) When I use this instance on a local workstation, it works as expected. However, when I use it in a Kubernetes pod, queries like the ones below return zero/empty instead of the proper count/data. #mybrokenscript.py client = settings.MONGO_CLIENT database = client["mydatabase"] collection = database.get_collection('myCollection') print("Count: ", collection.count()) # returns 0, though the collection contains data for doc in collection.find(): # we never get here When I construct a local MongoClient with the same values, it works as expected. #myworkingscript.py client = MongoClient( host=settings.MONGO_HOST, port=settings.MONGO_PORT, username=settings.MONGO_USERNAME, authSource=settings.MONGO_DATABASE, password=settings.MONGO_PASSWORD ) database = client["myDatabase"] collection = database.get_collection('myCollection') print("Count: ", collection.count()) # returns the right number for doc in collection.find(): # works as expected To be clear, the two scripts above generate different results. In the first, Count is 0. In the second, Count is the number of documents in the collection. Any idea what could be happening? Python 3.6.8 Mongo 4.4.4 pymongo 3.7.1 Django 3.1 -
Django Storing Images Locally And Remotely
I have built an image sharing website on django in which i'm storing my thumbnails images on server and original images on object storage. The problem i'm facing is that i'm able to upload the images onto the server and object storage but facing issues to download from object from object storage as my media_root is set at the location of the server. This is my settings.py code : # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') This is my download function code : def download(request,id): previous_url = request.META.get('HTTP_REFERER') if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() ''' End reCAPTCHA validation ''' if result['success']: image = Image.objects.get(id=id) file_name = os.path.basename(image.image.name) file_path = image.image.name fl = storage.open(file_path, "rb") content_type = mimetypes.guess_type(file_path)[0] response = HttpResponse(fl, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(file_path) return response else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') return redirect(previous_url) else: return redirect(previous_url) Please refer the error image while download the image : Error Image -
How can I make a field case insensitive and unique only?
I'm trying to add object to my models that are unique and case insensitive so if I add 'car' first and then I try to add 'cAr' it should return an error. I don't know how to that, though. How can I make this happen? This is the model: class Food(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name This is the serializer: class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__' -
Django rest-framework ListCreateAPIView doesn't return the full path for the file
I just started using Django rest-framework, and I wanted the JSON response to return the URL for the file stored in the server, I used generics.ListCreateAPIView class class PeopleList(generics.ListCreateAPIView): queryset = People.objects.all().order_by('registration_time') serializer_class = PeopleSerializer and it worked actually! it returned a full path clickable URL: { "id": 1, ... "profile": "http://127.0.0.1:8000/media/profile_image/IMG_20190826_105834_vwKLf10.jpg", ... }, But then I had to use the list function because I needed the request object, now the response only contains the path without the domain: { "id": 1, ... "profile": "/media/profile_image/IMG_20190826_105834_vwKLf10.jpg", ... }, so the question is, How can I return the whole URL? -
How to tell serializer field is in nested dict?
I have the following models: class Holding(models.Model): ticker = models.CharField(max_length=32) class Fund(models.Model): name = models.CharField(max_length=32) holdings = models.ManyToManyField(Holding) JSON looks like this: { "name": "iShares Index Fund" "holdings":[ { "holding": { "ticker": "AAPL" }, { "holding": { "ticker": "AMZN" } ] } My serializers looks like this: class HoldingSerializer(serializers.ModelSerializer): class Meta: model = Holding fields = '__all__' class FundSerializer(serializers.ModelSerializer): holdings = HoldingSerializer(many=True) class Meta: model = Fund fields = '__all__' however it doesn't work because holding is nested How do I tell the HoldingSerializer that the ticker is inside a nested object? I've tried class HoldingSerializer(serializers.ModelSerializer): ticker = serializers.CharField(source='holding.ticker') class Meta: model = Holding fields = '__all__' but I dont think source is used to specify the source in the json; it is used to specify the source from the django models, is that correct? however I still get the error {'holdings': [ { 'ticker': [ErrorDetail(string='This field is required.', code='required')], }, { 'ticker': [ErrorDetail(string='This field is required.', code='required')] }] } -
Adding array into excel using openpyxl (formatting issue)
I am using "openpyxl" to put an array into an excel file for users to download on a django site. The data goes into the excel fine using the following loop: for row_num, row in enumerate(matrix, 3): for col_num, item in enumerate(row, col_start - 12): ws.cell(column=col_num, row=row_num, value=item) wb.save(excel_file_path_from_db) My problem is that when the data enters the excel is is not in number format. I think it could be because i am getting my atix values from a user input via: matrix = ast.literal_eval(list(request.GET)[0]) print(matrix) Any ideas how I can make my matrix come into the excel file in number format? -
Module not found while running server in django
I am trying to start a new django project and I have decided to split my settings into production, staging and development following this tutorial https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html On running python manage.py runserver --settings=mysite.settings.development,I get this error File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'crosspoint.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/user/crosspoint/crosspoint-venv/lib/python3.6/site-packages/django/core/management/__init__.py", line … -
Django | Adding/changing code in 3rd party packages with monkey patching
(+/- 3 months experience with Django) I'm using the django-newsletter package to create and send newsletters to subscribers on my website. It uses a message.html template for which the context is added in the Submission model: class Submission(models.Model): # Some irrelevant code, only showing the send_message method below: def send_message(self, subscription): variable_dict = { 'subscription': subscription, 'site': Site.objects.get_current(), 'submission': self, 'message': self.message, 'newsletter': self.newsletter, 'date': self.publish_date, 'STATIC_URL': settings.STATIC_URL, 'MEDIA_URL': settings.MEDIA_URL } unescaped_context = get_context(variable_dict, autoescape=False) subject = self.message.subject_template.render( unescaped_context).strip() text = self.message.text_template.render(unescaped_context) message = EmailMultiAlternatives( subject, text, from_email=self.newsletter.get_sender(), to=[subscription.get_recipient()], headers=self.extra_headers, ) if self.message.html_template: escaped_context = get_context(variable_dict) message.attach_alternative( self.message.html_template.render(escaped_context), "text/html" ) # some more code irrelevant to the question message.send() Essentially upon Submitting the newsletter, the context is added in variable_dict in the Submission.send_message method. In order to add more Personalization possibilities I would like to add my own context variables to this. From what I understand is that it's best to use monkey patching to achieve this, but I am not able to access the variable_dict from outside the method itself. Below is my monkey patch code: ## Monkey Patching ## # monkey_patches.py DJANGO_NEWSLETTER_CONTEXT_PATCH = True # adds context to Submission def monkey_patch(): if DJANGO_NEWSLETTER_CONTEXT_PATCH: from newsletter.models import Submission old_send_message … -
how to maintain website on django with redis and memchached on aws
weird question but can I find explanation of how I should control this structure on ec2 instances like one instance for Django one for Redis and other? or I can do in one instance what you all think about that -
Add forms to a Django formset dynamically using htmx?
There are several writeups on how to use javascript to add forms dynamically to a Django formset. For example this or this. I just learned about htmx. How can I add forms dynamically to a Django formset using htmx instead of hand-coded javascript? I thought maybe I could use click-to-load, but it seems odd to call back to the server to get an empty row. Maybe this just isn't an htmx thing. -
Heroku Build succeeded but “application error”
I'm trying to deploy a django application on Heroku. The heroku build succeeded but I have the "application error" when I go to my web site URL host. I don't where I can find a solution, Could you please give me some help ? Here is the build log : -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.8.9 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.8.6 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting dj-database-url==0.5.0 Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) Collecting Django==3.1.7 Downloading Django-3.1.7-py3-none-any.whl (7.8 MB) Collecting gunicorn==20.1.0 Downloading gunicorn-20.1.0.tar.gz (370 kB) Collecting psycopg2-binary==2.8.6 Downloading psycopg2_binary-2.8.6-cp38-cp38-manylinux1_x86_64.whl (3.0 MB) Collecting whitenoise==5.2.0 Downloading whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Collecting asgiref<4,>=3.2.10 Downloading asgiref-3.3.4-py3-none-any.whl (22 kB) Collecting sqlparse>=0.2.2 Downloading sqlparse-0.4.1-py3-none-any.whl (42 kB) Collecting pytz Downloading pytz-2021.1-py2.py3-none-any.whl (510 kB) Building wheels for collected packages: gunicorn Building wheel for gunicorn (setup.py): started Building wheel for gunicorn (setup.py): finished with status 'done' Created wheel for gunicorn: filename=gunicorn-20.1.0-py3-none-any.whl size=78917 sha256=6781fff294c8bda3c2eda9afb07e9359bd87e521eb8b3dbc744ece40c3d69fc1 Stored in directory: /tmp/pip-ephem-wheel-cache-tmd9budj/wheels/21/4b/32/9be8daf8a4d73da26e4dba66c47c9b4b7d838a6b372981a3ed Successfully built gunicorn Installing collected packages: dj-database-url, asgiref, sqlparse, pytz, Django, gunicorn, … -
Django app accessing WooCommerce database - how to follow coupon to order relationship in the template
I am developing a Django application which provides read-only access to a WordPress WooCommerce database. I have created a view where I would like to show a list of WooCommerce coupons and any related order data where the coupon was used. The relation between a coupon and the order it was used in is in the table WpWcOrderCouponLookup, and I am passing the contents of this table by adding it as an additional parameter in get_context_data. What I can't figure out is how to access a specific record in the WpWcOrderCouponLookup structure from inside the template. I'll include my code below. Since I am using an existing Wordpress database, my models came from an inspectdb command, and I modified the output to include what I hope are the correct foreign key relations. This is the relevant model code: class WpPosts(models.Model): id = models.BigAutoField(db_column='ID', primary_key=True) # Field name made lowercase. post_author = models.PositiveBigIntegerField() post_date = models.DateTimeField() post_date_gmt = models.DateTimeField() post_content = models.TextField() post_title = models.TextField() post_excerpt = models.TextField() post_status = models.CharField(max_length=20) comment_status = models.CharField(max_length=20) ping_status = models.CharField(max_length=20) post_password = models.CharField(max_length=255) post_name = models.CharField(max_length=200) to_ping = models.TextField() pinged = models.TextField() post_modified = models.DateTimeField() post_modified_gmt = models.DateTimeField() post_content_filtered = models.TextField() post_parent = models.PositiveBigIntegerField() … -
Cannot run django migrations
I have a mysql database. On this database, I have tried to create an account and then grant that account permissions to create a test database and standard database. To look at permissions, I use the following: SHOW GRANTS FOR 'broker_admin'@'localhost'; This then produces an output similar to: 'GRANT USAGE ON *.* TO 'broker_admin'@'localhost' 'GRANT ALL PRIVILEGES ON `dbbrokerdata`.`dbbrokerdata` TO 'broker_admin'@'localhost' 'GRANT ALL PRIVILEGES ON `test_dbbrokerdata`.`test_dbbrokerdata` TO 'broker_admin'@'localhost' When I try to run the django app that uses this database, I get the following errors: django.db.utils.OperationalError: (1142, "CREATE command denied to user 'broker_admin'@'localhost' for table 'django_migrations'") django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'broker_admin'@'localhost' for table 'django_migrations'")) Watching for file changes with StatReloader Performing system checks... What do I need to do to the user permissions to get django migrations to work properly ?