Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What environment variables do I need to include in a bash script in order to run a Django migration?
I'm running Python 3.7, Django 2, on Mac OS X. When I run the following commands from the command line, they work seamlessly ... localhost:web davea$ source ./venv/bin/activate (venv) localhost:web davea$ python manage.py migrate maps System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.0/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: maps Running migrations: No migrations to apply. However, when I create a bash script containing the commands !#/bin/bash source ./venv/bin/activate python manage.py migrate maps The script dies localhost:web davea$ sh test.sh test.sh: line 1: !#/bin/bash: No such file or directory Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File … -
Python, Django3 error 'QuerySet' object has no attribute 'patterns'
I am very new in Python and Django. I have problem with request in my app. I want to get the value for pattern in part model (reletionship M2M) And i have django error: 'QuerySet' object has no attribute 'patterns' What is the error and how to fix it? Thanks for help Models.py from django.db import models class Pattern(models.Model): patternName = models.CharField(max_length=64) def __str__(self): return self.patternName class Part(models.Model): unitsList = ( ('szt', "szt"), ('m', "m"), ('komp', "komp") ) partName = models.CharField(unique=False, max_length=128) code = models.CharField(unique=True, max_length=15) units = models.CharField(max_length=10, choices=unitsList, default='szt') description = models.TextField() pattern = models.ManyToManyField(Pattern, related_name='patterns) def __str__(self): return self.partName views.py from django.shortcuts import render, from .models import Part, Pattern def partList(request): allParts = Part.objects.all() allPatterns = allParts.patterns.objects.all() return render(request, 'partList.html', {'parts': allParts, 'patterns': allPatterns}) partList.html {% for part in parts %} <tr> <td>{{part.partName}}</td> <td>{{part.code}}</td> <td>{{part.units}}</td> <td>{{part.description}}</td> <td>{{part.producer}}</td> <td>{{part.pattern}} </td> <td> <!-- <a href="../editPart/{{part.id}}">EDYTUJ</a> <a href="../deletePart/{{part.id}}">USUN</a> --> <a href="{% url 'editPart' part.id %}">EDYTUJ</a> <a href="{% url 'deletePart' part.id %}">USUN</a> </td> </tr> {% endfor %} -
How to keep the page paginated using django-filters when no filter is applied?
I'm using django-filters to filter categories and price. My problem is that, when I'm filtering results, it's paginated, but when there are no filters applied, there is no pagination. How can I add pagination when there are no filters applied? Thanks in advance! My filters.py: import django_filters from .models import Item class ItemFilter(django_filters.FilterSet): class Meta: model = Item fields = { 'category': ['exact'], 'price': ['lte'] } My views.py: class homeview(ListView): model = Item template_name = 'products/home.html' paginate_by = 8 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = ItemFilter(self.request.GET, queryset=self.get_queryset()) return context My home.html: <div class="card"> <div class="card-body"> <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button type="submit" class="btn btn-primary mt-4">Filter</button> </form> </div> </div> </div> <h1 class="mb-4">List Of Items</h1> <div class="row"> {% for item in filter.qs %} .... {% endfor %} -
Django Testing Package Installed by PIP Locally
When developing in Django, we can use the following command (or its variations) to run tests on all the apps written by us: python manage.py test. This will make Django look for test directories, as well as files with names along the lines of test_*. What I am wondering about is whether there is a way to include into the testing a package that was installed via pip install -e /path/to/package/here. I am trying to do this because I want to change some code in this package to make it compatible with a latter Django version. The package does have unit-tests in the test directory. However, it seems that it needs a virtual environment with Django to run those tests. Upon creating one, it is discovered that one needs to set up a project with settings to get it to work. Hence, my thought was: if we already have a project that is using this package, can we not run its tests from the project itself? If there is a better way of doing it, I am happy to hear it. -
access cpanel Database from my django website
so i am building a custom dashboard for my clients (using Django) whose websites are hosted using cpanel. i wanted to access their databases from my django app. is this possible in the first place? and if yes where do i start? -
Nuxtjs authentification
Does Google auth via gmail somehow relate to back end in nuxt js? I mean , when we work with tokens. After logging in , should I send the token to back end or nuxt js tackles it instead? -
Post button isn't adding the data to the back end database
I want the user to be able to add comments to the posts. I can add comments on the back end, I am having issues allowing users to add them via the front end. When I click Post, I want the comment to be added to the back end. And I want the page the user is currently on to be refreshed. Unfortunately the comments are not currently being added to the back end. And I am being directed to http://localhost:8000/your-name/. I made a page on my site called your-name as a test. And once I did this, the test page did load. But the comments were still not being added to the back end. The comments have a many to one relationship with the posts. Each comment can only have one post linked to it. Each post can have many comments linked to it. I think one problem is that the posts have individual URLs. But the comments don't have their own URLs. When I refresh the page, I need to take the URL of the active post. I tried doing comment_form.save(commit=True). I wanted to see if I could get any thing (valid or invalid data) to be added … -
Event listener from js static file pointing to incorrect path in Django
This is the first time I am trying to integrate front-end with backend in Django. I currently have the following file structure: my_project | +-- my_app | | | +-- ... | +-- static | | | | | +--my_app | | | +--app.js | | | +--style.css | | | +--back.png | | | +--dice-1.png | | | +--dice-2.png | | | +--dice-3.png | | | +--dice-4.png | | | +--dice-5.png | | | +--dice-6.png | +-- templates | | | | | +--my_app | | | +--index.html | | +-- manage.py The problem is my css file from my_app/static is loading just fine - including the initial image file on the page, but when I try doing a click event on the app.js file to load an image from the static folder, i am getting an error on the console: GET http://localhost:8000/js_dom/dice-1.png 404 (Not Found) From my js file: // setter: change dice img var diceDOM = document.querySelector('.dice'); // select dice DOM diceDOM.src = `dice-${dice}.png`; // use correct png based on roll <-- this is where I am getting the error }); The initial image loads from my html file: <img src="{% static 'js_dom/dice-5.png' %}" alt="Dice" class="dice"> And … -
Django: widthratio but in views.py
In my template I have the following code which multiplies data.quantity with data.price. {% widthratio data.quantity 1 data.price as foo %} {% if foo > "10000" %} <td>{{ foo }} test1</td> {% else %} <td>{{ foo }} test2</td> {% endif %} I would like to use something similar in my views.py since I want to create a filter for my queryset, is there some smooth solution for this such as widthratio in the templates? -
Django import export - How to skip the new rows, and only update the existed ones
When importing a file I want to skip all of the new rows that exists, and only update and change the ones that already exists, I've been trying for days to solve this problem, any ideas will help. also the file type is ".xls" or ".xlsx" here's my code: models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True, on_delete=models.CASCADE) author_email = models.EmailField('Author email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.DateField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) def __str__(self): return self.name admin.py: class BookResource(resources.ModelResource): class Meta: model = Book import_id_field = 'id' import_id_fields = ('id',) fields = ('id', 'name', 'price',) skip_unchanged = True report_skipped = True dry_run = True class CustomBookAdmin(ImportMixin, admin.ModelAdmin): resource_class = BookResource # tried to override it like so but it didn't work def skip_row(self, instance, original): original_id_value = getattr(original, self._meta.import_id_field) instance_id_value = getattr(instance, self._meta.import_id_field) if original_id_value != instance_id_value: return True if not self._meta.skip_unchanged: return False for field in self.get_fields(): try: if list(field.get_value(instance).all()) != list(field.get_value(original).all()): return False except AttributeError: if field.get_value(instance) != field.get_value(original): return False return True -
Django - The current path did not match any of url pattern
Getting Request URL: http://127.0.0.1:8000/picture/7/pic/31/delete/None instead of http://127.0.0.1:8000/picture/7/pic/31/delete/ Why it's adding /None at the end? #html action="{% url 'picture:item-delete' pic.album_id pic.pk %}" #views.py class ItemDelete(DeleteView): model = Pic def get_success_url(self): reverse_lazy('picture:detail', kwargs={'pk': self.object.album_id}) #urls.py urlpatterns = [ # /picture/<album_id>/pic/<pic_id>/delete/ url(r'^(?P<id>[0-9]+)/pic/(?P<pk>[0-9]+)/delete/$', views.ItemDelete.as_view(), name='item-delete'), ] Though, it deleted the model(pic). -
Django Form Validation not working on a field
I am doing a simple form validation. But not sure where i'm missing. Here I have put a validation of the field company_name which will validate if my company name is equal to "BFR". However I am not getting any validationerror after submitting the form. Could you please help me on this? forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Button from django.forms import ValidationError from .models import Company class CompanyForm(forms.ModelForm): compname = forms.CharField(label='Name : ', required=True) class Meta: model = Company fields = ['compname'] labels = { 'compname': 'Name : ', } def clean_compname(self): company_name = self.clean_data.get('compname') if (company_name == "BFR"): raise forms.ValidationError('company name cant be empty') return company_name def __init__(self, *args, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs['autocomplete'] = 'off' self.helper.layout = Layout( 'compname', Submit('save', 'Save changes'), Button('Reset', 'Reset', css_class='btn btn-info'), Button('cancel', 'Cancel' , css_class='btn btn-secondary'), ) models.py from django.db import models # Create your models here. class Company(models.Model): compname = models.CharField(max_length=20) def __str__(self): return self.compname views.py from django.shortcuts import render from django.contrib import messages from .forms import CompanyForm from .models import Company def company_form(request, id=0): if request.method == 'GET': if id == 0: form = CompanyForm() else: company = Company.objects.get(pk=id) … -
Custom Django Password Reset - Link does not get invalidated
I know that the one time link for the password reset should be invalidated following the email password change procedure as given here enter link description here. Yet, with my below implementation, although the link can reset the password each time, it does not get invalidated. The link works each time. What could be the reason for this ? (I also see the last login timestamp is also updated in admin pages for the particular user that I am changing the password for) (forms.py) from django.contrib.auth.forms import UserCreationForm, SetPasswordForm from django.contrib.auth import get_user_model class ResetPasswordForm(SetPasswordForm): class Meta: model = get_user_model() fields = ('password1', 'password2') (tokens.py) from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() (views.py) def activate_forgot_password(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = get_user_model() user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): if request.method == 'POST': form = ResetPasswordForm(user, request.POST) if form.is_valid(): user = form.save(commit=False) print(user.password) user.save() login(request, user, backend='mysite.signup.views.EmailBackend') return redirect('home') else: form = ResetPasswordForm(user) return render(request, 'change_password.html', {'form': form, 'uidb64': uidb64, 'token': token}) return render(request, 'account_forgot_password_token_invalid.html') (template.html) <form id="ResetPasswordForm" method="post" action="{% … -
Django save_to_database() when the model is a temp table?
I have a view where I let the users upload xls, xlsx and csv files. My users will upload 3 types of data in every month, but their dataset has to be validated first, so I want to load the data from the Excel files to temp tables first. It is working very well until I have to load the data from the Excel files to the temp tables. Django's save_to_database method requires a model, which I do not have for temp tables. Is there any way I can use save_to_database with temp tables? It is really easy to use with different excel formats. In my code I pass a string to the model, I know it is not going to work, but I wanted to show what I need exactly.I am using SQL Server. My view: def submission_upload(request): if request.method == "POST": form = uploadForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data submission_type = cd["submission_type"] #this should be done with session variables username = request.META["USERNAME"] currentUser = User() entity_id = re.search("[0-9]+", str(currentUser.get_entity_id(username))).group() #creating the tmp_table based on the given info cursor = connection.cursor() strTable = "[SCLR].[webtmp_" + entity_id + "_" + submission_type +"]" queryString = "IF OBJECT_ID('" + strTable + … -
Import error: No module named 'secrets' - python manage.py not working after pull to Digital Ocean
I'm following along a course - Django development to deployment. After pulling it to Digital Ocean everything else ran smoothly. Until I tried running python manage.py help (env) djangoadmin@ubuntu-1:~/pyapps/btre_project_4$ python manage.py help and I get this error. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/__init__.py", line 16, in setup from django.urls import set_script_prefix File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/urls/__init__.py", line 1, in <module> from .base import ( File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/urls/base.py", line 9, in <module> from .exceptions import NoReverseMatch, Resolver404 File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/urls/exceptions.py", line 1, in <module> from django.http import Http404 File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/http/__init__.py", line 2, in <module> from django.http.request import ( File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/http/request.py", line 10, in <module> from django.core import signing File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/core/signing.py", line 45, in <module> from django.utils.crypto import constant_time_compare, salted_hmac File "/home/djangoadmin/pyapps/env/lib/python3.5/site-packages/django/utils/crypto.py", line 6, in <module> import secrets ImportError: No module named 'secrets' I'm a newbie and have been stuck on this for a while. I just want to know what could possibly cause this. -
Django, Celery - How can I run a task for every 45 days at a particular time
I need to run a task every 45 days at a particular time using Celery. I tried using "time delta" of python DateTime library as follows but I can't specify a particular time. Can anyone help me on this, please? app.conf.beat_schedule = { 'add-every-45-days': { 'task': 'tasks.add', 'schedule': timedelta(days=45), }, } -
how to save locally made files to contenttype in django
File.objects.create(title=file_name, file=file_obj, content_object=task_obj, author=task_obj.client) i want save my file .txt type file here wich is file_obj but i am getting error. 'file' object has no attribute '_committed' while my above code working fine for request.FILES.getlist('files'). any help is much appreciated. -
Show related fields from different models in django admin
I have following 3 models in Django. We have multiple Grades. Each Grade has multiple subjects. Each subject has multiple lessons. class Grade(models.Model): name = models.CharField(max_length=100) class Subject(models.Model): grade = models.ForeignKey(Grade, on_delete=models.CASCADE, related_name='subject') class Lesson(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='lesson') In my admin console when I am trying to add a new Lesson , I only see a Subject dropdown. Multiple grades can have the same subject name. eg: grade 1 has subject english and grade 2 has subject english. Hence I would like to see both grade & subject dropdown in my Lesson model in admin console. Thanks -
Onload function not triggered from js file
When I run window.onload function from .js file, the function is not triggered. <script type="text/javascript" src="{% static 'jscode.js' %}"></script> window.onload = function() { alert('Page is loaded'); }; However, onload is working as expected when put along a seperate script tag or into body onload <script type="text/javascript"> window.onload = function() { alert('Page is loaded'); }; </script> <script type="text/javascript" src="{% static 'jscode.js' %}"></script> In my jscode.js are other functions that work fine except for triggering the onload. I tired jQuery code, js code etc. Only putting the scrpit tag in html line seems to be working but it is not what I tend to achieve. Is there something I am missing for the onload to trigger? I use django to create my website. -
Django: Display thumbnail image in jQuery DataTables, Class based ListView
I'd like to display a thumbnail image in a jQuery DataTables. Research(1) shows that a js render function needs to be added to the .DataTable settings: table_settings.js $('#imagetable').DataTable({ 'render': function (data, type, full, meta) { return '<img src="'+data+'" style="height:100px;width:100px;"/>';} }); I'd like to implement above in a standard base case, using Django, class based ListView. models.py class ProductImage(models.Model): product_image_name = models.CharField(max_length=20) product_image_description = models.TextField(max_length=255, null=True) product_image = models.ImageField(default='product_image/default.jpg', upload_to='product_image') views.py class ImageListView(ListView): model = ProductImage template_name = 'product/image_list.html' table element (within image_list.html) <table id="imagetable"> <thead> <tr> <th>Name</th> <th>Description</th> <th>Image</th> </tr> </thead> <tbody> {% for object in object_list %} <tr> <td> {{ object.product_image_name }} </td> <td> {{ object.product_image_description }} </td> <td> {{ object.product_image }} </td> </tr> {% endfor %} </tbody> </table> Above does not work as intended (to display a picture), however, it shows the link: product_image/product92839_EWkQvy2.jpg. I assume I would need to tell $('#imagetable') more information, such as where are the images stored (i.e. define the var data). As I am starting out in jQuery, I'd appreciate a hand showing how to communicate from server side to front in this example using class based ListView (if possible). -
How to use a Django search view with a Select2 multiselect that shows GET values with a + operator in-between
I currently have a working search view built with Django and a Select2 multiselect on the front end. When the form is submitted I get ?Query=Value1 in the URL which works fine, it searches my model and I get the desired result. The problem is when multiple values are selected. I get this in the URL ?Query=value1&Query=Value2. In this scenario, it's only the last value that is searched. What I want to happen is that both values are searched (with the equivalent of an AND operator in-between). I've added the search form and Django search view below. If you need anything else let me now. Search form on the front end <form id="makeitso" role="search" action="" method="get"> <select class="js-example-placeholder-multiple" name="query" multiple="multiple"> <option value="Value 1">Value 1</option> <option value="Value 2">Value 2</option> <option value="Value 3">Value 3</option> </select> <script> $(".js-example-placeholder-multiple").select2({ placeholder: "Search here", }); </script> <div class="form-inline justify-content-center"> <button type="submit" class="btn btn-xlarge">Search</button> </div> </form> views.py def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = TestPage.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = TestPage.objects.none() # Pagination paginator = Paginator(search_results, 3) try: search_results = paginator.page(page) except PageNotAnInteger: search_results = paginator.page(1) except EmptyPage: search_results = paginator.page(paginator.num_pages) return render(request, … -
"version `GLIBCXX_3.4.26' not found" error running gdal in anaconda env
I've been relocating a geodjango project from Ubuntu 16.04 to 20.04, creating a conda env from a yml file, running the server I got this error version `GLIBCXX_3.4.26' not found (required by /lib/libgdal.so.26) from other posts I got to check the following: I ran strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIBCXX and got: GLIBCXX_3.4 GLIBCXX_3.4.1 GLIBCXX_3.4.2 GLIBCXX_3.4.3 GLIBCXX_3.4.4 GLIBCXX_3.4.5 GLIBCXX_3.4.6 GLIBCXX_3.4.7 GLIBCXX_3.4.8 GLIBCXX_3.4.9 GLIBCXX_3.4.10 GLIBCXX_3.4.11 GLIBCXX_3.4.12 GLIBCXX_3.4.13 GLIBCXX_3.4.14 GLIBCXX_3.4.15 GLIBCXX_3.4.16 GLIBCXX_3.4.17 GLIBCXX_3.4.18 GLIBCXX_3.4.19 GLIBCXX_3.4.20 GLIBCXX_3.4.21 GLIBCXX_3.4.22 GLIBCXX_3.4.23 GLIBCXX_3.4.24 GLIBCXX_3.4.25 GLIBCXX_3.4.26 GLIBCXX_3.4.27 GLIBCXX_3.4.28 GLIBCXX_DEBUG_MESSAGE_LENGTH so the version required IS installed running locate libstdc++.so.6 i got: /home/fcr/anaconda3/envs/fcr/lib/libstdc++.so.6 /home/fcr/anaconda3/envs/fcr/lib/libstdc++.so.6.0.25 /home/fcr/anaconda3/envs/fcr/x86_64-conda_cos6-linux-gnu/sysroot/lib/libstdc++.so.6 /home/fcr/anaconda3/envs/fcr/x86_64-conda_cos6-linux-gnu/sysroot/lib/libstdc++.so.6.0.25 /home/fcr/anaconda3/lib/libstdc++.so.6 /home/fcr/anaconda3/lib/libstdc++.so.6.0.26 /home/fcr/anaconda3/pkgs/libstdcxx-ng-8.2.0-hdf63c60_1/lib/libstdc++.so.6 /home/fcr/anaconda3/pkgs/libstdcxx-ng-8.2.0-hdf63c60_1/lib/libstdc++.so.6.0.25 /home/fcr/anaconda3/pkgs/libstdcxx-ng-8.2.0-hdf63c60_1/x86_64-conda_cos6-linux-gnu/sysroot /lib/libstdc++.so.6 /home/fcr/anaconda3/pkgs/libstdcxx-ng-8.2.0-hdf63c60_1/x86_64-conda_cos6-linux-gnu/sysroot /lib/libstdc++.so.6.0.25 /home/fcr/anaconda3/pkgs/libstdcxx-ng-9.1.0-hdf63c60_0/lib/libstdc++.so.6 /home/fcr/anaconda3/pkgs/libstdcxx-ng-9.1.0-hdf63c60_0/lib/libstdc++.so.6.0.26 /home/fcr/anaconda3/pkgs/libstdcxx-ng-9.1.0-hdf63c60_0/x86_64-conda_cos6-linux-gnu/sysroot/lib/libstdc++.so.6 /home/fcr/anaconda3/pkgs/libstdcxx-ng-9.1.0-hdf63c60_0/x86_64-conda_cos6-linux-gnu/sysroot/lib/libstdc++.so.6.0.26 /home/fcr/anaconda3/x86_64-conda_cos6-linux-gnu/sysroot/lib/libstdc++.so.6 /home/fcr/anaconda3/x86_64-conda_cos6-linux-gnu/sysroot/lib/libstdc++.so.6.0.26 /snap/core/9066/usr/lib/x86_64-linux-gnu/libstdc++.so.6 /snap/core/9066/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21 /snap/core/9066/usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21-gdb.py /snap/core18/1705/usr/lib/x86_64-linux-gnu/libstdc++.so.6 /snap/core18/1705/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25 /snap/core18/1705/usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25- gdb.py /snap/core18/1754/usr/lib/x86_64-linux-gnu/libstdc++.so.6 /snap/core18/1754/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25 /snap/core18/1754/usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25-gdb.py /snap/vlc/1620/usr/lib/x86_64-linux-gnu/libstdc++.so.6 /snap/wine-platform-runtime/123/usr/lib/i386-linux-gnu/libstdc++.so.6 /snap/wine-platform-runtime/123/usr/lib/i386-linux-gnu/libstdc++.so.6.0.25 /snap/wine-platform-runtime/123/usr/share/gdb/auto-load/usr/lib/i386-linux-gnu/libstdc++.so.6.0.25-gdb.py /usr/lib/x86_64-linux-gnu/libstdc++.so.6 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28 /usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28-gdb.py is there too many installations of the compiler?, how can I get around this? thanks -
How to remove an operational error in Django?
I am trying to develop my first website(more specifically, an e-commerce site) with the help of a beginners' tutorial. Adding all the required fields, I tried to save the details for the first product. After this I received the operational error as EXCEPTION TYPE and no such table : main.auth_user__old as Exception value. I am providing the exact syntax below (not the traceback though, if someone needs to check it, pls let me know):- OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\RITAJA\PycharmProjects\P1\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\RITAJA\PycharmProjects\P1\venv\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\RITAJA\PycharmProjects\P1', 'C:\Users\RITAJA\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\RITAJA\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\RITAJA\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\RITAJA\AppData\Local\Programs\Python\Python38-32', 'C:\Users\RITAJA\PycharmProjects\P1\venv', 'C:\Users\RITAJA\PycharmProjects\P1\venv\lib\site-packages', 'C:\Users\RITAJA\PycharmProjects\P1\venv\lib\site-packages\setuptools-40.8.0-py3.8.egg', 'C:\Users\RITAJA\PycharmProjects\P1\venv\lib\site-packages\pip-19.0.3-py3.8.egg'] Server time: Fri, 1 May 2020 16:23:28 +0000 -
How to fix get() returned more than one Order -- it returned 2
I have a project with courses, and tried to add payment system to that, did everything for that and when i am adding more that one course to the cart(doesn't matter same course or not) i get this error get() returned more than one Order -- it returned 2! It's really strange because i did this system it previous projects and everything worked, but now i am getting that. Maybe problem is I created custom user and did two types of users, but i am not sure in that and also I tried to change tutor and students(Course) connection from foreign key to the one to one field but there I get a lot of other errors, and also in cart view changed get to the filter and error has gone, but I didn't see any orders in the cart. How to fix this error? models class Course(models.Model): title = models.CharField(max_length=255) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE) students = models.ForeignKey(User,related_name='course_students',blank=True,null=True,on_delete=models.CASCADE) class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) courses = models.ManyToManyField(OrderCourse) ordered = models.BooleanField(default=False) class OrderCourse(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) ordered = models.BooleanField(default=False) course = models.ForeignKey(Course,on_delete=models.CASCADE) views def add_to_cart(request,pk): course = get_object_or_404(Course,pk=pk) order_course,created = OrderCourse.objects.get_or_create( course=course, user=request.user, ordered = False, ) ordered_date = timezone.now() order = Order.objects.create(user=request.user,ordered_date=ordered_date) … -
Pytest assertion error in django rest framework
my model like this class Appeal(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) other_category = models.CharField(max_length=500, null=True, blank=True) file = models.FileField(upload_to='appeals/', null=True) short_name = models.CharField(max_length=100) appeal_desc = models.TextField() state = models.IntegerField(choices=STATUS, default=NEW) dept = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True) location = models.PointField(srid=4326, null=True) address = models.CharField(max_length=255) history = HistoricalRecords() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) I am going to test this model but I am failing I do not know where I am making a mistake pytest only gives an error like this > assert appeal_res.status_code == status.HTTP_201_CREATED E AssertionError: assert 400 == 201 E +400 E -201 my whole test here class AppealTestCase(APITestCase): client = APIClient() def post_appeal(self, short_name, appeal_desc, address, location, category): url = reverse('appeal-create') data = {'short_name': short_name, 'appeal_desc': appeal_desc, 'address': address, 'location': location, 'category_id': category} response = self.client.post(url, data, format='json') return response def create_user_set_token(self): user = User.objects.create_user(username='test', password='test2020') token = Token.objects.create(user=user) self.client.credentials(HTTP_AUTHORIZATION='Token {0}'.format(token.key)) def test_post_and_get_appeal(self): self.create_user_set_token() category = Category.objects.create(name='Test Category').id print(category) short_name = 'bla bla' desc = 'test desc' location = 'SRID=4326;POINT (1.406108835239464 17.66601562254118)' address = 'test address' appeal_res = self.post_appeal(short_name, desc, address, location, category) assert appeal_res.status_code == status.HTTP_201_CREATED Here What I have tried so far. If anybody know please, help me on this issue, with or without Category model …