Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass file path which is in the Docker volume?
Currently I am using Django + Nginx + Gunicorn + Docker. My app receives a file from post request, saves it in media volume in Docker and processes it. So to process that file I have to pass the file path to some function. How can I do that? -
django-tenant-schemas with django cookiecutter
I have used Django Cookie cutter in order to generate the project. Now I want to use the Django-tenant-schemas app to achieve multi-tenancy in my app. I haven't migrated yet and once I try to do migration using migrate_schemas --shared the error says that django.db.utils.ProgrammingError: relation "users_user" does not exist. Django cookiecutter creates a migration file in the user's model during the creation of the Project, How can I fix this? -
lightgallery is not working in django its shows black screen
The lightgallery is working but with one big issue with it. it is not shown the image where it shows that in the thumbnail but the main window it is black. The lightgallery is working but with one big issue with it. it is not shown the image where it shows that in the thumbnail but the main window it is black. enter image description here $(document).ready(function() { $('#lightgallery').lightGallery({ mode: 'slide', download: false, }); }); {% extends "keeraapp/base.html" %} {% load static %} {% block title %}{{ object.topic }}{% endblock %} {% block content %} <script src="{% static 'keeraapp/javascript/jquery.min.js' %}"></script> <script src="{% static 'keeraapp/javascript/gallery.js' %}"></script> <script src="{% static 'keeraapp/javascript/lightgallery.min.js' %}"></script> <script src="{% static 'keeraapp/javascript/picturefill.min.js' %}"></script> <script src="{% static 'keeraapp/javascript/lg-thumbnail.min.js' %}"></script> <script src="{% static 'keeraapp/javascript/lg-fullscreen.min.js' %}"></script> <script src="{% static 'keeraapp/javascript/DeletingConfirmation.js' %}"></script> <link rel="stylesheet" href="{% static 'keeraapp/css/lightgallery.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'keeraapp/css/one-topic.css' %}" type="text/css"> <input class="declare_checkbox" name="declare_checkbox" id="declare_checkbox" type="checkbox" value= "agree"> <label for="declare_checkbox"> <a class="declare-label">أتعهد بدفع قيمة خدمة هذا الموقع في حال تم التأجير وتقدر بـ 1% من السعر</a></label> <div class="inner-body" id="inner-body"> <P><center><b><h2>{{ object.topic }}</h2></b></center></P> <P><center><h5>{{ object.date }}</h5></center></P> <center><div class="warper-flex"> <div class="country">{{ object.country }}</div> <div class="city">{{ object.city }}</div> <div class="neighborhood">{{ object.neighborhood }}</div></br> <div class="category">{{ object.category }}</div> <div class="sub_category">{{ object.sub_category }}</div> … -
Display multiple polygon on Django admin
I have a model with a gis_models.GeometryField. class MyModel(django.db.models): area = gis_models.GeometryField(null=True, blank=True) I'm displaying this model on Django admin but i'm using https://github.com/makinacorpus/django-leaflet library. I already have 100+ rows in the database. when I open the admin page for any of those entries, I'm able to see a polygon being draw. that's perfect! take another case where I have to add a new polygon from the admin page. I am able to draw the map and save the entry. it works as expected. I can see the polygon on the map next time I open that entry on the map. the problem is when I add a new polygon I don't know what polygons are already there in the DB. so sometimes I add a new polygon that overlaps with existing ones. I was thinking of displaying all the available polygons on the map so that next time I add a new one I won't touch those points on the map. how can we display all the polygons (MultiPolygon) just for the /add/ page? -
Background image not found (404) in django
I intended to set a background image in the body of my HTML page and so I merrily tried following steps: Set STATIC_URL and STATIC_ROOT in the settings.py and pass the URL Patterns in the urls.py. Run static deployment python manage.py collectstatic Pass inline css in the body tag <body style="background-image: url('{% static '34.jpg' %}');"> into the base html file. but this all led me to this! GET http://localhost:7000/static/34.jpg 404 (Not Found) As usual below are my suspects/guilt-ridden files/codes for the case: 1. base.html <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>HR Suite</title> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script> <style> header { background-color: #4dacff; padding: 30px; text-align: center; font-size: 60px; color: white; } body { font-family: Arial, Helvetica, sans-serif; } </style> </head> <body style="background-image: url('{% static '34.jpg' %}');"> <header> <p>HR Suite</p> </header> <div class='row'> {% block content %} {% endblock %} </div> </body> </html> 2. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'uploads.core' ] ROOT_URLCONF = 'uploads.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Fill in missing data from Queryset Django
I've inherited a AngularJS / Django application using DjangoRestFramework and a Postgres DB which is being re-platformed from AngularJS to React / Redux. One of the things we're trying to do is present time series data using amCharts4. A problem (among many others) we're having is presenting data over a time range for which there may be no entries in the DB. For example, we have results which might look something like: [ { "date": "2020-01-16T00:00:00.000Z", "result": 3 }, { "date": "2020-01-18T00:00:00.000Z", "result": 2 } ] And would like them to look something like: [ { "date": "2020-01-16T00:00:00.000Z", "result": 3 }, { "date": "2020-01-17T00:00:00.000Z", "result": 0 }, { "date": "2020-01-18T00:00:00.000Z", "result": 2 } ] Additionally, we also have data with multiple data points per time event: [ { "date": "2020-01-13T00:00:00Z", "result": 1, "name": "Yes" }, { "date": "2020-01-14T00:00:00Z", "result": 1, "name": "No" }, { "date": "2020-01-16T00:00:00Z", "result": 1, "name": "No" } ] And would like the data filled in with 0's for any name on any date where there isn't a result: [ { "date": "2020-01-13T00:00:00Z", "result": 1, "name": "Yes" }, { "date": "2020-01-13T00:00:00Z", "result": 0, "name": "No" }, { "date": "2020-01-14T00:00:00Z", "result": 0, "name": "Yes" }, { "date": "2020-01-14T00:00:00Z", … -
Update model each time a view is generated in django
I'm trying to update my an instance of Post model each time a view PostDetail is generated. So far I've tried multiple approaches but none of them worked. I know that there is ready solution (django-hitcounter) but I would like to write one myself so I can understand what is happening. The goal there is to add 1 to post.views each time user accesses PostDetail view. models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) views = models.IntegerField(default=0) class Meta: ordering = ['-created_on'] views.py class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' urls.py urlpatterns = [ path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] -
Unable to load an audio file recorded using webRTC in django
I am currently working on a django project, in which i need to record the users audio and sent it to the server for processing. i have successfully recorded the audio using webRTC and passed it to views using an ajax request. But when i try to load the audio file using librosa for prosessing it gives an error for unknown file format. in my console i can clearly see that the wav file is received but it cannot load the file for processing to check what if i wrong with the file formats while recording tried different file formats which are supported by librosa and webRTC both audio/wav;codec=MS_PCM audio/wav;codec=MS_GSM610 to check if i had a problem with the file in receiving it on server i did upload the file on the server and i found that the file gets uploaded on the server and can be played on player directly. code that i used to upload the file and retrive it (note: i directly gave the path to the file to any recorded file just to check) def voice2(request): if request.method=='GET': return render(request,'record3.html') else: if request.method == 'POST' : print(request.FILES) audio=request.FILES.get("audioData") print(audio) file = request.FILES['audioData'] path = default_storage.save('media/somename.wav', ContentFile(file.read())) … -
Use JSON from flask with jinja in javascript
I have the following issue: I get from my mongodb an dict document, I parse it to json and pass it trough with jinja to my html page. I try to use this json document with the renderjson package. I have tried some solutions with quote the jinja object but it's working not properly. <div id="test"></div> <script type="text/javascript" src="static/renderjson.js"></script> <script> var str = "{{meta[1][0]}}" // meta is my list, the json object is the first element from flask document.getElementById("test").appendChild( renderjson(JSON.stringify(str)) ); </script> The json is valid. I am trying to use the renderjson package. https://github.com/caldwell/renderjson. If I use instead stringfy the parse method, nothing is displayed. How can I pass the json to the frontend properly? -
How to use data (view and url) of previous page in next page?
It is a bit hard to ask this question so, I will try to illustrate it through some pictures. I created the following interface for user to click add button and create new children of javascript (its parent). clicking add shows the following interface: Everything works good except that I have to manually choose JavaScript as parent of new child. I want to automate this process so user don't have to choose JavaScript as its parent, and it is taken from url automatically. This is my idea, but don't know how to do it. We already have the parent name in previous url: before clicking add button, if there is a way that I can send a portion of this url, namely JavaScript in our form so that form can use it somehow like this: class CatLevelThreeCreateView(CreateView): model = CatLevelThree template_name = 'cat-level-three-create.html' success_url = '/' fields = ['title', 'summary', 'image'] def form_valid(self, form): form.instance.levelThreeParent = self.kwargs.get('-------') # something instead of dashes! return super().form_valid(form) only if I am able to get the parent(in our example JavaSript) from somewhere the problem is solved! and above code will do its work! This is my bad idea, but if you know a better … -
Related Field got invalid lookup foreign key
i was writing the code for search request field which has a foreign key. so when i search for device command i should be able to get the command related to that device type but unfortunately it doesn't work i found a code online i did the similar way but when i search it doesn not return any result and my table is completely blank This is my code models.py class DeviceType(models.Model): devicetype = models.CharField(max_length=100) category = models.ForeignKey( Category, on_delete=models.CASCADE) def __str__(self): return self.devicetype class DeviceTypeCommand(models.Model): devicetypename = models.ForeignKey( DeviceType, on_delete=models.CASCADE) command = models.ForeignKey( Command, on_delete=models.CASCADE) def __str__(self): return self.devicetypename def get_absolute_urlwork(self): return reverse("edit_devicetypecommand", kwargs={"id": self.id}) forms.py class DeviceTypeCommandForm(BSModalForm): class Meta: model = DeviceTypeCommand fields = [ 'devicetypename', 'command', ] class DeviceTypeForm(BSModalForm): class Meta: model = DeviceType fields = [ 'devicetype', 'category', ] view.py def execute_selected(request, id=None): instance = get_object_or_404(Device, id=id) form = DeviceTypeCommandSearchForm(request.POST or None) queryset = DeviceTypeCommand.objects.all() context = { "form": form, "queryset": queryset, } if request.method == 'POST': queryset = DeviceTypeCommand.objects.filter(devicetypename__devicetype__icontains=form['devicetypename'].value()) context = { "queryset": queryset, "form": form, } return render(request, "selected_command.html", context) html file {% load static %} {% load crispy_forms_tags %} <!doctype html> <html lang="en"> <head> <title>Mannai Co.</title> <link href="{% static 'assets/other/bootstrap.min.css' %}" rel="stylesheet"> <link … -
RuntimeError: generator raised StopIteration
RuntimeError at /admin/products/category/add/ generator raised StopIteration Request Method: POST Request URL: http://0.0.0.0:9000/admin/products/category/add/ Django Version: 1.8.4 Exception Type: RuntimeError Exception Value: generator raised StopIteration Exception Location: /home/pyhub/.local/lib/python3.7/site-packages/django/http/multipartparser.py in read, line 337 Python Executable: /usr/bin/python3 Python Version: 3.7.5 Python Path: ['/home/pyhub/Desktop/deebaco/backend/backend', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/pyhub/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sun, 26 Jan 2020 12:19:05 +0000 -
I'm having an issue regarding AttributeError
AttributeError at /addpatient_to_db 'QuerySet' object has no attribute 'wardno' Request Method: POST Request URL: http://127.0.0.1:8000/addpatient_to_db Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'QuerySet' object has no attribute 'wardno' Exception Location: C:\Users\Saurabh Patil\Desktop\SanjeevniHospital\admininterface\views.py in addpatient_to_db, line 114 Python Executable: C:\Users\Saurabh Patil\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\Saurabh Patil\Desktop\SanjeevniHospital', 'C:\Users\Saurabh ' 'Patil\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\Saurabh Patil\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\Saurabh Patil\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\Saurabh Patil\AppData\Local\Programs\Python\Python37', 'C:\Users\Saurabh Patil\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\Saurabh ' 'Patil\AppData\Local\Programs\Python\Python37\lib\site-packages'] Server time: Sun, 26 Jan 2020 12:07:40 +0000 Here is my code ----------------------------- views.py def addpatient_to_db(request): if request.method == 'POST': name = request.POST['name'] age = request.POST['age'] sex = request.POST['sex'] address = request.POST['address'] contno = request.POST['contno'] wardno = request.POST['wardno'] bedno = request.POST['bedno'] doa = request.POST['doa'] docass = request.POST['docass'] pii = request.POST['pii'] alldata = patientdetails.objects.all() if alldata.wardno == wardno and alldata.bedno == bedno: # <---- This is the issuing line return render(request, "addpatient.html") else: addp = patientdetails(name=name, age=age, sex=sex, address=address, mobno=contno, wardno=wardno, bedno=bedno, dateofallot=doa, docass=docass, illness_issue=pii) addp.save() return redirect('addpatient') else: return render(request, 'addpatient.html') models.py from django.db import models # Create your models here. class patientdetails(models.Model): name = models.CharField(max_length=50) age = models.CharField(max_length=3) sex = models.CharField(max_length=10) address = models.CharField(max_length=100) mobno = models.CharField(max_length=10) wardno = models.CharField(max_length=3) bedno = models.CharField(max_length=3) dateofallot = models.CharField(max_length=10) docass = models.CharField(max_length=50) illness_issue = models.CharField(max_length=50) -
Django: Treat form field before validation
I have a form that has the following datetime field: Forms.py class FormBacktest(forms.Form): dateStart = forms.DateTimeField(label="Date Start") def to_python(self, dateStart): return serialize_datetime(dateStart) When the user submits the form, dateStart is a string. I want to serialize the field on the backend side before validation. To do so, I've found in the documentation that the method save_<Field> won't work, since it's executed after all_clean_data. I could also use the method to_python, but it is not exactly what i'm looking for : This method accepts the raw value from the widget and returns the converted value. Even so, I've tried to use it, but the function is never called. My view looks like this: Views.py def view(request): if request.method == "POST": backtestForm = FormBacktest(request.POST) if backtestForm.is_valid(): # blabla What is the best strategy to treat the data before validation? -
Django wrongly converting float x.xx to x,xx in template
I have a problem with my Django website. I'm passing a variable latitude_actuelle corresponding to a latitude from a view to a template. When I print the variable in the view, it's a float in a correct format x.xx. But when I display the variable in the template with {{ latitude_actuelle }}, the dot has been replaced by a comma : x,xx which is not a correct format for a float. The problem is that I need the float to be in a correct format in order to center a google map at the given latitude and longitude using javascript in the template. I thought about modifying the variable in the script with something like this : var lat_actuelle = {{ latitude_actuelle }} use float(lat_actuelle.replace(',','.')) But it looks like we cannot access template variables this way in javascript. Is there a way to disable the wrong conversion of the float from x.xx to x,xx ? And if not, how can I solve the problem ? Thanks in advance ! Here are the relevant part of my file if needed : view def infos_localisation(request): latitude_actuelle = 50.66981991272638 longitude_actuelle = 4.615554319641566 point = request.user.useradvanced.localisation if point != None: latitude_actuelle = float(point.y) longitude_actuelle … -
Django Post request not sent on button click?
i am new to Django, I am trying to create simple web page which sends ajax request when button is clicked. But post request is not sent template <form action="" method="post" id="post-form" enctype="multipart/form-data"> {% csrf_token %} <select id="select_dropdown"> <option value="joshua">joshua</option> <option value="peter">peter</option> </select> <input type="button" method = "POST" value="Apply" id="submitme" name="submitme"> </form>. <script src="{% static 'js/jquery-3.4.1.js' %}"></script> <script src="{% static 'js/bootstrap.js' %}"></script> {% csrf_token %} <script language="JavaScript"> $( document ).ready(function() { $('#submitme').click(function(e){ e.preventDefault(); var p = document.getElementById("select_dropdown"); var value = p.options[e.selectedIndex].value; $.ajax({ url: window.location.href, type: "post", // or "get" data: value, headers: {'X-CSRFToken': '{{ csrf_token }}'}, // for csrf token success: function(data) { window.location.replace("/video_courses/"); alert(data.result); }}); }); }); </script> view.py if request.method == "POST": # os request.GET() print("inside post") get_value = request.body data = {} data['result'] = 'you made a request' return HttpResponse(json.dumps(data), content_type="application/json") Please help -
У меня возникла ошибка: 'int' object is not iterable'
Я хочу, чтобы по гипер-ссылке можно было преходить на страницу для отдельного поста. Это осуществляется путем получения id каждого обьекта Post с помощью цикла for. Но почему-то, используя метод в new_blog.urls, у меня возникает такая ошибка. Фото шаблонов, views прилагаются: <div> <h1><a href="/">Post List</a></h1> </div> <ul> {% for post in posts%} <li> <a href="{%url 'post_detail' post.id %}">{{post.title}}</a> </li> <p> {{post.body}} </p> <p>published:{{post.publish}} </p> {% endfor %} </ul> from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.objects.filter(status = 'draft').order_by('status') context = {'slug':Post.slug, 'posts':posts,} return render(request, 'new_blog/index.html', context) def post_detail(request, post_id): post = get_object_or_404(Post, post_id) return render(request, 'new_blog/detail.html', {'post': post}) -
Django and Google Drive API Integration
In django, How user uploads files to the site without stored to the site, but uploaded immediately instead to google drive. How to put files which i got from request.FILES[file] into the code below: media = MediaFileUpload('files/photo.jpg',mimetype='image/jpeg') Thanks -
how to plot a pandas dataframe using google chart
I have a pandas dataframe like this and passed to django template real=dailycust['2017-01-01':].to_html() return render(request,'abc.html',{'data':real}) In the template i need to convert the table into google linechart i think {{data | safe}} is not recognizing in the code. <html> <head> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable({{data | safe}}); data.addColumn('datetime','date'); data.addColumn('number','number of customers'); var options = { title: 'Company Performance', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <div id="curve_chart" style="width: 900px; height: 500px"></div> </body> </html> but something is wrong with it. -
Visual Studio 2019 does not find python tests (pytest or unittest)
I just started a Django project with Visual Studio 2019 (v 16.4.3) to get familiar with it and I am seeing that the unit tests are not being discovered. Visual Studio allows to add a unittest python file, that contains a file that should fail when run, so I am pretty sure that it should be discoverable: import unittest class Test_test_1(unittest.TestCase): def test_A(self): self.fail("Not implemented") if __name__ == '__main__': unittest.main() I also tried to change the settings in Project/Properties and tried with both pytest and unittest, but the result is the same: (of course clicking "Run All" doesn't discover anything) Is it a known Visual Studio problem? Or am I placing the files in the wrong path? Any hint about what I am doing wrong here? p.s. I saw another question on SO about this, but this guy was getting an error. I just get nothing at all. -
How to add comments to a Django post
After adding this code to admin.py, I was expecting to see a Comments section under Blog on the Site Administration Page. To the best of my knowledge, I have run the appropriate migrations. I have looked at posts on Stack Overflow but still have not figured out the answer. from django.contrib import admin #register our models so they show up on our admin page from .models import Post, Comment admin.site.register(Post) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'created_on', 'active') list_filter = ('active', 'created_on') search_fields = ('name', 'email', 'body') actions = ['approve_comments'] def approve_comments(self, request, queryset): queryset.update(active=True) -
Showing user-uploaded images in a template
I have added all necessary code to settins.py (MEDIA_URL, MEDIA_ROOT and django.template.context_processors.media). I've also created a model for an image class Image(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) file = models.ImageField(upload_to="polls/") author = models.CharField(max_length = 60, default = "Unknown") So when I upload a picture via the admin panel django saves them to mysite/media/pollsHow do I access the images from a template now? I tried a lot and the closed attempt seems to be {% if question.image_set %} {% for image in question.image_set.all %} <img src="{{ MEDIA_URL }}{{ image.file }}"> {% endfor %} {% endif %} The result of this template is something like <img src="media/polls/rabstol_net_china_04_1600x1200.jpg"> the path seems to be correct, but the image doesn't appear. I suppose it's because the result is a relative path, but I don't know how to make it an absolute. -
Post html table row data from multiple rows at a time to django model
I have a table which is created after a user has selected a number of items from a list. If the user is happy with their selected items, they can submit the items to the backend where i need the items to be saved into the model. I use javascript to render the selected items in the new table. (Code Below) The data is from a Map where the keys are PKs and the values are objects with the description and price data. function logMapElements(value, key, map) { var newRow = document.createElement("tr"); var itemPK = document.createElement("td"); itemPK.setAttribute('class', 'id'); itemPK.textContent = key newRow.appendChild(itemPK); var itemDescription = document.createElement("td",); itemDescription.textContent = value.item newRow.appendChild(itemDescription); var itemPrice = document.createElement("td"); itemPrice.textContent = value.price newRow.appendChild(itemPrice); selectedItemsTableBody.appendChild(newRow); } }); The HTML table; <div class="table-responsive"> <table class="table table-borderless" id="selected_items_table"> <thead> <tr> <th>Description</th> <th>Price</th> <th>Remove</th> </tr> </thead> <form action="" method="POST"> {% csrf_token %} <tbody id="selectedItemsTable"> <!-- THE SELECTED ITEMS ARE RENDERED HERE --> </tbody> </form> </table> </div> My Django Model class Selected(models.Model): foreignKey = models.CharField(max_length=5) description = models.CharField(max_length=20) price = models.DecimalField(max_digits=5, decimal_places=2) Im not sure exactly how to write the view to save the data from the rows into the model. Or if i should be writing it in my … -
Python assertEqual two objects except one key
I need to test a function which will return an object with rest_framework.test.APITestCase's assertEqual in django. The object is something like this: { "first_name": "John", "last_name": "Doe", "random": some random number } How can I check the returned object with my suitable result except the random key? I mean assertEqual(a, result) should return True if these two objects are passed: a = { "first_name": "John", "last_name": "Doe", "random": 12 } result = { "first_name": "John", "last_name": "Doe", "random": 24 } Is there anyway to make this kind of exceptions in assertEqual or I have to use assert? -
Running unit tests throws error in django (Can't create create table . `#sql-6bf3_641` (errno: 150 "Foreign key constraint is incorrectly formed
I've been working on a Django project for 3 years and now I've planned to write test cases for future functionality. Now whenever I run (./manage.py test), I get following exception: "django.db.utils.OperationalError: (1005, 'Can\'t create table `test_mpd_db`.`#sql-6bf3_641` (errno: 150 "Foreign key constraint is incorrectly formed")')" Here is the full error log: Traceback (most recent call last): File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/MySQLdb/cursors.py", line 412, in _query rowcount = self._do_query(q) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/MySQLdb/cursors.py", line 375, in _do_query db.query(q) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1005, 'Can\'t create table `test_mpd_db`.`#sql-6bf3_641` (errno: 150 "Foreign key constraint is incorrectly formed")') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/rashid/.virtualenvs/paydo/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, …