Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Framework - API Authentication - Authorize Apps instead of Users
Being new to Django, i was wondering if there's a "fast" and "elegant" way to replace the default model against which Django creates access tokens for API authentication ? I use plugins like "django-rest-framework-simplejwt", and by default they work only with the user model. The point is to let users create apps, and each app has its own API access and refresh tokens ! Thank you. -
heroku h13 error code when using postgresql
Problem I have a Django app that I host on heroku. It's not the first that I do, so much so that I pretty much use the same config for the 4 apps that I have hosted there. However, I have a problem with the latest one, when I deploy with the default sqlite3 setup, everything works as it should, but if I use the prod settings that I usually use on my other projects, it crashes and I get an H13 error code. What I tried I obviously tried the server settings locally, and everything works as it should. I couldn't test directly with gunicorn however, and I'm wondering if there is a problem there. I tried removing the heroku settings, hardcoding the env variables (in case I miss-typed). The code I'll add some code if needed, but basically when I replace this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USR'), 'PASSWORD': os.environ.get('DB_PWD'), 'HOST': os.environ.get('DB_IP'), 'PORT': os.environ.get('DB_PORT'), 'OPTIONS': {'sslmode': 'require', }, } } by this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } it works. Just that I can't run with that in production, especially on Heroku. I have three settings files, a … -
Django-Select2 Heavy Widget
I was trying to implement Django-select2 for the first time.... I referred their documentation and some of the stack overflow solutions to implement it.... I managed to get ajax functionality work properly, also i am able to select multiple choices... however when I submit and validate the form, I am getting error like -> "Select a valid choice. 34425 is not one of the available choices." I am not understanding what I am doing wrong.... here is my form. class MyCustReqForm(forms.ModelForm): initial_customer = forms.MultipleChoiceField( widget=HeavySelect2MultipleWidget(data_view='customer_ajax', attrs={'data-minimum-input-length': 4, 'delay':200}, model=Customer), ) end_customer = forms.MultipleChoiceField( widget=HeavySelect2MultipleWidget(data_view='customer_ajax', attrs={'data-minimum-input-length': 4, 'delay':200}, model=Customer), ) class Meta: model = Workflow_Customer fields = [ 'initial_customer', 'end_customer' ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['initial_customer'].widget.attrs.update({'style': 'width:100%', 'data-placeholder': 'Select Customer'}) self.fields['end_customer'].widget.attrs.update({'style':'width:100%', 'data-placeholder':'Select end customer'}) and customer_ajax view calls below function... def customer_select2(request): term = request.GET.get("term", None) if term: res = list(Customer.objects.filter(Q(customer_number__contains=term) | Q(customer_name__contains=term)).values('id', 'customer_number', 'customer_name'))[:10] if res: result = [{'id': value['id'], 'text': value['customer_number'] + ' ' + value['customer_name'] } for index, value in enumerate(res)] return JsonResponse({'err': 'nil', 'results': result}, safe=False) return JsonResponse(data={'success': False, 'errors': 'No mathing items found'}) I appreciate for the quick help... if possible, please provide one complete example which explains how form defined and view used … -
Django / Model image field asks for default image
I do not want to add default image for my model in Django. But when I delete default image from the model it says image attribute has no file associated with it. How should I fix it that it would not ask for the image when user does not add an image? class MainPost(models.Model): title = models.CharField(max_length = 50,verbose_name= ('Başlık')) content = models.TextField(verbose_name= ('Yazı')) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(default='profile_pics/default.jpg',upload_to = 'images',blank=True,null=True,verbose_name = ('Resim')) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def save(self,*args, **kwargs): super(MainPost,self).save(*args,**kwargs) img = Image.open(self.image.path) if img.height > 500 or img.width > 500: output_size = (500,500) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('comment', kwargs={'pk':self.pk}) -
CSRF verification failed. Request aborted. Even with {% crsf_token %}
I'm getting CSRF verification failed. Request aborted. after I try signing in, even though I've provided the {% csrf_token %} template tag. templates/registration/login.html {% extends "base.html" %} {% block content %} <div class="container"> <div class="card"> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success"><i class="fas fa-sign-in-alt"></i> Login</button> <input type="hidden" name="next" value="{{ next }}" /> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> </div> </div> {% endblock content %} -
How to call one serializer in another serializer and vice versa using serializers.Serializer in django rest framework?
I want to perform POST rest api call to validate my data in serializer. my JSON data is { "operator": { "type": "or", "query_list": [ { "operator": { "type": "inclusion", "query_list": [ { "operator": { "type": "or", "query_list": [ { "query": { "index": "test", "fields": [ { "field": "name" } ] } } ] } } ] } }] }, "group_by": "name", "severity": 100 } Using minimal serializers.Serializer how can I validate the same nested data? -
AttributeError: 'module' object has no attribute 'model' while model word is not written anywhere,
In djnago I have created Download model and it worked as expected but later when I tried to add new model 'Model' it just showing '''AttributeError: 'Music' object has no attribute 'model'''' . from django.db import models # Download/models.py. class Download(models.Model): name = models.CharField(max_length=50) discription = models.CharField(max_length=50) link = models.CharField(max_length=50) imgages = models.ImageField(upload_to='media/') def __str__(self): return self.name class Music(models.Model): title = models.CharField(max_length=50) def __str__(self): return self.name and here is an admin file from django.contrib import admin from .models import Download,Music # Register your models here. admin.site.register(Download,Music) -
HTML Page gets downloaded on link click
I have created a django web application were I have about 8 html pages. All the html pages seem to work fine, but on some local machines one of the pages gets downloaded upon clicking on the link. It worked fine in my machine. When I deployed it in a private server and tried to click on the same link online, it got downloaded instead of going to the actual page. In linux instead od downloading, it displays the html page. Can anyone tell me what the real issue is? My apologies as I can't post the html page due to issues associated with privacy. However can anyone tell me as to what might be the issue? In other posts I was told that if you'd clear the local machines browsing history this would solve it, but this is not the case when it's in the server. I need a permanent solution. Thanks in Advance -
Overriding Bulk Delete of Models in Django
I wrote a custom delete method for a model. It appears to work with two caveats. When I enter into the model instance inside the Django Admin and click delete, then the file is deleted from AWS S3 bucket (that was the purpose of overriding the method in the first place). The model itself gets removed as well. If I delete via "Delete Selected" bulk feature, then the file lingers in S3, but the instance gets removed from the list of instances of this type. It is my understanding that in the bulk delete, a different (queryset) method is invoked. My question is what is the most effective method of making both single and bulk deletes act the same? Should I be trying to create a custom manager for this model? The model declaration and delete method: from boto3.session import Session from django.conf import settings class Video(models.Model): title=models.CharField(max_length=500) description=models.TextField(default="") creation_date=models.DateTimeField(default=timezone.now) videofile=models.FileField(upload_to='videos/', null=True, verbose_name="") tags = TaggableManager() actions = ['delete'] def __str__(self): return self.title + ": " + str(self.videofile) def delete(self, *args, **kwargs): session = Session (settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) s3_resource = session.resource('s3') s3_bucket = s3_resource.Bucket(settings.AWS_STORAGE_BUCKET_NAME) file_path = "media/" + str(self.videofile) response = s3_bucket.delete_objects( Delete={ 'Objects': [ { 'Key': file_path } ] }) … -
Receiving a text file instead of html file In Django
I currently have a model named Order in models.py class Order(models.Model): order_item = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) order_name = models.CharField(max_length=200) def __str__(self): return self.order_name In the views.py file I have def ordering(request): latest_order = Order.objects.all() context = {'latest_order':latest_order} return render(request, 'users/ordering.html', {'title':'Ordering'}, context) I wanted to show the orders on the html page but all im getting back is a txt file Image of the html file Is there a better approach for me to keep track of a user's order? -
Json Post from Django to Camunda
Further to my earlier post yesterday: Post request to external Rest Service using Django - use returned json to update model I have managed to post data to camunda using Django - request.post. Using the following script: payload = "{\n \"businessKey\": \"SomeValue\",\n \"variables\": {\n \"Organisation_ID\": {\n \"value\": \"SOmeUUID\",\n \"type\": \"String\"\n },\n \"UserID\": {\n \"value\":\"Some User ID\",\n \"type\": \"String\"\n }\n }\n}" However when I start to use variables from the form and format my payload using class StartProcessView(View): template_name = 'startdeliveryphase.html' def get(self,request, *args, **kwargs): form = IntStartDeliveryPhase return render(request, self.template_name,{'form':form}) def post(self,request, *args, **kwargs): form = IntStartDeliveryPhase(request.POST or None) if form.is_valid(): data = form.cleaned_data OrganisationID = data['Form_Field_OrganisationID'] UserID = data['Form_Field_User_ID'] BusinessKey = data['Form_Field_Business_Key'] url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start" payload = {"businessKey":BusinessKey,"variables":[{"Organisation":[{"value":OrganisationID, "type":"String"}]},[{"Startedby":[{"value":UserID,"type":"String"}]}]]} headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data = payload) #print(repsonse.errors) print(response.text.encode('utf8')) return render(request) else: return render(request,self.template_name,{'form':form}) I get an error from the camunda engine:- b'{"type":"JsonParseException","message":"Unrecognized token \'businessKey\': was expecting (\'true\', \'false\' or \'null\')\\n at [Source: (org.camunda.bpm.engine.rest.filter.EmptyBodyFilter$1$1); line: 1, column: 13]"}' the local vars shows the following: ▼ Local vars Variable Value BusinessKey '1qaz' OrganisationID <Organisation: Some Local Authoristy> UserID <Actor_User: me@me.com> args () data {'Form_Field_Business_Key': '1qaz', 'Form_Field_CamundaInstanceID': 'sss', 'Form_Field_Camunda_HRef': 'ss', 'Form_Field_Camunda_TenantID': '22', 'Form_Field_DateCreated': datetime.datetime(2020, 4, … -
How can I retrieve an up-to-date reference to a many-to-many field in an object's save() method in django?
I have a model: class Camera(models.Model): users_allowed_to_view = models.ManyToManyField(User, ...) def save(self, *args, **kwargs): print(self.users_allowed_to_view.all()) super().save(*args, **kwargs) If I use Django Admin to modify a Camera, changing which list of users is allowed to view my camera, and hit Submit, the print statement above returns an old list of users (before the save currently in progress). Even if I move the print statement after super(), I still get an old list of users. Is there a way to get the new list of users that's about to be saved? Also, a related question - I'm pretty sure the .all() above does a DB query. Can I just get a list of IDs referenced by the field without doing a DB query, like you can for a ForeignKey field (by doing foreignkeyfield_id)? -
Django model testing
I want to create some tests in my app, but all the time i got some errors. Now i have information errors Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: setUpClass (comments.tests.test_models.ReplyCommentModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\madas\OneDrive\Pulpit\Code\git-projects\django_tutek\djangoenv\lib\site-packages\django\test\testcases.py", line 1137, in setUpClass cls.setUpTestData() ....... raise TypeError( TypeError: Tried to update field comments.ReplyComment.author_reply with a model instance, <User: >. Use a value compatible with CharField. ---------------------------------------------------------------------- Ran 2 tests in 0.170s FAILED (errors=1) Tests from django.test import TestCase from django.contrib.auth.models import User from blog.models import Post, get_default_user from comments.models import Comment, ReplyComment class CommentModelTest(TestCase): @classmethod def setUpTestData(cls): cls.user = User(first_name='adam', is_staff=True, is_active=True, is_superuser=True) cls.user.save() cls.post = Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) cls.post.save() cls.comment = Comment.objects.create(post=Post.objects.get(title='Pierwszy post'), author='robot', text='ok') cls.comment.save() def setUp(self): self.post = Post.objects.get(title='Pierwszy post') self.comment = Comment.objects.get(id=1) def test_str(self): self.assertEqual(self.comment.text, 'ok') def test_approve(self): self.assertFalse(self.comment.is_approved) self.comment.is_approved = True self.assertTrue(self.comment.is_approved) class ReplyCommentModelTest(TestCase): @classmethod def setUpTestData(cls): cls.user = User(first_name='adam', is_staff=True, is_active=True, is_superuser=True) cls.user.save() cls.post = Post.objects.create(field='Python', title='Pierwszy post', slug='pierwszy-post', status=1) cls.post.save() cls.comment = Comment.objects.create(post=Post.objects.get(title='Pierwszy post'), author='robot', text='ok') cls.comment.save() cls.reply_comment = ReplyComment.objects.create(comment_reply=Comment.objects.get(author='robot'), text_reply='not_ok') cls.reply_comment.save() def setUp(self): self.post = Post.objects.get(title='Pierwszy post') self.comment = Comment.objects.get(id=1) self.reply = ReplyComment.objects.get(id=1) def test_str(self): self.assertEqual(self.reply.text_reply, 'not ok') Models from django.db … -
Using Django to Query a SQL database
I am very new to Django, but just ran into an issue at work that hopefully we can use Django to resolve. Currently we have a outdated ticketing system that is using sql for the database. We are working on updating the ticketing system. When trying to import the data into the new system (same manufacture just newer system) it does not work. There Tech stated it is something with the way we set up our active directory. They said we can go forth with not updating it and start from scratch or call Microsoft on the issue. Would there be a way I can use Django to quary the ticketing systems database and pull the information to where I can display it using Django? -
Function 'doclist' has no 'filter' memberpylint(no-member)
It gives an error that Function 'doclist' has no 'filter' memberpylint(no-member) and please give suggestion if my code is correct related to search This Is My Model.py file class Document(models.Model): name = models.CharField(max_length=200) url = models.URLField(max_length=250) types = models.CharField(max_length=200) category = models.CharField(max_length=200) desc = models.TextField() upload = models.FileField(upload_to='documents') objects = models.Manager() class Meta: verbose_name_plural = "documents" def __str__(self): return self.name This is my View.py File def doclist(request): documents = Document.objects.filter() search_query = request.GET.get('q') if search_query : doclist = doclist.filter( Q(name__icontains = search_query) ) print(search_query) return render(request, 'doclist.html', { 'documents' : documents }) This is my Search Form <form method="GET" action="/doclist/"> {% csrf_token %} <div class="search-box"> <input type="text" class="search-txt" placeholder="Search Here" name="q" value="{{request.GET.q}}"> <button class="search-btn" type="submit" name="action"><i class="fas fa-search"></i></button> </form> -
Djano checking multiple variables in the view or the template?
I have site that the user selects a drop down menu item, inputs some JSON and then clicks "Parse". Then the JSON data is checked against certain properties based on the drop down menu item. Basically I have a list that looks like this.. myList = [{'Prop1': ['asdf', 'wefef']}, {'prop3': ['ss']}, {'prop2': ['d']}] This is all the data I am checking against. It is the property name and then a list of expected values for that property name. Then in the JSON I have to compare those properties against the JSON properties in the list above. Right now I am not sure where the best way to go about checking these. Should I do it in my views.py or should I do it in the page.html? Basically I will need to look through myList and check if that property is in the JSON. If so then I need to check it against the expected property. And then I need to print things in a row so that you can view the info like.. Property Excepted Value Actual Value P/F prop1 asdf, wefef apple F prop2 d d P prop3 ss sd F My issue is, this will be a bunch … -
How can I call a Django app from another Python app?
In the standard setup, Django applications are called by a WSGI server (like gunicorn and mod_wsgi) to answer HTTP requests, the entrypoint at user-level is the django View. Can I make a custom calling convention to call Django apps (a new entrypoint)? If so, How I properly load a Django app? -
Django, NoReverseMatch. What should I write in this code?
I have a problem: NoReverseMatch at /update-orders/12 Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\-orders/(?P[0-9]+)$'] Request Method: GET Request URL: http://192.168.0.249:8000/update-orders/12 Django Version: 3.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\-orders/(?P[0-9]+)$'] Exception Location: /root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 Python Executable: /root/.local/share/virtualenvs/myp4-4l8n6HJk/bin/python Python Version: 3.7.3 Python Path: ['/var/workspace/myp4/webprint', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages'] Why do I have this Error during template rendering? detail_order.html {% extends 'index.html' %} {% block content %} <p><a href="{% url 'orders' %}">Back</a></p> <h1>Заказ {{get_order.number_order}}</h1> <h2><a href="{% url 'update_order' get_order.id %}">Update</a></h2> views.py class UpdateOrderView(CustomSuccessMessageMixin, UpdateView): model = Order template_name = 'detail_order.html' form_class = OrderForm success_url = reverse_lazy('detail_order') success_msg = 'Ok' def get_context_data(self, **kwargs): kwargs['update'] = True return super().get_context_data(**kwargs) urls.py from django.contrib import admin from django.urls import path, include from .views import * from print import views urlpatterns = [ path('', views.home_page, name='index'), path('orders', views.OrderCreateView.as_view(), name='orders'), path('update-orders/<int:pk>', views.UpdateOrderView.as_view(), name='update_order'), # THIS PATH path('delete-orders/<int:pk>', views.DeleteOrderView.as_view(), name='delete_order'), path('detail-order/<int:pk>', views.DetailOrderView.as_view(), name='detail_order'), path('login', views.MyprojectLoginView.as_view(), name='login_page'), path('register', views.RegisterUserView.as_view(), name='register_page'), path('logout', views.MyprojectLogout.as_view(), name='logout_page'), ] -
Django REST framework TokenAuthentication - Unauthorized 401
I'm using axios to get data from Django server. getQuestionsPage(page) { return axios.get(`${API_URL}/questions/?page=${page}`, c.getHeaders).then(response => response.data); } getQuestionsURL(url) { return axios.get(url, c.getHeaders()).then(response => response.data); } Both URLs are the same, but when I getQuestionsPage(page) is called, the request is unauthorized. [23/Apr/2020 17:59:41] "GET /questions/?page=2 HTTP/1.1" 401 58 [23/Apr/2020 17:59:41] "GET /questions/?page=2 HTTP/1.1" 200 3489 How can I solve this problem? -
ChartJS : It's not showing in html on Django
I will plot horizontal bar chart in html but it's not showing. I send 2 variable from views.py are {{top5StockCode}} and {{top5TotalSales}}. The values of {{top5StockCode}} that views.py sent is ['23166', '21108', '85123A', '48185', '22470'] and {{top5TotalSales}} is [2671740, 227322, 171770, 158120, 143808]. This is my code in html file. <div class="top5"> <p class="topicTop5">Top 5 Selling Products</p> <canvas id="top5"></canvas> </div> <script> var top5 = document.getElementById('top5').getContext('2d'); var chart = new Chart(top5, { type: 'horizontalBar', data: { labels: {{top5StockCode}}, datasets: [{ label: 'Top 5 selling products ', backgroundColor: '#CE3B21', borderColor: 'rgb(255, 99, 132)', data: {{top5TotalSales}} }] }, options: { legend: { display: false }, responsive: true, maintainAspectRatio: false, scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); </script> I'm so confused why it's not showing graph. Please help me. Thank -
I'm getting django.db.utils.IntegrityError: FOREIGN KEY constraint failed in cmd
I copied a json file from online. I'm using it for django project in sublime text 3. I entered the following lines in cmd - >>> import json >>> from blog.models import Post >>> with open('posts.json') as f: ... posts_json=json.load(f) ... >>> for post in posts_json: ... post = Post(title=post['title'], content=post['content'], author_id=post[' user_id']) ... post.save() ... And the error I got was - Traceback (most recent call last): File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 3, in <module> File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 745, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 782, in save_base updated = self._save_table( File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 887, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields , raw) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\base.py", line 924, in _do_insert return manager._insert( File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\models\sql\compiler.py", line 1391, in execute_sql cursor.execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang o\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\Admin\.virtualenvs\my_projects-I2onQxk3\lib\site-packages\djang … -
CORS_ORIGIN_WHITELIST inside a environment file in django
I need to configure the whitelist for the CORS policy inside my django app. Instead of hardcode the urls inside settings.py, I'd like to put them inside a separate file, like the .env file from django-environ. This is my code: .env DEBUG=on SECRET_KEY='xxx' DATABASE_URL=psql://xxx CORS_ORIGIN_WHITELIST=http://127.0.0.1:4200 settings.py (MIDDLEWARE and INSTALLED_APPS are fine) ... environ.Env.read_env() ... CORS_ORIGIN_WHITELIST = env('CORS_ORIGIN_WHITELIST') I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/david/errepiu-project/backend/venv/lib/python3.7/site-packages/django/core/management/base.py", line 441, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '.' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. … -
Importing CSV file to MySQL table made in Django Models.py
I'm attempting to import a CSV file into a table in MySQL, the table being made in a Django models.py file and then migrated over. I am able to import CSV files into tables made in MySQL but when I attempt to import into the models.py made tables I get "0 records imported". Could someone help enlighten me to my mistakes? Relevant code and process screenshots below Models.py from django.db import models # Create your models here. class StudentDetails(models.Model): firstname = models.CharField(max_length=500) lastname = models.CharField(max_length=500) major = models.CharField(max_length=500) year = models.CharField(max_length=50) GPA = models.DecimalField(max_digits=3, decimal_places=3) class CourseDetails(models.Model): courseID = models.IntegerField() coursetitle = models.CharField(max_length=500, default="class") coursename = models.CharField(max_length=500) coursesectioncode = models.IntegerField(default="101") coursedept = models.CharField(max_length=500, default="college") courseinstructor = models.CharField(max_length=500, default="professor") Import process -
Django test does not add coverage with AssertRaises
There two lines that are not being executed by django tests when they are called as self.assertRaises. I am using: Python 3.6.9, Django 3, Coverage. I have this class: class AverageWeatherService: subclasses = WeatherService.__subclasses__() valid_services = { subclass.service_key: subclass for subclass in subclasses } @classmethod def _check_service(cls, one_service): if one_service not in cls.valid_services: logger.exception("Not valid service sent") raise NotValidWeatherFormException("Not valid service sent") And I have a local API that is up in my pc. Then I wrote this test: def test_integration_average_temp_services_error(self): self.assertRaises ( NotValidWeatherFormException, AverageWeatherService()._check_service, "MyFakeService", ) And although the test is successful with assert raises properly used this test is not adding coverage but If I call this method in a wrong way like this one: def test_integration_average_temp_services_error2(self): self.assertRaises ( NotValidWeatherFormException, AverageWeatherService()._check_service("MyFakeService") ) Then of course I get an error running the test because the exception is raised and not properly catched by assertRaises BUT It adds coverage. If I run this test wrongly I have my code 100% covered. If I use assertRaises as the first way these two lines are not being covered (According to coverage html). logger.exception("Not valid service sent") raise NotValidWeatherFormException("Not valid service sent") Also If I execute the method as the first way, the … -
after login through django social all_auth after redirect to webpage again webpage is refereshing when clicking on to it
i have used social django all_auth for login through gmail and it redirects to the page where i want but i am facing a problem after login through gmail it again refereshing the webpage and i want to perform two operations through textarea first it redirect me to gmail login after login when it returns back to the same page it takes input to it but whenever i click it refereshes the webpage and input not shows just bacause of that refereshing. here is myhtml code" <form id="new_user_form"> <a href="{% provider_login_url 'google'%}"> <textarea style=" width: 500px; border: 2px solid #333; padding: 15px 10px;"placeholder="Add Your Comment"></textarea></a>